diff options
Diffstat (limited to 'cdf/src')
44 files changed, 3125 insertions, 0 deletions
diff --git a/cdf/src/cdf-prop-value/README.md b/cdf/src/cdf-prop-value/README.md new file mode 100644 index 0000000..f83617e --- /dev/null +++ b/cdf/src/cdf-prop-value/README.md @@ -0,0 +1,53 @@ +org.onap.dcae.cdf [^1] +====================== + +This repository contails two modules: +* `cdf-util`: a port of the support functions needed to support CdfPortValue command +* `cdf-prop-value` : contains only the CdfPortValue command + +## Building + +To build: +* `cd cdf-util-build; mvn package` + +## Usage + +Command: `/opt/cdf/bin/getpropvalue` + +`/opt/cdf/bin/getpropvalue [-x] -n property -f property-file` + Extract the named value from the given property-file (or full pathname[^2]) + +`/opt/cdf/bin/getpropvalue -e method [-n property] [-s salt] -v value` + Encrypt the given property with the given name and value + +`/opt/cdf/bin/getpropvalue -u value` + Decrypt the given value, expressed as a triple METHOD:HEXSALT:HEXVAL + +`/opt/cdf/bin/setencryptedvalues` (same as `/opt/cdf/bin/getpropvalue -E`) + Encrypt all lines that look like ENCRYPTME.METHOD.name=value + +## Examples + + # using config files: + + # echo ENCRYPTME.AES.input=bogus | /opt/cdf/bin/setencryptedvalues > testconfig.txt + + # cat testconfig.txt + input.x=AES:353438323235:bf046d8a3e8b12fb678f5dec1e9d5743 + + # /opt/cdf/bin/getpropvalue -x -n input -f /home/ht1659/src/cdf/testconfig.txt + bogus + + # No file: + + # /opt/cdf/bin/getpropvalue -e AES -v bogus + AES:34383638353831:0e699f0f818593e3adbc642efed20341 + + # /opt/cdf/bin/getpropvalue -u AES:323937323833:8d95d8803978c4b13497b394d56a4a9c + bogus + + + +[^1]: Version 1.0, 24 Dec 2015 + +[^2]: The property-file valued currently requires a rooted (full) pathname. diff --git a/cdf/src/cdf-prop-value/buildjars/gnu_getopt.jar b/cdf/src/cdf-prop-value/buildjars/gnu_getopt.jar Binary files differnew file mode 100644 index 0000000..8105152 --- /dev/null +++ b/cdf/src/cdf-prop-value/buildjars/gnu_getopt.jar diff --git a/cdf/src/cdf-prop-value/cdf-prop-value/pom.xml b/cdf/src/cdf-prop-value/cdf-prop-value/pom.xml new file mode 100644 index 0000000..43fcf50 --- /dev/null +++ b/cdf/src/cdf-prop-value/cdf-prop-value/pom.xml @@ -0,0 +1,28 @@ +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <groupId>org.onap.dcae.cdf</groupId> + <artifactId>cdf-prop-value</artifactId> + <packaging>jar</packaging> + <version>1.0-SNAPSHOT</version> + <name>cdf-prop-value</name> + <url>http://maven.apache.org</url> + + <dependencies> + <dependency> + <groupId>org.onap.dcae.cdf</groupId> + <artifactId>cdf-util</artifactId> + <version>1.0-SNAPSHOT</version> + </dependency> + + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <version>3.8.1</version> + <scope>test</scope> + </dependency> + + </dependencies> + +</project> diff --git a/cdf/src/cdf-prop-value/cdf-prop-value/src/main/java/.gitignore b/cdf/src/cdf-prop-value/cdf-prop-value/src/main/java/.gitignore new file mode 100644 index 0000000..863d673 --- /dev/null +++ b/cdf/src/cdf-prop-value/cdf-prop-value/src/main/java/.gitignore @@ -0,0 +1 @@ +javadoc diff --git a/cdf/src/cdf-prop-value/cdf-prop-value/src/main/java/javadocs.built b/cdf/src/cdf-prop-value/cdf-prop-value/src/main/java/javadocs.built new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/cdf/src/cdf-prop-value/cdf-prop-value/src/main/java/javadocs.built diff --git a/cdf/src/cdf-prop-value/cdf-prop-value/src/main/java/makefile b/cdf/src/cdf-prop-value/cdf-prop-value/src/main/java/makefile new file mode 100644 index 0000000..f3deade --- /dev/null +++ b/cdf/src/cdf-prop-value/cdf-prop-value/src/main/java/makefile @@ -0,0 +1,31 @@ +go=../../../../buildjars/gnu_getopt.jar +cu=../../../../cdf-util/src/main/java/cdf-util.jar + +.SUFFIXES= .class + +JAVA=org/onap/dcae/cdf/CdfPropValue.java +CLASSES=$(JAVA:.java=.class) + +all: + +build: cdf-prop-value.jar + +classes: $(CLASSES) + +clean: + find . -name '*.class' -exec rm -f {} + + rm -rf javadoc javadoc.built + +cdf-prop-value.jar: $(CLASSES) + rm -f cdf-prop-value.jar + jar cvf cdf-prop-value.jar $(CLASSES) + +$(CLASSES): $(JAVA) + javac -cp $(go):$(cu) $(JAVA) + +javadocs: javadocs.built +javadocs.built: cdf-prop-value.jar + rm -rf javadoc + mkdir -p javadoc + javadoc -d javadoc -classpath $(go):$(cu) $(JAVA) + touch javadocs.built diff --git a/cdf/src/cdf-prop-value/cdf-prop-value/src/main/java/org/onap/dcae/cdf/.gitignore b/cdf/src/cdf-prop-value/cdf-prop-value/src/main/java/org/onap/dcae/cdf/.gitignore new file mode 100644 index 0000000..6b468b6 --- /dev/null +++ b/cdf/src/cdf-prop-value/cdf-prop-value/src/main/java/org/onap/dcae/cdf/.gitignore @@ -0,0 +1 @@ +*.class diff --git a/cdf/src/cdf-prop-value/cdf-prop-value/src/main/java/org/onap/dcae/cdf/CdfPropValue.java b/cdf/src/cdf-prop-value/cdf-prop-value/src/main/java/org/onap/dcae/cdf/CdfPropValue.java new file mode 100644 index 0000000..cd9a51c --- /dev/null +++ b/cdf/src/cdf-prop-value/cdf-prop-value/src/main/java/org/onap/dcae/cdf/CdfPropValue.java @@ -0,0 +1,86 @@ +/* + Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this code except in compliance + with the License. You may obtain a copy of the License + at http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied. See the License for the specific language governing + permissions and limitations under the License. + +*/ +package org.onap.dcae.cdf; + +import org.onap.dcae.cdf.util.config.PropValue; +import java.util.logging.Logger; +import org.onap.dcae.cdf.util.config.Configuration; +import java.io.InputStream; +import java.io.PrintStream; + +public class CdfPropValue extends PropValue { + public static String getCDFHOME() { + String optCdf = System.getProperty("CDF_HOME"); + if (optCdf == null) optCdf = System.getenv("CDF_HOME"); + if (optCdf == null) optCdf = "/opt/app/cdf"; + return optCdf; + } + + public static String getGLOBALPROPFILE() { + String optCdfCfg = System.getProperty("CDF_CFG"); + if (optCdfCfg == null) optCdfCfg = System.getenv("CDF_CFG"); + if (optCdfCfg == null) optCdfCfg = getCDFHOME() + "/lib/cdf.cfg"; + return optCdfCfg; + } + + public static void init() { + PropValue.setGlobalPropFile(getGLOBALPROPFILE()); + PropValue.setEncryptionKeyProperty("Global_Title"); + } + static { + init(); + } + + public static void printEncryptedProperty(String method, String name, String salt, String value, String globalPropFile) { + PropValue.printEncryptedProperty(method, name, salt, value, globalPropFile); + } + public static String generateEncryptedProperty(String method, String salt, String value, String globalPropFile) throws Exception { + return PropValue.generateEncryptedProperty(method, salt, value, globalPropFile); + } + public static String generateEncryptedProperty(String method, String salt, String value, PropValue propValue) throws Exception { + return PropValue.generateEncryptedProperty(method, salt, value, propValue); + } + public static void extractProperty(String f, String name, boolean encrypted) { + PropValue.extractProperty(f, name, encrypted); + } + public static void extractProperty(String f, String name, boolean encrypted, String globalPropFile) { + PropValue.extractProperty(f, name, encrypted, globalPropFile); + } + public static String decryptTriple(String triple, String globalPropFile) { + return PropValue.decryptTriple(triple, globalPropFile); + } + public static String decryptTriple(String triple, PropValue propValue) { + return PropValue.decryptTriple(triple, propValue); + } + public static void encryptInput(InputStream in, PrintStream out) throws Exception { + PropValue.encryptInput(in, out); + } + public static void encryptInput() throws Exception { + PropValue.encryptInput(); + } + public static void encryptInput(String globalPropFile, InputStream sysin, PrintStream sysout) throws Exception { + PropValue.encryptInput(globalPropFile, sysin, sysout); + } + public static void main(String args[]) throws Exception { + PropValue.main(args); + } + + + public CdfPropValue(Configuration globalConfig, Logger logger) { + super(globalConfig, logger); + } + +} diff --git a/cdf/src/cdf-prop-value/cdf-prop-value/src/test/java/org/onap/dcae/cdf/cdfpropvalue/AppTest.java b/cdf/src/cdf-prop-value/cdf-prop-value/src/test/java/org/onap/dcae/cdf/cdfpropvalue/AppTest.java new file mode 100644 index 0000000..64753bd --- /dev/null +++ b/cdf/src/cdf-prop-value/cdf-prop-value/src/test/java/org/onap/dcae/cdf/cdfpropvalue/AppTest.java @@ -0,0 +1,53 @@ +/* + Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this code except in compliance + with the License. You may obtain a copy of the License + at http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied. See the License for the specific language governing + permissions and limitations under the License. + +*/ +package org.onap.dcae.cdf.cdfpropvalue; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +/** + * Unit test for simple App. + */ +public class AppTest + extends TestCase +{ + /** + * Create the test case + * + * @param testName name of the test case + */ + public AppTest( String testName ) + { + super( testName ); + } + + /** + * @return the suite of tests being tested + */ + public static Test suite() + { + return new TestSuite( AppTest.class ); + } + + /** + * Rigourous Test :-) + */ + public void testApp() + { + assertTrue( true ); + } +} diff --git a/cdf/src/cdf-prop-value/cdf-util/pom.xml b/cdf/src/cdf-prop-value/cdf-util/pom.xml new file mode 100644 index 0000000..ed89368 --- /dev/null +++ b/cdf/src/cdf-prop-value/cdf-util/pom.xml @@ -0,0 +1,26 @@ +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <groupId>org.onap.dcae.cdf</groupId> + <artifactId>cdf-util</artifactId> + <packaging>jar</packaging> + <version>1.0-SNAPSHOT</version> + <name>cdf-util</name> + <url>http://maven.apache.org</url> + + <dependencies> + <dependency> + <groupId>gnu.getopt</groupId> + <artifactId>java-getopt</artifactId> + <version>1.0.13</version> + </dependency> + + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <version>3.8.1</version> + <scope>test</scope> + </dependency> + </dependencies> +</project> diff --git a/cdf/src/cdf-prop-value/cdf-util/src/main/java/.gitignore b/cdf/src/cdf-prop-value/cdf-util/src/main/java/.gitignore new file mode 100644 index 0000000..863d673 --- /dev/null +++ b/cdf/src/cdf-prop-value/cdf-util/src/main/java/.gitignore @@ -0,0 +1 @@ +javadoc diff --git a/cdf/src/cdf-prop-value/cdf-util/src/main/java/makefile b/cdf/src/cdf-prop-value/cdf-util/src/main/java/makefile new file mode 100644 index 0000000..268770c --- /dev/null +++ b/cdf/src/cdf-prop-value/cdf-util/src/main/java/makefile @@ -0,0 +1,49 @@ + +go=../../../../buildjars/gnu_getopt.jar + +.SUFFIXES= .class + +JAVA= org/onap/dcae/cdf/util/common/Classify.java \ + org/onap/dcae/cdf/util/common/Tuple3.java \ + org/onap/dcae/cdf/util/common/AsHex.java \ + org/onap/dcae/cdf/util/common/G2CookieGen.java \ + org/onap/dcae/cdf/util/common/Compress.java \ + org/onap/dcae/cdf/util/common/Pair.java \ + org/onap/dcae/cdf/util/common/Tuple4.java \ + org/onap/dcae/cdf/util/common/Hostname.java \ + org/onap/dcae/cdf/util/common/Uid.java \ + org/onap/dcae/cdf/util/common/Tuple2.java \ + org/onap/dcae/cdf/util/common/Pid.java \ + org/onap/dcae/cdf/util/common/Convert.java \ + org/onap/dcae/cdf/util/common/Popen.java \ + org/onap/dcae/cdf/util/config/PropValue.java \ + org/onap/dcae/cdf/util/config/Configuration.java \ + org/onap/dcae/cdf/util/config/EncryptedConfiguration.java \ + org/onap/dcae/cdf/util/config/Configurable.java \ + org/onap/dcae/cdf/util/config/ConfigurationRegistry.java \ + org/onap/dcae/cdf/util/threads/TaskThread.java \ + org/onap/dcae/cdf/util/threads/ThreadUtils.java + +CLASSES=$(JAVA:.java=.class) + +all: + +build: cdf-util.jar + +cdf-util.jar: $(CLASSES) + rm -f cdf-util.jar + jar cvf cdf-util.jar $(CLASSES) + +clean: + find . -name '*.class' -exec rm -f {} + + rm -rf javadoc javadocs.built + +$(CLASSES): $(JAVA) + javac -cp $(go) $(JAVA) + +javadocs: javadocs.built +javadocs.built: cdf-util.jar + rm -rf javadoc + mkdir -p javadoc + javadoc -d javadoc -classpath $(go) $(JAVA) + touch javadocs.built diff --git a/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/common/.gitignore b/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/common/.gitignore new file mode 100644 index 0000000..6b468b6 --- /dev/null +++ b/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/common/.gitignore @@ -0,0 +1 @@ +*.class diff --git a/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/common/AsHex.java b/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/common/AsHex.java new file mode 100644 index 0000000..05d8f37 --- /dev/null +++ b/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/common/AsHex.java @@ -0,0 +1,116 @@ +/* + Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this code except in compliance + with the License. You may obtain a copy of the License + at http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied. See the License for the specific language governing + permissions and limitations under the License. + +*/ +package org.onap.dcae.cdf.util.common; + +public class AsHex +{ + public static String asHex(byte[] data, int offset, int length, String sep) { + return asHex(data, offset, length, true); + } + public static String asHex(byte[] data, String sep) { + return asHex(data, 0, data.length, sep); + } + public static String asHex(byte[] data, int offset, int length) { + return asHex(data, offset, length, " "); + } + public static String asHex(byte[] data) { + return asHex(data, 0, data.length); + } + + public static String asHex(String data) { + return asHex(data.getBytes()); + } + + static private int asHexBlockLength = 16; + public static void setAsHexBlockLength(int n) { asHexBlockLength = n; } + public static int getAsHexBlockLength() { return asHexBlockLength; } + + private final static char[] hexdigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; + + /** + * return a byte buf as a hex string + */ + public static String asHex(byte[] buf, int offset, int length, boolean addFinalNL) { + StringBuilder ret = new StringBuilder(); + return asHex(ret, buf, offset, length, addFinalNL).toString(); + } + + /** + * Return a byte buf as hex into the provided StringBuilder. + */ + public static StringBuilder asHex(StringBuilder ret, byte[] buf, int offset, int length, boolean addFinalNL) { + final int blockLength = asHexBlockLength; + for (int o = 0; o < length; o += blockLength) { + int iend = (o + blockLength < length) ? (o + blockLength) : length; + int pend = o + blockLength; + for (int i = o; i < iend; i++) { + int b = (int)(buf[i+offset] & 0xFF); + ret.append(hexdigits[b/16]); + ret.append(hexdigits[b%16]); + } + for (int i = iend; i < pend; i++) { + ret.append(" "); + } + ret.append(" "); + for (int i = o; i < iend; i++) { + byte b = buf[i+offset]; + int ib = (int)(b & 0xFF); + if ((ib >= 0x20) && (ib < 0x7f)) ret.append((char)b); + else ret.append('.'); + } + if (iend < length) ret.append('\n'); + } + if (addFinalNL && (length%blockLength != 0)) ret.append('\n'); + return ret; + } + + /** + * Return a byte buf as hex with a maximum number of lines. + */ + public static String asHexWithMaxLines(byte[] buf, int offset, int length, int maxLines, boolean addFinalNL) { + StringBuilder ret = new StringBuilder(); + return asHexWithMaxLines(ret, buf, offset, length, maxLines, addFinalNL).toString(); + } + + /** + * Return a byte buf as hex into the provided StringBuilder with a maximum number of lines. + */ + public static StringBuilder asHexWithMaxLines(StringBuilder ret, byte[] buf, int offset, int length, int maxLines, boolean addFinalNL) { + int bytesToPrint = length - offset; + if (maxLines < 1) maxLines = 1; + int maxBytesToPrint = maxLines * asHexBlockLength; + if (bytesToPrint <= maxBytesToPrint) { + return asHex(ret, buf, offset, length, addFinalNL); + } else { + if (bytesToPrint > maxBytesToPrint) bytesToPrint = maxBytesToPrint; + asHex(ret, buf, offset, offset + bytesToPrint, false); + ret.append(" ...."); + if (addFinalNL) ret.append("\n"); + return ret; + // return asHex(ret, buf, length - halfBytesToPrint, length, addFinalNL); + } + } + + // Convert a hex string back to a byte array. + // This assumes that there is no whitespace within the string. + // public static byte[] fromHex(String hexStr) { + // byte[] bts = new byte[hexStr.length() / 2]; + // for (int i = 0; i < bts.length; i++) { + // bts[i] = (byte) Integer.parseInt(hexStr.substring(2*i, 2*i+2), 16); + // } + // return bts; + // } +} diff --git a/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/common/Classify.java b/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/common/Classify.java new file mode 100644 index 0000000..e0b9203 --- /dev/null +++ b/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/common/Classify.java @@ -0,0 +1,109 @@ +/* + Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this code except in compliance + with the License. You may obtain a copy of the License + at http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied. See the License for the specific language governing + permissions and limitations under the License. + +*/ +package org.onap.dcae.cdf.util.common; + +import java.lang.Character; + +/** + * Classify holds various checking functions. + */ +public final class Classify { + + /** + * isHex(ch) - is a character a hex value? + * + * @param ch (char) + * @return boolean + */ + public static boolean isHex(char ch) { + return (ch >= '0' && ch <= '9') || + (ch >= 'A' && ch <= 'F') || + (ch >= 'a' && ch <= 'f'); + } + + /** + * isValidGuid + * + * @param input (String) + * @return boolean + */ + + public static boolean isValidGuid(String input) { + // Checks if the GUID has the following format: "0f114b6f-3f1d-4c8f-a065-2a2ec3d0f522" + + if ( (input == null) || (input.length() != 36)) return false; + + for (int i=0; i < 36; i++) { + char c = input.charAt(i); + if ( (i==8 || i==13 || i==18 || i==23)) { + if (c != '-') return false; + } + else if (!isHex(c)) return false; + } + return true; + } + + + /** + * isValidClli + * + * @param input (String) + * @return boolean + */ + + public static boolean isValidClli(String input) { + // Checks if the CLLI only contains letters or digits. + + if (input == null) return false; + int len = input.length(); + if (len == 0) return false; + + for (int i=0; i < len; i++) { + char c = input.charAt(i); + if (!Character.isLetterOrDigit(c)) return false; + } + return true; + } + + + /** + * isValidCanonicalIpv4Address + * + * @param ipAddress (String) + * @return boolean + */ + + public static boolean isValidCanonicalIpv4Address(String ipAddress) { + + String[] parts = ipAddress.split( "\\." ); + + if ( parts.length != 4 ) { + return false; + } + for ( String s : parts ) { + try { + int i = Integer.parseInt( s ); + if ( (i < 0) || (i > 255) ) { + return false; + } + } catch (Exception ex) { + return false; + } + } + + return true; + } +} diff --git a/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/common/Compress.java b/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/common/Compress.java new file mode 100644 index 0000000..86ff60b --- /dev/null +++ b/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/common/Compress.java @@ -0,0 +1,131 @@ +/* + Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this code except in compliance + with the License. You may obtain a copy of the License + at http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied. See the License for the specific language governing + permissions and limitations under the License. + +*/ +package org.onap.dcae.cdf.util.common; + +import java.util.zip.GZIPOutputStream; +import java.util.zip.ZipOutputStream; +import java.util.zip.ZipEntry; +// import java.io.InputStream; +import java.io.FileOutputStream; +import java.io.FileInputStream; +import java.io.File; +import java.io.IOException; + +public class Compress { + + /** + * Compress a file with the gzip algorithm, sending output to outFilename. + * Based on code at http://www.java-tips.org/java-se-tips/java.util.zip/how-to-compress-a-file-in-the-gip-format.html. + */ + public static void gzip(String inFilename, String outFilename) throws IOException { + String tmpFilename = outFilename + ".tmp"; + try { + // Create the GZIP output stream + GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(tmpFilename)); + + // Open the input file + FileInputStream in = new FileInputStream(inFilename); + + // Transfer bytes from the input file to the GZIP output stream + byte[] buf = new byte[4096]; + int len; + while ((len = in.read(buf)) > 0) { + out.write(buf, 0, len); + } + in.close(); + + // Complete the GZIP file + out.finish(); + out.close(); + + // rename .gz.tmp to .gz + File target = new File(outFilename); + if (target.exists()) target.delete(); + File file = new File(tmpFilename); + boolean result = file.renameTo(target); + if (!result) throw new IOException("Cannot rename " + tmpFilename + " to " + outFilename); + } catch (IOException e) { + // If we can't write the gzip file, remove it and pass on the exception. + File f = new File(outFilename); + f.delete(); + throw e; + } + } + + /** + * Compress a file with the gzip algorithm, sending output to filename+".gz". + */ + public static void gzip(String filename) throws IOException { + gzip(filename, filename + ".gz"); + } + + /** + * Compress a file with the zip algorithm, sending output to outFilename + * Based on code at http://www.java-tips.org/java-se-tips/java.util.zip/how-to-compress-a-file-in-the-gip-format.html. + */ + public static void zip(String inFilename, String outFilename) throws IOException { + String tmpFilename = outFilename + ".tmp"; + try { + // Create the ZIP output stream + ZipOutputStream out = new ZipOutputStream(new FileOutputStream(tmpFilename)); + ZipEntry zipEntry = new ZipEntry(inFilename); + out.putNextEntry(zipEntry); + + // Open the input file + FileInputStream in = new FileInputStream(inFilename); + + // Transfer bytes from the input file to the ZIP output stream + byte[] buf = new byte[4096]; + int len; + while ((len = in.read(buf)) > 0) { + out.write(buf, 0, len); + } + in.close(); + + // Complete the ZIP file + out.finish(); + out.close(); + + // rename .zip.tmp to .zip + File target = new File(outFilename); + if (target.exists()) target.delete(); + File file = new File(tmpFilename); + boolean result = file.renameTo(target); + if (!result) throw new IOException("Cannot rename " + tmpFilename + " to " + outFilename); + } catch (IOException e) { + // If we can't write the zip file, remove it and pass on the exception. + File f = new File(outFilename); + f.delete(); + throw e; + } + } + + /** + * Compress a file with the gzip algorithm, sending output to filename+".zip". + */ + public static void zip(String filename) throws IOException { + zip(filename, filename + ".zip"); + } + + public static void main(String args[]) throws Exception { + if (args.length == 1) { + gzip(args[0]); + zip(args[0]); + } else { + System.err.println("Usage: java Compress filename"); + } + } +} diff --git a/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/common/Convert.java b/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/common/Convert.java new file mode 100644 index 0000000..6182fde --- /dev/null +++ b/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/common/Convert.java @@ -0,0 +1,97 @@ +/* + Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this code except in compliance + with the License. You may obtain a copy of the License + at http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied. See the License for the specific language governing + permissions and limitations under the License. + +*/ +package org.onap.dcae.cdf.util.common; + +import java.lang.Character; + +/** + * Covert holds various conversion functions. + */ +public final class Convert { + + private static final char[] HEX_CHARS = "0123456789abcdef".toCharArray(); + + /** + * toHexString(String) - convert a string into its hex equivalent + */ + public static String toHexString(String buf) { + if (buf == null) return ""; + return toHexString(buf.getBytes()); + } + + /** + * toHexString(byte[]) - convert a byte-string into its hex equivalent + */ + public static String toHexString(byte[] buf) { + if (buf == null) return ""; + char[] chars = new char[2 * buf.length]; + for (int i = 0; i < buf.length; ++i) { + chars[2 * i] = HEX_CHARS[(buf[i] & 0xF0) >>> 4]; + chars[2 * i + 1] = HEX_CHARS[buf[i] & 0x0F]; + } + return new String(chars); + } + + // alternate implementation that's slightly slower + // protected static final byte[] Hexhars = { + // '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' + // }; + // public static String encode(byte[] b) { + // StringBuilder s = new StringBuilder(2 * b.length); + // for (int i = 0; i < b.length; i++) { + // int v = b[i] & 0xff; + // s.append((char)Hexhars[v >> 4]); + // s.append((char)Hexhars[v & 0xf]); + // } + // return s.toString(); + // } + + /** + * Convert a hex string to its equivalent value. + */ + public static String stringFromHex(String hexString) throws Exception { + if (hexString == null) return ""; + return stringFromHex(hexString.toCharArray()); + } + + public static String stringFromHex(char[] hexCharArray) throws Exception { + if (hexCharArray == null) return ""; + return new String(bytesFromHex(hexCharArray)); + } + + public static byte[] bytesFromHex(String hexString) throws Exception { + if (hexString == null) return new byte[0]; + return bytesFromHex(hexString.toCharArray()); + } + + public static byte[] bytesFromHex(char[] hexCharArray) throws Exception { + if (hexCharArray == null) return new byte[0]; + int len = hexCharArray.length; + if ((len % 2) != 0) throw new Exception("Odd number of characters: '" + hexCharArray + "'"); + byte [] txtInByte = new byte [len / 2]; + int j = 0; + for (int i = 0; i < len; i += 2) { + txtInByte[j++] = (byte)(((fromHexDigit(hexCharArray[i], i) << 4) | fromHexDigit(hexCharArray[i+1], i)) & 0xFF); + } + return txtInByte; + } + + protected final static int fromHexDigit(char ch, int index) throws Exception { + int digit = Character.digit(ch, 16); + if (digit == -1) throw new Exception("Illegal hex character '" + ch + "' at index " + index); + return digit; + } +} diff --git a/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/common/G2CookieGen.java b/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/common/G2CookieGen.java new file mode 100644 index 0000000..738fb3c --- /dev/null +++ b/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/common/G2CookieGen.java @@ -0,0 +1,209 @@ +/* + Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this code except in compliance + with the License. You may obtain a copy of the License + at http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied. See the License for the specific language governing + permissions and limitations under the License. + +*/ +package org.onap.dcae.cdf.util.common; + +import javax.crypto.Cipher; +// import javax.crypto.SecretKey; +// import javax.crypto.KeyGenerator; +// import javax.crypto.spec.IvParameterSpec; +import java.security.Key; +// import java.security.NoSuchAlgorithmException; +// import java.security.SecureRandom; +// import javax.crypto.SecretKey; +// import sun.misc.*; +import java.util.*; + +public class G2CookieGen +{ + private Cipher cipher; + private Key key = null; + + private static String alg = "DES"; + private static String desecb = "DES/ECB/PKCS5Padding"; + + public static String G2_CLIENT_MEC_ID_1 = "MEC0001"; + private static String G2_CLIENT_MEC_ID_2 = "MEC0002"; + public static String G2_ENCRYPT_KEY = "secretK9"; + public static String G2_EPOCH_TM_STR = null; + + + private static long G2_TM_DELTA_IN_MILLISECONDS = 10*60*1000; + + class G2WSSKey implements Key + { + private final byte[] keyBytes; + private final String alg; + + G2WSSKey(String algorithm, byte[] keyBytes) + { + this.alg = algorithm; + this.keyBytes = keyBytes; + } + + public String getAlgorithm() + { + return alg; + } + public String getFormat() + { + return "RAW"; + } + public byte[] getEncoded() + { + return (byte[])keyBytes.clone(); + } + } + + + public G2CookieGen() { + try { + cipher = Cipher.getInstance(desecb); + } catch (Throwable t) { + System.err.println(t.toString()); + return; + } + } + + + public static String getClient1MacId() { + return G2_CLIENT_MEC_ID_1; + } + + public static String getClient2MacId() { + return G2_CLIENT_MEC_ID_2; + } + + public static String toHexStringFromByteArray(byte[] bytes) + { + StringBuilder retString = new StringBuilder(); + for (int i = 0; i < bytes.length; ++i) { + retString.append(Integer.toHexString(0x0100 + (bytes[i] & 0x00FF)).substring(1)); + } + return retString.toString(); + } + + public static byte[] toByteArrayFromHexString(String hexStr) + { + byte[] bts = new byte[hexStr.length() / 2]; + for (int i = 0; i < bts.length; i++) { + bts[i] = (byte) Integer.parseInt(hexStr.substring(2*i, 2*i+2), 16); + } + return bts; + } + + public byte[] encryptData(String sData) + { + try { + byte[] data = sData.getBytes(); + //System.out.println("Original data : " + new String(data)); + if (key == null) setKey(G2_ENCRYPT_KEY); + cipher.init(Cipher.ENCRYPT_MODE, key); + byte[] result = cipher.doFinal(data); + return result; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public String decryptData(byte[] sData) + { + try { + cipher.init(Cipher.DECRYPT_MODE, key); + byte[] result = cipher.doFinal(sData); + return new String(result); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public String constructCookie(String mechId) { + return mechId + ":" + System.currentTimeMillis(); + } + + public void setKey(String g2EncryptKey) { + key = new G2WSSKey(this.alg, g2EncryptKey.getBytes()); + } + + public String getEncryptedCookie(String mechId, String g2EncryptKey) { + setKey(g2EncryptKey); + String tmp = constructCookie(mechId); + byte[] byteArray = this.encryptData(tmp); + return this.toHexStringFromByteArray(byteArray); + } + + public long getTimeMillisFromCookie(String cookie) { + StringTokenizer tkn = new StringTokenizer(cookie,":"); + String tmStr = null; + while (tkn.hasMoreTokens()) { + tmStr = tkn.nextToken(); + } + Long tmLong = new Long(tmStr); + return tmLong.longValue(); + } + + public boolean isValid(long tm) { + long ctm = System.currentTimeMillis(); +System.out.println("Current Time="+ctm); +System.out.println("G2_TM_DELTA_IN_MILLISECONDS="+G2_TM_DELTA_IN_MILLISECONDS); + if ( Math.abs(ctm - tm) <= G2_TM_DELTA_IN_MILLISECONDS ) { + return true; + } + return false; + } + + + public static void main(String argv[]) { + try { + if (argv.length > 0) { +System.out.println("using Client MACID="+argv[0]); + G2_CLIENT_MEC_ID_1 = argv[0]; + + } + + if (argv.length > 1) { + if (argv[1].length() == 8) { +System.out.println("using Key="+argv[1]); + G2_ENCRYPT_KEY = argv[1]; + } + } + + if (argv.length > 2) { +System.out.println("using Epoch Time (in seconds) ="+argv[2]); + G2_EPOCH_TM_STR = argv[2]; + } + + + G2CookieGen wssc = new G2CookieGen(); + +// System.out.println("tz_diff="+G2_CLIENT_TM_ZONE_TO_PDT_IN_MILLISECONDS); +System.out.println("macid="+G2_CLIENT_MEC_ID_1); + + String cookie = wssc.constructCookie(G2_EPOCH_TM_STR); +System.out.println("original cookie="+cookie); + + byte[] byteArrary = wssc.encryptData(cookie); + String hexString = wssc.toHexStringFromByteArray(byteArrary); +System.out.println("encrypted cookie="+hexString); + System.exit(0); + + } catch (Exception e) { + System.err.println("Error: " + e); + System.exit(1); + } + } /* main */ +} diff --git a/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/common/Hostname.java b/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/common/Hostname.java new file mode 100644 index 0000000..4385c01 --- /dev/null +++ b/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/common/Hostname.java @@ -0,0 +1,108 @@ +/* + Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this code except in compliance + with the License. You may obtain a copy of the License + at http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied. See the License for the specific language governing + permissions and limitations under the License. + +*/ +package org.onap.dcae.cdf.util.common; + +import java.net.InetAddress; + +public class Hostname { + + /** + * Hostname FQDN + */ + public static String getHostName() { + return getHostName("unknown.unknown"); + } + + /** + * Hostname FQDN + */ + public static String getHostName(String def) { + return (uname == null) ? def : hostName; + } + + /** + * uname, the 1st portion of the hostname FQDN + */ + public static String getUname() { + return getUname("unknown"); + } + + /** + * uname, the 1st portion of the hostname FQDN + */ + public static String getUname(String def) { + return (uname == null) ? def : uname; + } + + /** + * Get an IP address for this machine + */ + public static String getLocalIP() { + return defaultLocalIP; + } + /** + * Get an IP address for this machine + */ + public static String getLocalIPinHex() { + return defaultLocalIPinHex; + } + /** + * Get a host name for this machine + */ + public static String getCanonicalHostName() { + return defaultCanonicalHostName; + } + + /** + * Value returned by getLocalIP() method + */ + private static String defaultLocalIP; + private static String defaultLocalIPinHex; + private static String defaultCanonicalHostName; + private static String hostName = null; // Hostname FQDN + private static String uname = null; // Hostname 1st part + + static { + try { + InetAddress ia = InetAddress.getLocalHost(); + defaultLocalIP = ia.getHostAddress(); + byte b[] = ia.getAddress(); + defaultLocalIPinHex = Convert.toHexString(b); + defaultCanonicalHostName = ia.getCanonicalHostName(); + } catch (Exception e) { + defaultLocalIP = "127.0.0.1"; + defaultLocalIPinHex = "7F000001"; + defaultCanonicalHostName = "localhost"; + } + + try { + hostName = InetAddress.getLocalHost().getHostName(); + String hostNameParts[] = hostName.split("\\."); + uname = hostNameParts[0]; + } catch (Exception ex) { + } + int dotInHostname = hostName.indexOf('.'); + if (dotInHostname > -1) hostName = hostName.substring(0, dotInHostname); + } + + public static void main(String args[]) { + System.out.println("getHostName() = '" + getHostName() + "'"); + System.out.println("getUname() = '" + getUname() + "'"); + System.out.println("getLocalIP() = '" + getLocalIP() + "'"); + System.out.println("getLocalIPinHex() = '" + getLocalIPinHex() + "'"); + System.out.println("getCanonicalHostName() = '" + getCanonicalHostName() + "'"); + } +} diff --git a/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/common/Pair.java b/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/common/Pair.java new file mode 100644 index 0000000..5a2a3f4 --- /dev/null +++ b/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/common/Pair.java @@ -0,0 +1,40 @@ +/* + Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this code except in compliance + with the License. You may obtain a copy of the License + at http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied. See the License for the specific language governing + permissions and limitations under the License. + +*/ +package org.onap.dcae.cdf.util.common; + +public final class Pair<L,R> { + public final L left; + public final R right; + public Pair(L l, R r) { left = l; right = r; } + + @Override + public boolean equals(Object obj) { + Pair<L,R> o = (Pair<L,R>)obj; + return left.equals(o.left) && right.equals(o.right); + } + @Override + public String toString() { + return "(" + left + "," + right + ")"; + } + @Override + public int hashCode() { + return left.hashCode() + right.hashCode(); + } + + public static <L,R> Pair<L,R> of(L l, R r) { + return new Pair<L,R>(l, r); + } +} diff --git a/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/common/Pid.java b/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/common/Pid.java new file mode 100644 index 0000000..c405c44 --- /dev/null +++ b/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/common/Pid.java @@ -0,0 +1,37 @@ +/* + Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this code except in compliance + with the License. You may obtain a copy of the License + at http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied. See the License for the specific language governing + permissions and limitations under the License. + +*/ +package org.onap.dcae.cdf.util.common; +import java.io.File; + +public class Pid { + /** + * Return the pid. + */ + public static int getPid() { return pid; } + public static String getPidStr() { return pidStr; } + + private static int pid; + private static String pidStr; + static { + try { + pid = Integer.parseInt( ( new File("/proc/self")).getCanonicalFile().getName() ); + pidStr = Integer.toString(pid); + } catch (java.io.IOException e) { + pid = -1; + pidStr = "-1"; + } + } +} diff --git a/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/common/Popen.java b/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/common/Popen.java new file mode 100644 index 0000000..d7f5846 --- /dev/null +++ b/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/common/Popen.java @@ -0,0 +1,84 @@ +/* + Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this code except in compliance + with the License. You may obtain a copy of the License + at http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied. See the License for the specific language governing + permissions and limitations under the License. + +*/ +package org.onap.dcae.cdf.util.common; + +import java.io.InputStream; +import java.io.OutputStream; +import java.io.IOException; + +public class Popen { + public static class Results { + public final String stdout, stderr; + public final int exitValue; + public Results(String so, String se, int e) { + stdout = so; stderr = se; exitValue = e; + } + } + + public static Results popen(String cmd) throws java.io.IOException, java.lang.InterruptedException { + return popen(cmd, null); + } + + public static Results popen(String cmd, String stdin) throws java.io.IOException, java.lang.InterruptedException { + Process process = Runtime.getRuntime().exec(cmd); + return proc(process, stdin); + } + + public static Results popen(String[] args) throws java.io.IOException, java.lang.InterruptedException { + return popen(args, null); + } + + public static Results popen(String[] args, String stdin) throws java.io.IOException, java.lang.InterruptedException { + Process process = Runtime.getRuntime().exec(args); + return proc(process, stdin); + } + + private static Results proc(Process process, String stdin) throws java.io.IOException, java.lang.InterruptedException { + OutputStream pinput = process.getOutputStream(); + InputStream poutput = process.getInputStream(); + InputStream perror = process.getErrorStream(); + + if (stdin != null) + pinput.write(stdin.getBytes()); + pinput.close(); + + String stdout = captureStream(poutput); + poutput.close(); + String stderr = captureStream(perror); + perror.close(); + process.waitFor(); + // System.out.println("stdin=\nnvvvvvvvvvvvvvvvv\n"); + // System.out.println(stdin); + // System.out.println("^^^^^^^^^^^^^^^^"); + // System.out.println("stdout=\nvvvvvvvvvvvvvvvv\n"); + // System.out.println(stdout); + // System.out.println("^^^^^^^^^^^^^^^^"); + // System.out.println("stderr=\nvvvvvvvvvvvvvvvv\n"); + // System.out.println(stderr); + // System.out.println("^^^^^^^^^^^^^^^^"); + return new Results(stdout, stderr, process.exitValue()); + } + + private static String captureStream(InputStream inp) throws java.io.IOException { + byte[] buf = new byte[8192]; + StringBuffer out = new StringBuffer(); + int b; + while ((b = inp.read(buf)) > 0) { + out.append(new String(buf, 0, b)); + } + return out.toString(); + } +} diff --git a/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/common/Tuple2.java b/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/common/Tuple2.java new file mode 100644 index 0000000..f4fd441 --- /dev/null +++ b/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/common/Tuple2.java @@ -0,0 +1,25 @@ +// -*- indent-tabs-mode: nil -*- +/* + Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this code except in compliance + with the License. You may obtain a copy of the License + at http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied. See the License for the specific language governing + permissions and limitations under the License. + +*/ +package org.onap.dcae.cdf.util.common; + +public class Tuple2<T1,T2> { + public Tuple2(T1 n1, T2 n2) { + t1 = n1; t2 = n2; + } + public final T1 t1; + public final T2 t2; +} diff --git a/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/common/Tuple3.java b/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/common/Tuple3.java new file mode 100644 index 0000000..566f910 --- /dev/null +++ b/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/common/Tuple3.java @@ -0,0 +1,29 @@ +// -*- indent-tabs-mode: nil -*- +/* + Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this code except in compliance + with the License. You may obtain a copy of the License + at http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied. See the License for the specific language governing + permissions and limitations under the License. + +*/ +package org.onap.dcae.cdf.util.common; + +public class Tuple3<T1,T2,T3> extends Tuple2<T1,T2> { + public Tuple3(T1 n1, T2 n2, T3 n3) { + super(n1, n2); + t3 = n3; + } + public Tuple3(Tuple3<T1,T2,T3> t) { + super(t.t1, t.t2); + t3 = t.t3; + } + public final T3 t3; +} diff --git a/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/common/Tuple4.java b/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/common/Tuple4.java new file mode 100644 index 0000000..c41d64c --- /dev/null +++ b/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/common/Tuple4.java @@ -0,0 +1,29 @@ +// -*- indent-tabs-mode: nil -*- +/* + Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this code except in compliance + with the License. You may obtain a copy of the License + at http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied. See the License for the specific language governing + permissions and limitations under the License. + +*/ +package org.onap.dcae.cdf.util.common; + +public class Tuple4<T1,T2,T3,T4> extends Tuple3<T1,T2,T3> { + public Tuple4(T1 n1, T2 n2, T3 n3, T4 n4) { + super(n1, n2, n3); + t4 = n4; + } + public Tuple4(Tuple4<T1,T2,T3,T4> t) { + super(t.t1, t.t2, t.t3); + t4 = t.t4; + } + public final T4 t4; +} diff --git a/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/common/Uid.java b/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/common/Uid.java new file mode 100644 index 0000000..99feeb3 --- /dev/null +++ b/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/common/Uid.java @@ -0,0 +1,69 @@ +/* + Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this code except in compliance + with the License. You may obtain a copy of the License + at http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied. See the License for the specific language governing + permissions and limitations under the License. + +*/ +package org.onap.dcae.cdf.util.common; +import java.io.File; +import java.io.BufferedReader; +import java.io.FileReader; +import org.onap.dcae.cdf.util.common.Popen; + +public class Uid { + /** + * Return the uid. + */ + public static int getUid() { return uid; } + public static String getUidStr() { return uidStr; } + + private static int uid = -1; + private static String uidStr = ""; + static { + try { + uid = getUidFromProcSelfStatus(); + if (uid == -1) uid = getUidFromIdU(); + uidStr = Integer.toString(uid); + } catch (java.io.IOException e) { + uid = -1; + uidStr = "-1"; + System.err.println("Exception: " + e); + } catch (Exception e) { + System.err.println("Exception: " + e); + } + + } + + private static int getUidFromProcSelfStatus() throws java.io.IOException { + int uid = -1; + if (true) return -1; + BufferedReader br = new BufferedReader(new FileReader(new File("/proc/self/status"))); + String thisLine = null; + while ((thisLine = br.readLine()) != null) { + if (thisLine.startsWith("Uid:")) { + String[] uids = thisLine.split("[: \t]+"); + if (uids.length > 1) { + uid = Integer.parseInt(uids[1]); + break; + } + } + } + br.close(); + return uid; + } + + private static int getUidFromIdU() throws java.io.IOException, java.lang.InterruptedException { + Popen.Results results = Popen.popen("/usr/bin/id -u"); + uid = Integer.parseInt(results.stdout.trim()); + return uid; + } +} diff --git a/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/config/.gitignore b/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/config/.gitignore new file mode 100644 index 0000000..6b468b6 --- /dev/null +++ b/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/config/.gitignore @@ -0,0 +1 @@ +*.class diff --git a/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/config/Configurable.java b/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/config/Configurable.java new file mode 100644 index 0000000..29f709d --- /dev/null +++ b/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/config/Configurable.java @@ -0,0 +1,28 @@ +/* + Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this code except in compliance + with the License. You may obtain a copy of the License + at http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied. See the License for the specific language governing + permissions and limitations under the License. + +*/ +package org.onap.dcae.cdf.util.config; + +/** + * The interface for an object that wants to be notified when the + * configuration files have changed (so it can re-configure itself) + */ + +public interface Configurable { + /** + * Configuration files have changed. + */ + public void reConfigure(); +} diff --git a/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/config/Configuration.java b/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/config/Configuration.java new file mode 100644 index 0000000..db54276 --- /dev/null +++ b/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/config/Configuration.java @@ -0,0 +1,579 @@ +/* + Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this code except in compliance + with the License. You may obtain a copy of the License + at http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied. See the License for the specific language governing + permissions and limitations under the License. + +*/ +package org.onap.dcae.cdf.util.config; + +import java.io.*; +import java.util.*; +import java.net.*; +import java.util.logging.*; +import org.onap.dcae.cdf.util.common.*; +import org.onap.dcae.cdf.util.threads.*; + +/** + * Class to monitor configuration parameters and notify + * other objects when they change + */ + +public class Configuration extends Thread implements Configurable { + /** + * Time between checks of config file in milliseconds + */ + private static int INTERVAL = 30000; + private int interval = INTERVAL; + /** + * Minimum age of config file before loading it in milliseconds + */ + private static final int MINAGE = 30000; + private int minage = MINAGE; + /** + * Value returned by getInstance() method + */ + private static Configuration defaultInstance = new Configuration(); + /** + * Value returned by getLocalIP() method + */ + private static String defaultLocalIP; + private static String defaultLocalIPinHex; + private static String defaultCanonicalHostName; + static { + try { + InetAddress ia = InetAddress.getLocalHost(); + defaultLocalIP = ia.getHostAddress(); + byte b[] = ia.getAddress(); + defaultLocalIPinHex = Convert.toHexString(b); + defaultCanonicalHostName = ia.getCanonicalHostName(); + } catch (Exception e) { + defaultLocalIP = "127.0.0.1"; + defaultLocalIPinHex = "7F000001"; + defaultCanonicalHostName = "localhost"; + } + } + /** + * Get an IP address for this machine + */ + public static String getLocalIP() { + return defaultLocalIP; + } + /** + * Get an IP address for this machine + */ + public static String getLocalIPinHex() { + return defaultLocalIPinHex; + } + /** + * Get a host name for this machine + */ + public static String getCanonicalHostName() { + return defaultCanonicalHostName; + } + /** + * Get a default global instance + */ + public static Configuration getInstance() { + return defaultInstance; + } + /** + * The current configuration + */ + private ResourceBundle config; + /** + * Where to log when things go wrong + */ + private static Logger logger = Logger.getLogger(Configuration.class.getName()); + /** + * The config file to read + */ + private File file; + /** + * The name of the config to read, when overriding the file. + */ + private String filename; + /** + * The last modified date of the config file + */ + private long curdate; + /** + * Should we stop scanning for config file updates? + */ + private boolean closed; + static boolean closeAll = false; + /** + * Have we started scanning for config file updates? + */ + private boolean initialized; + /** + * The name of the background thread monitoring the file. + */ + private static String monitorThreadName = "Configuration Monitor"; + /** + * How we keep track of registered Configurables. + */ + private ConfigurationRegistry configurationRegistry = new ConfigurationRegistry(); + /** + * included file. + */ + private Configuration subConfig = null; + private String subFile = null; + + public void reConfigure() { + configurationRegistry.reConfigureAll(logger); + } + + /** + * Create an instance using the default configuration file + * "configfile.properties" from the class path + */ + public Configuration() { + // logger.fine("Configuration()"); + } + /** + * Create an instance using a configuration file + * "FILENAME.properties" from the class path + */ + public Configuration(String filename) { + // logger.fine("Configuration(" + filename + ")"); + this.filename = filename; + } + /** + * Create an instance using a specific configuration file + */ + public Configuration(File file) { + this.file = file; + // logger.fine("Configuration(File)"); + } + + /** + * Change the configuration file to use + */ + public void setConfig(File file) { + this.file = file; + curdate = 0; + interrupt(); + } + /** + * Reset the interval used for rechecking the file. + * @param interval + */ + public synchronized void setInterval(int interval) { + this.interval = interval; + } + /** + * Reset the default interval used for rechecking the file. + * @param interval + */ + public synchronized void setDefaultInterval(int interval) { + this.INTERVAL = interval; + } + /** + * Reset the minimum age the file must be before being reread. + * This is used to prevent reading the file while it is being written, say by vi. + * @param minage + */ + public synchronized void setMinage(int minage) { + this.minage = minage; + } + /** + * Stop checking for config changes + */ + public void close() { + checkinit(); + closed = true; + if (Thread.currentThread() == this) { + return; + } + interrupt(); + try { + join(); + } catch (Exception e) { + } + } + /** + * Check the config file to see if it has changed + */ + private synchronized void check() { + long now = System.currentTimeMillis(); + if (logger.isLoggable(Level.FINE)) logger.fine("check(): now=" + Long.toString(now)); + try { + long ndate = file.lastModified(); + if (logger.isLoggable(Level.FINE)) logger.fine("file=" + file + ", ndate=" + Long.toString(ndate) + ", curdate=" + Long.toString(curdate,10)); + if (ndate == curdate || (now < ndate + minage && curdate != 0)) { + return; + } + if (logger.isLoggable(Level.FINE)) logger.fine("reloading file=" + file); + FileInputStream in = new FileInputStream(file); + config = new PropertyResourceBundle(in); + in.close(); + try { + String inc = config.getString("include"); + if ((inc != null) && !inc.equals("")) { + subFile = inc; + subConfig = new Configuration(subFile); + subConfig.registerConfigurable(this); + } + } catch (Exception e) { + } + + curdate = ndate; + configurationRegistry.reConfigureAll(logger); + // logger.info("CNFG0006: Configuration '" + file + "' reloaded"); + } catch (Exception e) { + logger.log(Level.SEVERE, "DAIS0048 Unrecoverable configuration error CNFG0004: Configuration file '" + file + "' inaccessible", e); + } + } + /** + * Make sure we're initialized and read the config file + * if necessary + */ + public void checkinit() { + // System.out.println("checkinit()"); + if (initialized) { + return; + } + initialized = true; + try { + if (file == null) { + if (filename == null) + filename = System.getProperty("configfile", "configfile"); + // logger.info("DAIS0073 0.8.73 >>> filename=" + filename); + if (filename.charAt(0) == '/') { + // logger.info("DAIS0073 0.8.73 filename has leading slash: " + filename); + file = new File(filename); + } else { + URI uri = getClass().getClassLoader().getResource(filename + ".properties").toURI(); + // logger.info("DAIS0073 0.8.73 uri=" + uri.toString()); + file = new File(uri); + } + } + } catch (Exception e) { + logger.log(Level.SEVERE, "DAIS0048 Unrecoverable configuration error CNFG0003: Cannot find configuration file '" + filename + "'", e); + } + check(); + setDaemon(true); + setName(monitorThreadName); + start(); + } + /** + * Check the config file to see if it has changed + */ + public void run() { + if (logger.isLoggable(Level.FINE)) logger.fine("Configuration::run()"); + while (!closed && !closeAll) { + try { + if (logger.isLoggable(Level.FINE)) logger.fine("sleeping " + Integer.toString(interval) + ", id=" + Long.toString(Thread.currentThread().getId()) + ", file=" + filename); + Thread.sleep(interval); + } catch (Exception e) { + } + if (logger.isLoggable(Level.FINE)) { + Thread currentThread = Thread.currentThread(); + logger.fine("checking id=" + Long.toString((currentThread != null) ? currentThread.getId() : -1) + ", file=" + filename); + } + check(); + } + } + + public static void wakeAllThreads() { + try { + Thread[] threads = ThreadUtils.getNamedThreads( monitorThreadName ); + for ( Thread thread : threads ) + thread.interrupt(); + } catch (Exception e) { + } + } + + public static void closeAllThreads() { + closeAll = true; + wakeAllThreads(); + } + + /** + * Forward this Configurable to the ConfigurationRegistry to be registered. + */ + public void registerConfigurable(Configurable element) { + configurationRegistry.registerConfigurable(element); + } + /** + * Forward this Configurable to the ConfigurationRegistry to be deRegistered. + */ + public void deRegisterConfigurable(Configurable element) { + configurationRegistry.deRegisterConfigurable(element); + } + + /** + * Get a configuration parameter as a String. + * If undefined, return null and log an error. + * @return String + */ + public String getString(String name) { + return getString(name, null, true); + } + /** + * Get a configuration parameter as a String. + * If undefined, return the specified default value. + * @return String + */ + public String getString(String name, String deflt) { + return getString(name, deflt, false); + } + + public static String trimQuotes(String str) { + if (str == null) return null; + str = str.trim(); + int len = str.length(); + if (len < 2) return str; + char startChar = str.charAt(0); + char endChar = str.charAt(len-1); + boolean startDoubleQuote = startChar == '"'; + boolean startSingleQuote = startChar == '\''; + boolean endDoubleQuote = endChar == '"'; + boolean endSingleQuote = endChar == '\''; + if ((startDoubleQuote && endDoubleQuote) || + (startSingleQuote && endSingleQuote)) { + return str.substring(1, len-1); + } else { + return str; + } + } + + /** + * Get a configuration parameter as a String. + * If undefined, return the specified default value. + * If complaining, log an error. + * @return String + */ + public String getString(String name, String deflt, boolean complain) { + checkinit(); + try { + return trimQuotes(config.getString(name)); + } catch (Exception e) { + if (subConfig != null) { + try { + return subConfig.getString(name, deflt, complain); + } catch (Exception e2) { + } + } + if (complain) + logger.log(Level.SEVERE, "DAIS0048 Unrecoverable configuration error CNFG0001: '" + filename + "': Configuration property " + name + " must be defined", e); + return deflt; + } + } + + /** + * Get a configuration parameter as a String encoded using URL % escapes. + * If undefined, return null and log an error. + * @return String + */ + public String getDecodedString(String name) { + return getDecodedString(name, null, true); + } + /** + * Get a configuration parameter as a String encoded using URL % escapes. + * If undefined, return the specified default value. + * @return String + */ + public String getDecodedString(String name, String deflt) { + return getDecodedString(name, deflt, false); + } + /** + * Get a configuration parameter as a String encoded using URL % escapes. + * If undefined, return the specified default value. + * If complaining, log an error. + * @return String + */ + public String getDecodedString(String name, String deflt, boolean complain) { + checkinit(); + try { + return URLDecoder.decode(config.getString(name), "UTF-8"); + } catch (UnsupportedEncodingException e) { + logger.log(Level.SEVERE, "DAIS0048 Unrecoverable configuration error CNFG0007: UTF-8 is not recognized as a character set encoding", e); + return deflt; + } catch (Exception e) { + if (complain) + logger.log(Level.SEVERE, "DAIS0048 Unrecoverable configuration error CNFG0001: '" + filename + "': Configuration property " + name + " must be defined", e); + return deflt; + } + } + + /** + * Get a configuration parameter as a String[]. + * If undefined, return null and log an error. + * @return String[] + */ + public String[] getStrings(String name) { + return getStrings(name, null, "[ \t,]+", true); + } + /** + * Get a configuration parameter as a String[]. + * If undefined, return the specified default. + * @return String[] + */ + public String[] getStrings(String name, String[] deflt) { + return getStrings(name, deflt, "[ \t,]+", false); + } + /** + * Get a configuration parameter as a String[]. + * If undefined, return the specified default + * @return String[] + */ + public String[] getStrings(String name, String[] deflt, String pattern, boolean complain) { + name = getString(name, null, complain); + if (name == null) { + return deflt; + } + return name.trim().split(pattern); + } + + /** + * Get a configuration parameter as a String[], each String encoded using URL % escapes. + * If undefined, return null and log an error. + * @return String[] + */ + public String[] getDecodedStrings(String name) { + return getDecodedStrings(name, null, "[ \t,]+", true); + } + /** + * Get a configuration parameter as a String[], each String encoded using URL % escapes. + * If undefined, return the specified default. + * @return String[] + */ + public String[] getDecodedStrings(String name, String[] deflt) { + return getDecodedStrings(name, deflt, "[ \t,]+", false); + } + /** + * Get a configuration parameter as a String[], each String encoded using URL % escapes. + * If undefined, return the specified default. + * @return String[] + */ + public String[] getDecodedStrings(String name, String[] deflt, String pattern) { + return getDecodedStrings(name, deflt, pattern, false); + } + /** + * Get a configuration parameter as a String[], each String encoded using URL % escapes. + * If undefined, return the specified default. + * @return String[] + */ + public String[] getDecodedStrings(String name, String[] deflt, String pattern, boolean complain) { + name = getString(name, null, complain); + if (name == null) { + return deflt; + } + String[] strs = (name.trim().split(pattern)); + try { + for (int i = 0; i < strs.length; i++) { + strs[i] = URLDecoder.decode(strs[i], "UTF-8"); + } + } catch (UnsupportedEncodingException e) { + logger.log(Level.SEVERE, "DAIS0048 Unrecoverable configuration error CNFG0007: UTF-8 is not recognized as a character set encoding", e); + } + return strs; + } + + /** + * Get a configuration parameter as a long. If undefined or non-numeric, return -1 and log an error. + */ + public long getLong(String name) { + return getLong(name, -1L); + } + /** + * Get a configuration parameter as a long. If undefined, return the specified default + * If non-numeric, return the specified default and log an error. + */ + public long getLong(String name, long deflt) { + String value = getString(name, null); + if (value == null) { + return deflt; + } + try { + return Long.parseLong(value.trim()); + } catch (Exception e) { + logger.log(Level.SEVERE, "DAIS0048 Unrecoverable configuration error CNFG0002: '" + filename + "': Configuration property " + name + " must be numeric", e); + return deflt; + } + } + + /** + * Get a configuration parameter as an int. If undefined or non-numeric, return -1 and log an error. + */ + public int getInt(String name) { + return getInt(name, -1); + } + /** + * Get a configuration parameter as an int. If undefined, return the specified default + * If non-numeric, return the specified default and log an error. + */ + public int getInt(String name, int deflt) { + String value = getString(name, null); + if (value == null) { + return deflt; + } + try { + return Integer.parseInt(value.trim()); + } catch (Exception e) { + logger.log(Level.SEVERE, "DAIS0048 Unrecoverable configuration error CNFG0002: '" + filename + "': Configuration property " + name + " must be numeric", e); + return deflt; + } + } + + /** + * Get a configuration parameter as an boolean. If undefined or non-numeric, return false and log an error. + */ + public boolean getBoolean(String name) { + return getBoolean(name, false); + } + /** + * Get a configuration parameter as an boolean. If undefined, return the specified default + * If non-numeric, return the specified default and log an error. + */ + public boolean getBoolean(String name, boolean deflt) { + String value = getString(name, null); + if (value == null) { + return deflt; + } + try { + return Boolean.parseBoolean(value.trim()); + } catch (Exception e) { + logger.log(Level.SEVERE, "DAIS0048 Unrecoverable configuration error CNFG0002: '" + filename + "': Configuration property " + name + " must be true/false", e); + return deflt; + } + } + + /** + * Get a configuration parameter as a double. If undefined or non-numeric, return -1 and log an error. + */ + public double getDouble(String name) { + return getDouble(name, -1); + } + /** + * Get a configuration parameter as a double. If undefined, return the specified default + * If non-numeric, return the specified default and log an error. + */ + public double getDouble(String name, double deflt) { + String value = getString(name, null); + if (value == null) { + return deflt; + } + try { + return Double.parseDouble(value); + } catch (Exception e) { + logger.log(Level.SEVERE, "DAIS0048 Unrecoverable configuration error CNFG0002: '" + filename + "': Configuration property " + name + " must be numeric", e); + return deflt; + } + } + + public Enumeration getKeys() { + checkinit(); + return (config != null) ? config.getKeys() : null; + } +} diff --git a/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/config/ConfigurationRegistry.java b/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/config/ConfigurationRegistry.java new file mode 100644 index 0000000..f108ced --- /dev/null +++ b/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/config/ConfigurationRegistry.java @@ -0,0 +1,106 @@ +/* + Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this code except in compliance + with the License. You may obtain a copy of the License + at http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied. See the License for the specific language governing + permissions and limitations under the License. + +*/ +package org.onap.dcae.cdf.util.config; + +import java.util.logging.*; +import java.lang.ref.*; + +/** + * Class to register and notify other objects when needed. + * Those other objects must implement Configurable. + */ + +public class ConfigurationRegistry { + public ConfigurationRegistry() { } + + /** + * The set of registered configurables + */ + private WeakReference<Configurable>[] configurables = new WeakReference[0]; + + /** + * Request callback whenever the configuration data changes + */ + public synchronized void registerConfigurable(Configurable element) { + // System.out.println("adding " + element.getClass().getName() + ", length=" + Integer.toString(configurables.length)); + for (int i = 0; i < configurables.length; i++) { + if (configurables[i].get() == element) { + return; + } + } + WeakReference<Configurable>[] nconfigurables = new WeakReference[configurables.length + 1]; + System.arraycopy(configurables, 0, nconfigurables, 0, configurables.length); + nconfigurables[configurables.length] = new WeakReference<Configurable>(element); + configurables = nconfigurables; + element.reConfigure(); + } + + /** + * Cancel request for callbacks when configuration changes + */ + public synchronized void deRegisterConfigurable(Configurable element) { + // System.out.println("removing " + element.getClass().getName() + ", length=" + Integer.toString(configurables.length)); + for (int i = 0; i < configurables.length; i++) { + if (configurables[i].get() == element) { + WeakReference<Configurable>[] nconfigurables = new WeakReference[configurables.length - 1]; + if (i > 0) { + System.arraycopy(configurables, 0, nconfigurables, 0, i); + } + if (i < nconfigurables.length) { + System.arraycopy(configurables, i + 1, nconfigurables, i, nconfigurables.length - i); + } + configurables = nconfigurables; + return; + } + } + } + + /** + * Notify all of the Configurables that they need to reConfigure. + */ + public void reConfigureAll() { + reConfigureAll(Logger.getLogger(ConfigurationRegistry.class.getName())); + } + + /** + * Notify all of the Configurables that they need to reConfigure. + */ + public void reConfigureAll(Logger logger) { + // System.out.println("reConfigureAll(), length=" + Integer.toString(configurables.length)); + for (int i = 0; i < configurables.length; i++) { + try { + // System.out.println("reConfigureAll(), i=" + Integer.toString(i)); + WeakReference<Configurable> wc = configurables[i]; + Configurable c = (wc != null) ? wc.get() : null; + if (c != null) + c.reConfigure(); + } catch (Exception e) { + WeakReference<Configurable> wc = configurables[i]; + Configurable c = (wc != null) ? wc.get() : null; + logger.log(Level.SEVERE, "DAIS0048 Unrecoverable configuration error CNFG0005: Problem while invoking reConfigure for: " + + ((wc == null) ? "null" : (c == null) ? "null/null" : c.getClass().getName()) + ": " + + e.getMessage(), e); + } + } + } + + /** + * Return the number of configurables that are registered. + */ + public int getCount() { + return configurables.length; + } +} diff --git a/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/config/EncryptedConfiguration.java b/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/config/EncryptedConfiguration.java new file mode 100644 index 0000000..3da0f42 --- /dev/null +++ b/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/config/EncryptedConfiguration.java @@ -0,0 +1,219 @@ +/* + Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this code except in compliance + with the License. You may obtain a copy of the License + at http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied. See the License for the specific language governing + permissions and limitations under the License. + +*/ +package org.onap.dcae.cdf.util.config; + +import java.util.logging.*; +// import java.lang.ref.*; +import org.onap.dcae.cdf.util.common.*; +import gnu.getopt.Getopt; +import java.security.*; +import javax.crypto.*; +import javax.crypto.spec.SecretKeySpec; + +/** + * Class to manage encrypted configuration values. + */ + +public class EncryptedConfiguration { + /** + * Our secret key + */ + private String encryptionKey; + + /** + * Where to log when things go wrong + */ + private Logger logger; + + public EncryptedConfiguration(String key, Logger logger) { + encryptionKey = key.trim(); + this.logger = logger; + } + + /** + * Retrieve an encrypted string from the given configuration. + * The name will have ".x" appended to it. + * Decoded from hex, it will be "method:hexsalt:hexvalue". + * The format of the value will be in hex. + * Method will be "r" to begin with, for "rc4". + */ + public String getString(Configuration config, String name, String deflt, boolean complain) throws Exception { + return getString(config, name, deflt, complain, encryptionKey); + } + + /** + * Retrieve an encrypted string from the given configuration. + * The name will have ".x" appended to it. + * Decoded from hex, it will be "method:hexsalt:hexvalue". + * The format of the value will be in hex. + * Method will be "r" to begin with, for "rc4". + */ + public String getString(Configuration config, String name, String deflt, boolean complain, String key) throws Exception { + String str = config.getString(name + ".x", null, complain); + if (str == null) { + return deflt; + } + return decrypt(str, key); + } + + /** + * Decrypt a string in 'method:hexsalt:hexvalue' format. + */ + public static String decrypt(String triple, String key) throws Exception { + String[] strParts = triple.trim().split(":"); + if (strParts.length != 3) throw new Exception("Encrypted value must look like 'x:y:z'"); + return decrypt(strParts[0], Convert.stringFromHex(strParts[1]), key, Convert.bytesFromHex(strParts[2])); + } + + /** + * Decrypt a string 'method:hexsalt:hexvalue' format. + */ + public static String decrypt(String method, String salt, String key, byte[] bvalue) throws Exception { + /* if (false) { + System.out.println("method length=" + method.length()); System.out.println(AsHex.asHex(method)); + System.out.println("salt length=" + salt.length()); System.out.println(AsHex.asHex(salt)); + System.out.println("key length=" + key.length()); System.out.println(AsHex.asHex(key)); + System.out.println("bvalue length=" + bvalue.length); System.out.println(AsHex.asHex(bvalue)); + } */ + byte[] secretKey = runDigest(salt + "." + key); + + SecretKeySpec skeySpec = new SecretKeySpec(secretKey, method); + + Cipher cipher = Cipher.getInstance(method); // "AES" + cipher.init(Cipher.DECRYPT_MODE, skeySpec); + + byte[] decrypted = cipher.doFinal(bvalue); + return new String(decrypted); + } + + /** + * Encrypt a string using the given method, salt and key. + */ + public static byte[] encrypt(String method, String salt, String key, String value) throws Exception { + byte[] bvalue = value.getBytes(); + byte[] secretKey = runDigest(salt + "." + key); + + SecretKeySpec skeySpec = new SecretKeySpec(secretKey, method); + + Cipher cipher = Cipher.getInstance(method); // "AES" + cipher.init(Cipher.ENCRYPT_MODE, skeySpec); + + byte[] encrypted = cipher.doFinal(bvalue); + return encrypted; + } + + /** + * Prepare a secret key by running a digest on it. + */ + private static byte[] runDigest(String text) throws Exception { + MessageDigest md = MessageDigest.getInstance("MD5"); + md.reset(); + md.update(text.getBytes(), 0, text.length()); + return md.digest(); + } + + /** + * Encrypt a string using the given method, salt and key, and return it as a hex-formated triple. + */ + public static String encryptToTriple(String method, String salt, String key, String value) throws Exception { + StringBuilder sb = new StringBuilder(method); + sb.append(':').append(Convert.toHexString(salt)) + .append(':').append(Convert.toHexString(encrypt(method, salt, key, value))); + return sb.toString(); + } + + /** + * Create a value that can be used as a salt. + */ + public static String generateSalt() { + return Long.toString(System.currentTimeMillis() % 1000) + Pid.getPidStr(); + } + + public static void usage() { + usage(null); + } + + public static void usage(String msg) { + if (msg != null) System.out.println(msg); + System.out.println("Usage: java EncryptedConfiguration -D triple -k key\n" + + "java EncryptedConfiguration -d string -m method [-s salt | -S] -k key\n" + + "java EncryptedConfiguration -e string -m method [-s salt | -S] -k key\n" + + "-D\tdecrypt x:y:z triple\n" + + "-d\tdecrypt string (in hex)\n" + + "-e\tencrypt string\n" + + "-S\tgenerate a salt\n" + ); + System.exit(1); + } + + public static void main(String args[]) throws Exception { + Getopt g = new Getopt( "EncryptedConfiguration", args, "s:Sk:m:e:d:D:?" ); + + int c, verbosity = 0; + String salt = null, key = null, method = null, encStr = null, decStr = null, triple = null; + boolean genSalt = false; + + while ((c = g.getopt()) != -1) { + switch (c) { + case 's': salt = g.getOptarg(); break; + case 'S': genSalt = true; break; + case 'k': key = g.getOptarg(); break; + case 'm': method = g.getOptarg(); break; + case 'e': encStr = g.getOptarg(); break; + case 'd': decStr = g.getOptarg(); break; + case 'D': triple = g.getOptarg(); break; + case '?': usage(); break; + } + } + + if (triple == null) { + if ((salt == null) && !genSalt) usage("one of -s or -S must be specified"); + if ((salt != null) && genSalt) usage("only one of -s or -S must be specified"); + if (key == null) usage("-k must be specified"); + if (method == null) usage("-m must be specified"); + if ((encStr == null) && (decStr == null)) usage("one of -d or -e must be specified"); + if ((encStr != null) && (decStr != null)) usage("only one of -d or -e may be specified"); + if (genSalt) salt = generateSalt(); + if (encStr != null) + System.out.println(encryptToTriple(method, salt, key, encStr)); + if (decStr != null) + System.out.println(decrypt(method, salt, key, Convert.bytesFromHex(decStr))); + } else { + if (key == null) usage("-k not specified"); + System.out.println(decrypt(triple, key)); + } + + // http://forums.sun.com/thread.jspa?threadID=5290983 + // try { + // String message = "Strong Versus Unlimited Strength Cryptography"; + // SecretKeySpec skeySpec = new SecretKeySpec("0123456789ABCDEF".getBytes(), "AES"); //AES-128 + + // Cipher cipher = Cipher.getInstance("AES"); // "AES/ECB/NoPadding" + // cipher.init(Cipher.ENCRYPT_MODE, skeySpec); + + // byte[] encrypted = cipher.doFinal(message.getBytes()); + // System.out.println("encrypted string: " + encrypted); //storing into MySQL DB + // System.out.println("in hex: '" + Convert.toHexString(encrypted) + "'"); + + // cipher.init(Cipher.DECRYPT_MODE, skeySpec); + // byte[] original = cipher.doFinal(encrypted); + // String originalString = new String(original); + // System.out.println("Original string: " + originalString); + // } catch (Exception e) { + // System.err.println("Exception caught: " + e.toString()); + // } + } +} diff --git a/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/config/PropValue.java b/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/config/PropValue.java new file mode 100644 index 0000000..efeabc5 --- /dev/null +++ b/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/config/PropValue.java @@ -0,0 +1,245 @@ +/* + Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this code except in compliance + with the License. You may obtain a copy of the License + at http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied. See the License for the specific language governing + permissions and limitations under the License. + +*/ +package org.onap.dcae.cdf.util.config; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.BufferedReader; +import java.io.PrintStream; +import java.io.IOException; +import java.util.logging.Logger; +import org.onap.dcae.cdf.util.config.Configuration; +import org.onap.dcae.cdf.util.config.EncryptedConfiguration; +import gnu.getopt.Getopt; + +public class PropValue { + private EncryptedConfiguration encryptedConfiguration; + private String encryptionKey; + + public PropValue(Configuration globalConfig, Logger logger) { + encryptionKey = globalConfig.getString(getEncryptionKeyProperty()); + encryptedConfiguration = new EncryptedConfiguration(encryptionKey, logger); + } + + public String getEncryptedString(Configuration config, String name, String deflt, boolean complain) throws Exception { + return encryptedConfiguration.getString(config, name, deflt, complain); + } + + public String generateEncryptedProperty(String method, String salt, String value) throws Exception { + return generateEncryptedProperty(method, salt, value, this); + } + + public String decryptTriple(String triple) { + return decryptTriple(triple, this); + } + + public static void printEncryptedProperty(String method, String name, String salt, String value, String globalPropFile) { + try { + if (name != null) System.out.print(name + ".x="); + if (globalPropFile == null) globalPropFile = getGlobalPropFile(); + if (globalPropFile == null) throw new NullPointerException("globalPropFile not set"); + System.out.println(generateEncryptedProperty(method, salt, value, globalPropFile)); + } catch (Exception e) { + System.err.println("Cannot encrypt '" + value + "', method '" + method + "' for property '" + name + "': "+ e.toString()); + } + } + + public static String generateEncryptedProperty(String method, String salt, String value, String globalPropFile) throws Exception { + Logger logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME); + if (globalPropFile == null) globalPropFile = getGlobalPropFile(); + if (globalPropFile == null) throw new NullPointerException("globalPropFile not set"); + PropValue propValue = new PropValue(new Configuration(globalPropFile), logger); + return generateEncryptedProperty(method, salt, value, propValue); + } + + public static String generateEncryptedProperty(String method, String salt, String value, PropValue propValue) throws Exception { + if (salt == null) salt = EncryptedConfiguration.generateSalt(); + return EncryptedConfiguration.encryptToTriple(method, salt, propValue.encryptionKey, value); + } + + public static void extractProperty(String f, String name, boolean encrypted) { + extractProperty(f, name, encrypted, null); + } + + public static void extractProperty(String f, String name, boolean encrypted, String globalPropFile) { + Configuration config = new Configuration(f); + Logger logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME); + if (globalPropFile == null) globalPropFile = getGlobalPropFile(); + if (globalPropFile == null) throw new NullPointerException("globalPropFile not set"); + PropValue propValue = new PropValue(new Configuration(globalPropFile), logger); + String val = ""; + try { + if (encrypted) + val = propValue.getEncryptedString(config, name, "", true); + else + val = config.getString(name); + System.out.println(val); + } catch (Exception e) { + System.err.println("Cannot extract '" + name + "' from '" + config + "': " + e.toString()); + } + } + + public static void usage() { + usage(null); + } + + // public static String decryptTriple(String triple) { + // return decryptTriple(triple, null); + // } + + public static String decryptTriple(String triple, String globalPropFile) { + Logger logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME); + if (globalPropFile == null) globalPropFile = getGlobalPropFile(); + if (globalPropFile == null) throw new NullPointerException("globalPropFile not set"); + PropValue propValue = new PropValue(new Configuration(globalPropFile), logger); + return decryptTriple(triple, propValue); + } + + public static String decryptTriple(String triple, PropValue propValue) { + String ret = null; + try { + ret = EncryptedConfiguration.decrypt(triple, propValue.encryptionKey); + } catch (Exception e) { + System.err.println("Cannot decrypt '" + triple + "': " + e.toString()); + } + return ret; + } + + public static void encryptInput(InputStream in, PrintStream out) throws Exception { + encryptInput(null, in, out); + } + public static void encryptInput() throws Exception { + encryptInput(null, System.in, System.out); + } + + private static void printEncryptedValue(Matcher m, PropValue propValue, PrintStream sysout) { + String method = m.group(1); + String name = m.group(2); + String value = m.group(3); + try { + sysout.println(name + ".x=" + + EncryptedConfiguration.encryptToTriple(method, + EncryptedConfiguration.generateSalt(), + propValue.encryptionKey, value)); + } catch (Exception e) { + System.err.println("Error: Cannot encrypt '" + value + "', method '" + method + "' for property '" + name + "': " + e.toString()); + } + } + + public static void encryptInput(String globalPropFile, InputStream sysin, PrintStream sysout) throws Exception { + String s; + + Pattern pDquote = Pattern.compile("^ENCRYPTME[.]([A-Z]*)[.]([^= \t]*)[ \t]*=[ \t]*\"([^\"]*)\"[ \t]*$"); + Pattern pSquote = Pattern.compile("^ENCRYPTME[.]([A-Z]*)[.]([^= \t]*)[ \t]*=[ \t]*'([^']*)'[ \t]*$"); + Pattern pNoWhite = Pattern.compile("^ENCRYPTME[.]([A-Z]*)[.]([^= \t]*)[ \t]*=[ \t]*([^ \t'\"]+)[ \t]*$"); +// Pattern pEncryptMe = Pattern.compile("^ENCRYPTME[.]([A-Z]*)[.]([^= \t]*)[ \t]*="); + + Logger logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME); + if (globalPropFile == null) globalPropFile = getGlobalPropFile(); + if (globalPropFile == null) throw new NullPointerException("globalPropFile not set"); + PropValue propValue = new PropValue(new Configuration(globalPropFile), logger); + + BufferedReader in = new BufferedReader(new InputStreamReader(sysin)); + + try { + while ((s = in.readLine()) != null) { + // System.out.println("looking at '" + s + "'"); + Matcher mDquote = pDquote.matcher(s); + Matcher mSquote = pSquote.matcher(s); + Matcher mNoWhite = pNoWhite.matcher(s); +// Matcher mEncryptMe = pNoWhite.matcher(s); + if (mDquote.matches()) { + printEncryptedValue(mDquote, propValue, sysout); + } else if (mSquote.matches()) { + printEncryptedValue(mSquote, propValue, sysout); + } else if (mNoWhite.matches()) { + printEncryptedValue(mNoWhite, propValue, sysout); + } else if (s.startsWith("ENCRYPTME")) { + throw new Exception("Bad value to encrypt: '" + s + "'"); + } else { + // System.out.println("printing the line: '" + s + "'"); + sysout.println(s); + } + } + } catch (IOException e) { + System.err.println("Error: Cannot read from stdin: " + e.toString()); + } catch (Exception e) { + throw e; + } + } + + public static void usage(String msg) { + if (msg != null) System.err.println(msg); + System.err.println("Usage: java PropValue [-x] -n property -f property-file"); + System.err.println("\tExtract the named value from the given property-file (or full pathname)"); + System.err.println("Usage: java PropValue -e method [-n property] [-s salt] -v value"); + System.err.println("\tEncrypt the given property with the given name and value"); + System.err.println("Usage: java PropValue -E"); + System.err.println("\tEncrypt all lines that look like ENCRYPTME.METHOD.name=value"); + System.err.println("Usage: java PropValue -u value"); + System.err.println("\tDecrypt the given value, expressed as a triple METHOD:HEXSALT:HEXVAL"); + System.exit(1); + } + + public static void setGlobalPropFile(String g) { sGlobalPropFile = g; } + public static String getGlobalPropFile() { return sGlobalPropFile; } + private static String sGlobalPropFile = null; + + public static void setEncryptionKeyProperty(String e) { encryptionKeyProperty = e; } + public static String getEncryptionKeyProperty() { return encryptionKeyProperty; } + private static String encryptionKeyProperty = "Global_Title"; + + public static void main(String args[]) throws Exception { + Getopt g = new Getopt( "PropValue", args, "e:Ef:G:n:s:u:v:x" ); + String propfile = null, name = null, method = null, value = null, unencrypt = null; + String globalPropFile = getGlobalPropFile(); + boolean useDecryption = false, encryptStdin = false; + String salt = null; + int c; + + while ((c = g.getopt()) != -1) { + switch (c) { + case 'e': method = g.getOptarg(); break; + case 'E': encryptStdin = true; break; + case 'f': propfile = g.getOptarg(); break; + case 'G': globalPropFile = g.getOptarg(); break; + case 'n': name = g.getOptarg(); break; + case 's': salt = g.getOptarg(); break; + case 'u': unencrypt = g.getOptarg(); break; + case 'v': value = g.getOptarg(); break; + case 'x': useDecryption = true; break; + case '?': usage(); break; + } + } + if (encryptStdin) { + if (name != null || propfile != null || method != null || value != null) usage("cannot use -E with other options"); + encryptInput(System.in, System.out); + } else if (unencrypt == null) { + if (method != null) { + if (value == null) usage("-v required"); + printEncryptedProperty(method, name, salt, value, globalPropFile); + } else { + if (name == null) usage("-n is required"); + if (propfile == null) usage("-f is required"); + extractProperty(propfile, name, useDecryption, globalPropFile); + } + } else { + System.out.println(decryptTriple(unencrypt, globalPropFile)); + } + } +} diff --git a/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/threads/.gitignore b/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/threads/.gitignore new file mode 100644 index 0000000..6b468b6 --- /dev/null +++ b/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/threads/.gitignore @@ -0,0 +1 @@ +*.class diff --git a/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/threads/TaskThread.java b/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/threads/TaskThread.java new file mode 100644 index 0000000..97d1520 --- /dev/null +++ b/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/threads/TaskThread.java @@ -0,0 +1,164 @@ +/* + Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this code except in compliance + with the License. You may obtain a copy of the License + at http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied. See the License for the specific language governing + permissions and limitations under the License. + +*/ +package org.onap.dcae.cdf.util.threads; + +/** + * A thread with a queue of runnable tasks to execute in the + * thread + */ +public class TaskThread extends Thread { + /** + * Allocates a new TaskThread object. + */ + public TaskThread() { + } + /** + * Allocates a new TaskThread object. + */ + public TaskThread(Runnable target) { + super(target); + } + /** + * Allocates a new TaskThread object. + */ + public TaskThread(ThreadGroup group, Runnable target) { + super(group, target); + } + /** + * Allocates a new TaskThread object. + */ + public TaskThread(String name) { + super(name); + } + /** + * Allocates a new TaskThread object. + */ + public TaskThread(ThreadGroup group, String name) { + super(group, name); + } + /** + * Allocates a new TaskThread object. + */ + public TaskThread(Runnable target, String name) { + super(target, name); + } + /** + * Allocates a new TaskThread object. + */ + public TaskThread(ThreadGroup group, Runnable target, String name) { + super(group, target, name); + } + /** + * A queued request to be run in the TaskThread + */ + private static class Task { + public Task next; + public Runnable target; + public Task(Runnable target) { + this.target = target; + } + } + private Task head; + private Task tail; + protected boolean closed; + /** + * Queue up a task to be executed by this thread. + */ + protected synchronized void queueRequest(Runnable r) { + Task t = new Task(r); + if (head == null) { + head = t; + wakeup(); + } else { + tail.next = t; + } + tail = t; + } + /** + * Mark as closed and wake up. + */ + protected synchronized void markClosed() { + if (!closed) { + closed = true; + wakeup(); + } + } + /** + * Wait for the next queued request. If closed, return + * null. Relies on the default implementation of wakeup. + */ + protected synchronized Runnable waitNextRequest() { + Task t; + while ((t = head) == null && !closed) { + try { + wait(); + } catch (Exception e) { + } + } + head = t.next; + if (head == null) { + tail = null; + } + return t.target; + } + /** + * Get the next queued request or null if none + */ + protected synchronized Runnable nextRequest() { + Task t = head; + if (t == null) { + return null; + } + head = t.next; + if (head == null) { + tail = null; + } + return t.target; + } + /** + * Wake up the thread to process tasks. + * Implementation depends on what the thread + * is waiting on. The default implementation + * does a this.notify(). + */ + protected void wakeup() { + notify(); + } + /** + * Process any pending requests then return + */ + protected void processQueuedRequests() { + Runnable r; + while ((r = nextRequest()) != null) { + r.run(); + } + } + /** + * Check whether any tasks are pending + */ + protected boolean areTasksPending() { + return (head != null); + } + /** + * Wait for and process pending requests until closed + */ + protected void processRequestsForever() { + Runnable r; + while ((r = waitNextRequest()) != null) { + r.run(); + } + } +} diff --git a/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/threads/ThreadUtils.java b/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/threads/ThreadUtils.java new file mode 100644 index 0000000..34afebe --- /dev/null +++ b/cdf/src/cdf-prop-value/cdf-util/src/main/java/org/onap/dcae/cdf/util/threads/ThreadUtils.java @@ -0,0 +1,89 @@ +/* + Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this code except in compliance + with the License. You may obtain a copy of the License + at http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied. See the License for the specific language governing + permissions and limitations under the License. + +*/ +package org.onap.dcae.cdf.util.threads; + +import java.util.LinkedList; +import java.util.List; + +/** + * Various utility functions dealing with threads + */ +public class ThreadUtils { + /** + * Get a list of all threads. + * + * @return an array of threads + */ + public static Thread[] getAllThreads() { + ThreadGroup rootGroup = getRootGroup(); + int noThreads = rootGroup.activeCount(); // returns an estimated count of active threads + Thread[] threads = new Thread[noThreads + 1]; + rootGroup.enumerate(threads); + + while ( rootGroup.enumerate( threads, true ) == threads.length ) { // iterate if we filled up the array + threads = new Thread[ threads.length + noThreads ]; + } + // remove null threads + LinkedList<Thread> lthreads = new LinkedList<Thread>(); + for (Thread thread: threads) + if (thread != null) + lthreads.push(thread); + return lthreads.toArray(new Thread[0]); + } + + /** + * Get a list of all threads with a given thread name. + * + * @param name the name to look for + * @return an array of threads with that name + */ + public static Thread[] getNamedThreads(final String name) { + Thread[] allThreads = getAllThreads(); + LinkedList<Thread> lthreads = new LinkedList<Thread>(); + for (Thread thread: allThreads) + if (thread.getName().equals(name)) + lthreads.push(thread); + + return lthreads.toArray(new Thread[0]); + } + + /** + * Get the ultimate root of the threads + * + * @return the root thread + */ + public static ThreadGroup getRootGroup() { + ThreadGroup rootGroup = Thread.currentThread( ).getThreadGroup( ); + ThreadGroup parentGroup; + while ( ( parentGroup = rootGroup.getParent() ) != null ) { + rootGroup = parentGroup; + } + return rootGroup; + } + + public static void main(String args[]) throws Exception { + System.out.println("==== get Root Threads ===="); + System.out.println("Root thread = " + getRootGroup().getName()); + System.out.println("==== get All Threads ===="); + Thread[] threads = getAllThreads(); + for (int i = 0; i < threads.length; i++) + System.out.println("Thread No:" + i + " = " + threads[i].getName()); + System.out.println("==== getNamedThreads(main) ===="); + threads = getNamedThreads("main"); + for (int i = 0; i < threads.length; i++) + System.out.println("Thread No:" + i + " = " + threads[i].getName()); + } +} diff --git a/cdf/src/cdf-prop-value/cdf-util/src/test/java/org/onap/dcae/cdf/util/AppTest.java b/cdf/src/cdf-prop-value/cdf-util/src/test/java/org/onap/dcae/cdf/util/AppTest.java new file mode 100644 index 0000000..60467c9 --- /dev/null +++ b/cdf/src/cdf-prop-value/cdf-util/src/test/java/org/onap/dcae/cdf/util/AppTest.java @@ -0,0 +1,53 @@ +/* + Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this code except in compliance + with the License. You may obtain a copy of the License + at http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied. See the License for the specific language governing + permissions and limitations under the License. + +*/ +package org.onap.dcae.cdf.util; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +/** + * Unit test for simple App. + */ +public class AppTest + extends TestCase +{ + /** + * Create the test case + * + * @param testName name of the test case + */ + public AppTest( String testName ) + { + super( testName ); + } + + /** + * @return the suite of tests being tested + */ + public static Test suite() + { + return new TestSuite( AppTest.class ); + } + + /** + * Rigourous Test :-) + */ + public void testApp() + { + assertTrue( true ); + } +} diff --git a/cdf/src/cdf-prop-value/makefile b/cdf/src/cdf-prop-value/makefile new file mode 100644 index 0000000..194ad29 --- /dev/null +++ b/cdf/src/cdf-prop-value/makefile @@ -0,0 +1,13 @@ +all: + +build: + cd cdf-util/src/main/java && $(MAKE) build + cd cdf-prop-value/src/main/java && $(MAKE) build + +javadocs: + cd cdf-util/src/main/java && $(MAKE) javadocs + cd cdf-prop-value/src/main/java && $(MAKE) javadocs + +clean: + cd cdf-util/src/main/java && $(MAKE) clean + cd cdf-prop-value/src/main/java && $(MAKE) clean diff --git a/cdf/src/common/postinst b/cdf/src/common/postinst new file mode 100755 index 0000000..875b535 --- /dev/null +++ b/cdf/src/common/postinst @@ -0,0 +1,50 @@ +#!/bin/bash +# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this code except in compliance +# with the License. You may obtain a copy of the License +# at http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +# implied. See the License for the specific language governing +# permissions and limitations under the License. + + +exec 1> /tmp/cdf.out 2>&1 +set -x +if [ -d /opt/app/postgresql-9.5.2 ] +then export ONAP=false NOTONAP=true +else export ONAP=true NOTONAP=false +fi + +echo STARTING $0 $(date) +umask 0 +echo STARTING $0 $(date) >> /tmp/pgaas.inst.report + +die() +{ + echo $0: "$@" 1>&2 + echo $0: "$@" + umask 022 + echo $0: "$@" >> /tmp/pgaas-failures + exit 1 +} + +id +umask 022 + +# randomize the the CDF package +ranval=$(dd if=/dev/urandom count=1 ibs=8 2>/dev/null | od -x -w1000 | sed -e 's/^0000000 //' -e 's/ //g' -e 1q) +CDFCFG=${INSTALL_ROOT}/opt/app/cdf/lib/cdf.cfg +rm -f ${CDFCFG} +sed -e 's/${HOSTNAME}/'"$(hostname -f)"'/' -e 's/${RANDOM}/'"$ranval"'0/' < ${INSTALL_ROOT}/opt/app/cdf/lib/cdf.cfg.tmpl > ${CDFCFG} +chown postgres:postgres ${CDFCFG} + +echo ENDING $0 $(date) +echo ENDING $0 $(date) >> /tmp/pgaas.inst.report +if $NOTONAP +then sed -n '/^STARTING/,/^ENDING/p' `dirname $0`/../../proc_out >> /tmp/pgaas.inst.report +fi diff --git a/cdf/src/makefile b/cdf/src/makefile new file mode 100644 index 0000000..fdd7748 --- /dev/null +++ b/cdf/src/makefile @@ -0,0 +1,53 @@ + +DEVBIN=../../bin +PKG=cdf +REPACKAGEDEBIANOPTS= + +INS= ../install +INSSTG= $(INS)/stage +INSCOM= $(INS)/common +KEEP= + +all: + +clean-stage: + rm -rf $(INSSTG) + +clean-common: + rm -rf $(INSCOM) + +clean-ins: clean-stage clean-common + rm -rf $(INS) + +clean: clean-ins + rm -rf *~ + cd cdf-prop-value && $(MAKE) clean + +build: javadocs build-java + +build-java: + cd cdf-prop-value && $(MAKE) build + +javadocs: + cd cdf-prop-value && $(MAKE) javadocs + +stage: build clean-stage clean-common + mkdir -p $(INS) + find stage common ! -name makefile ! -name '*~' | cpio -pudmv $(INS) + cp -p cdf-prop-value/cdf-prop-value/src/main/java/cdf-prop-value.jar $(INS)/stage/opt/app/cdf/lib/cdf-prop-value-1.1.0.jar + cp -p cdf-prop-value/cdf-prop-value/src/main/java/cdf-prop-value.jar $(INS)/stage/opt/app/cdf/lib/cdf-prop-value.jar + cp -p cdf-prop-value/cdf-util/src/main/java/cdf-util.jar $(INS)/stage/opt/app/cdf/lib/jars/cdf-util-1.1.0.jar + cp -p cdf-prop-value/cdf-util/src/main/java/cdf-util.jar $(INS)/stage/opt/app/cdf/lib/jars/cdf-util.jar + chmod a+x $(INSCOM)/* + + +debian: stage + sed 's/$${RELLONG}/$(RELLONG)/' < repackage.yaml > $(INS)/repackage.yaml + repackage -b debian $(REPACKAGEDEBIANOPTS) -d $(INS) -u -M "{datetime},LATEST" -y $(INS)/repackage.yaml + @echo debian built + +upload-javadocs: javadocs + cd cdf-prop-value && find cdf-*/src/main/java/javadoc -type f | while read f; do \ + curl -k --user "$${ONAP_NEXUS_USER}:$${ONAP_NEXUS_PASSWORD}" --upload-file "$$f" "$${ONAP_NEXUS_JAVADOC}/org.onap.dcae.storage.cdf/1.1.0/$$f"; \ + done + diff --git a/cdf/src/repackage.json b/cdf/src/repackage.json new file mode 100644 index 0000000..4618183 --- /dev/null +++ b/cdf/src/repackage.json @@ -0,0 +1,29 @@ +{ + "debian": { + "groupId": "org.onap.dcae.storage.pgaas", + "conflicts": [], + "replaces": [], + "externalDependencies": [ + { + "libgetopt-java": ">= 1.0.14" + } + ] + }, + "fileGroup": "postgres", + "internalDependencies": [], + "fileUser": "postgres", + "executionUser": "postgres", + "executionGroup": "postgres", + "docker": { + "tag": "latest", + "externalDependencies": [] + }, + "version": "${RELLONG}", + "directoryTreeTops": { + "/opt": "/opt/app/cdf" + }, + "maintainer": "ONAP <dcae@lists.onap.org>", + "groupId": "org.onap.dcae.storage.pgaas", + "applicationName": "cdf", + "description": " PostgreSQL as a Service main scripts " +}
\ No newline at end of file diff --git a/cdf/src/stage/opt/app/cdf/bin/getpropvalue b/cdf/src/stage/opt/app/cdf/bin/getpropvalue new file mode 100755 index 0000000..78a74b2 --- /dev/null +++ b/cdf/src/stage/opt/app/cdf/bin/getpropvalue @@ -0,0 +1,31 @@ +#!/bin/bash +# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this code except in compliance +# with the License. You may obtain a copy of the License +# at http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +# implied. See the License for the specific language governing +# permissions and limitations under the License. + + +P=/opt/cdf +CDF=/opt/app/cdf + +export PATH=/opt/java/jdk/jdk170/bin:$PATH +export CLASSPATH=$CDF/lib/cdf-prop-value.jar:$CDF/lib/jars/cdf-util.jar +if [ -f $CDF/lib/jars/gnu_getopt.jar ] +then CLASSPATH=$CLASSPATH:$CDF/lib/jars/gnu_getopt.jar ] +elif [ -f /usr/share/java/gnu-getopt.jar ] +then CLASSPATH=$CLASSPATH:/usr/share/java/gnu-getopt.jar +else echo "$0: Cannot find gnu-getopt.jar" 1>&2; exit 1 +fi + +PropValue=org.onap.dcae.cdf.CdfPropValue +CfgFile=$CDF/lib/cdf.cfg + +java $PropValue -f $CfgFile "$@" diff --git a/cdf/src/stage/opt/app/cdf/bin/setencryptedvalues b/cdf/src/stage/opt/app/cdf/bin/setencryptedvalues new file mode 100755 index 0000000..c60fbad --- /dev/null +++ b/cdf/src/stage/opt/app/cdf/bin/setencryptedvalues @@ -0,0 +1,30 @@ +#!/bin/bash +# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this code except in compliance +# with the License. You may obtain a copy of the License +# at http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +# implied. See the License for the specific language governing +# permissions and limitations under the License. + + +P=/opt/cdf +CDF=/opt/app/cdf + +export PATH=/opt/java/jdk/jdk170/bin:$PATH +export CLASSPATH=$CDF/lib/cdf-prop-value.jar:$CDF/lib/jars/cdf-util.jar +if [ -f $CDF/lib/jars/gnu_getopt.jar ] +then CLASSPATH=$CLASSPATH:$CDF/lib/jars/gnu_getopt.jar ] +elif [ -f /usr/share/java/gnu-getopt.jar ] +then CLASSPATH=$CLASSPATH:/usr/share/java/gnu-getopt.jar +else echo "$0: Cannot find gnu-getopt.jar" 1>&2; exit 1 +fi + +PropValue=org.onap.dcae.cdf.CdfPropValue + +java $PropValue -E "$@" diff --git a/cdf/src/stage/opt/app/cdf/lib/cdf.cfg.tmpl b/cdf/src/stage/opt/app/cdf/lib/cdf.cfg.tmpl new file mode 100644 index 0000000..7292963 --- /dev/null +++ b/cdf/src/stage/opt/app/cdf/lib/cdf.cfg.tmpl @@ -0,0 +1,18 @@ +# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this code except in compliance +# with the License. You may obtain a copy of the License +# at http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +# implied. See the License for the specific language governing +# permissions and limitations under the License. + + +#### +#### nothing should need to change below +#### +Global_Title="This is the Common DCAE Framework 1.0 ${HOSTNAME} ${RANDOM}" diff --git a/cdf/src/stage/opt/app/cdf/lib/jars/which_files b/cdf/src/stage/opt/app/cdf/lib/jars/which_files new file mode 100644 index 0000000..47a7ba7 --- /dev/null +++ b/cdf/src/stage/opt/app/cdf/lib/jars/which_files @@ -0,0 +1,3 @@ +The following files were installed here: + +gnu_getopt.jar |