summaryrefslogtreecommitdiffstats
path: root/src/main/java/org/openecomp/sparky/util
diff options
context:
space:
mode:
authorARULNA <arul.nambi@amdocs.com>2017-06-12 16:41:12 -0400
committerARULNA <arul.nambi@amdocs.com>2017-06-12 16:41:28 -0400
commitb4922d319d293894fddd512d29b5f0d1411915d9 (patch)
tree36cec7575f1631aad41d7b1131d6352847ea0de2 /src/main/java/org/openecomp/sparky/util
parent19dacd2ba38e345eeb5fcfbfe37d615602e8ea44 (diff)
Initial commit for AAI-UI(sparky-backend)
Change-Id: I785397ed4197663cdf0c1351041d2f708ed08763 Signed-off-by: ARULNA <arul.nambi@amdocs.com>
Diffstat (limited to 'src/main/java/org/openecomp/sparky/util')
-rw-r--r--src/main/java/org/openecomp/sparky/util/ConfigHelper.java194
-rw-r--r--src/main/java/org/openecomp/sparky/util/EncryptConvertor.java150
-rw-r--r--src/main/java/org/openecomp/sparky/util/Encryptor.java137
-rw-r--r--src/main/java/org/openecomp/sparky/util/ErrorUtil.java63
-rw-r--r--src/main/java/org/openecomp/sparky/util/JsonXmlConverter.java80
-rw-r--r--src/main/java/org/openecomp/sparky/util/KeystoreBuilder.java525
-rw-r--r--src/main/java/org/openecomp/sparky/util/NodeUtils.java714
-rw-r--r--src/main/java/org/openecomp/sparky/util/RawByteHelper.java177
-rw-r--r--src/main/java/org/openecomp/sparky/util/ServletUtils.java164
-rw-r--r--src/main/java/org/openecomp/sparky/util/SuggestionsPermutation.java82
-rw-r--r--src/main/java/org/openecomp/sparky/util/TreeWalker.java137
11 files changed, 2423 insertions, 0 deletions
diff --git a/src/main/java/org/openecomp/sparky/util/ConfigHelper.java b/src/main/java/org/openecomp/sparky/util/ConfigHelper.java
new file mode 100644
index 0000000..5d660ff
--- /dev/null
+++ b/src/main/java/org/openecomp/sparky/util/ConfigHelper.java
@@ -0,0 +1,194 @@
+/**
+ * ============LICENSE_START===================================================
+ * SPARKY (AAI UI service)
+ * ============================================================================
+ * Copyright © 2017 AT&T Intellectual Property.
+ * Copyright © 2017 Amdocs
+ * All rights reserved.
+ * ============================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file 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.
+ * ============LICENSE_END=====================================================
+ *
+ * ECOMP and OpenECOMP are trademarks
+ * and service marks of AT&T Intellectual Property.
+ */
+
+package org.openecomp.sparky.util;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Properties;
+import java.util.Set;
+
+import org.openecomp.cl.api.Logger;
+import org.openecomp.cl.eelf.LoggerFactory;
+import org.openecomp.sparky.logging.AaiUiMsgs;
+
+/**
+ * The Class ConfigHelper.
+ */
+public class ConfigHelper {
+
+ private static final Logger LOG = LoggerFactory.getInstance().getLogger(ConfigHelper.class);
+
+ /**
+ * Gets the config with prefix.
+ *
+ * @param configPrefix the config prefix
+ * @param properties the properties
+ * @return the config with prefix
+ */
+ public static Properties getConfigWithPrefix(String configPrefix, Properties properties) {
+
+ /*
+ * The idea here is collect properties groups prefixed with the same origin
+ */
+
+ Set<Object> set = properties.keySet();
+ Properties newProps = new Properties();
+
+ for (Object k : set) {
+ String ks = (String) k;
+ if (ks.startsWith(configPrefix)) {
+
+ String temp = ks.replaceFirst(configPrefix + ".", "");
+ newProps.setProperty(temp, properties.getProperty(ks));
+ }
+ }
+
+ return newProps;
+ }
+
+ /**
+ * Load config.
+ *
+ * @param fileName the file name
+ * @return the properties
+ * @throws Exception the exception
+ */
+ public static Properties loadConfig(String fileName) throws Exception {
+
+ String basePath = System.getProperty("user.dir");
+ InputStream fileInputStream = new FileInputStream(basePath + "//" + fileName);
+
+ Properties props = new Properties();
+ props.load(fileInputStream);
+
+ return props;
+ }
+
+ /**
+ * Load config from explicit path.
+ *
+ * @param fileName the file name
+ * @return the properties
+ */
+ public static Properties loadConfigFromExplicitPath(String fileName) {
+
+ Properties props = new Properties();
+
+ try {
+ InputStream fileInputStream = new FileInputStream(fileName);
+ props.load(fileInputStream);
+ } catch (Exception exc) {
+ LOG.warn(AaiUiMsgs.CONFIG_NOT_FOUND_VERBOSE, fileName, exc.getLocalizedMessage());
+ }
+
+ return props;
+ }
+
+ /**
+ * Property fetch.
+ *
+ * @param config the config
+ * @param propName the prop name
+ * @param defaultValue the default value
+ * @return the string
+ */
+ public static String propertyFetch(Properties config, String propName, String defaultValue) {
+ return config.getProperty(propName, defaultValue);
+ }
+
+ public static boolean isEssDevModeEnabled() {
+ return Boolean.parseBoolean(System.getProperty("isEssDevMode", "false"));
+ }
+
+ /**
+ * Gets the filepath.
+ *
+ * @param fileName the file name
+ * @param isRelativePath the is relative path
+ * @return the filepath
+ */
+ public static String getFilepath(String fileName, boolean isRelativePath) {
+
+ String filepath = null;
+
+ if (isRelativePath) {
+ filepath = System.getProperty("user.dir") + "/" + fileName;
+
+ } else {
+ filepath = fileName;
+ }
+
+ return filepath;
+
+ }
+
+ /**
+ * Gets the file contents.
+ *
+ * @param fileName the file name
+ * @return the file contents
+ * @throws IOException Signals that an I/O exception has occurred.
+ */
+ public static String getFileContents(String fileName) throws IOException {
+
+ LOG.debug(AaiUiMsgs.FILE_READ_IN_PROGRESS, fileName);
+
+ File file = new File(fileName);
+
+ if (!file.exists()) {
+ throw new FileNotFoundException("Failed to load file = " + fileName);
+ }
+
+ if (file.exists() && !file.isDirectory()) {
+ BufferedReader br = new BufferedReader(new FileReader(file));
+ try {
+ StringBuilder sb = new StringBuilder();
+ String line = br.readLine();
+
+ while (line != null) {
+ sb.append(line);
+ sb.append(System.lineSeparator());
+ line = br.readLine();
+ }
+
+ return sb.toString();
+ } finally {
+ br.close();
+ }
+ } else {
+ LOG.warn(AaiUiMsgs.FILE_NOT_FOUND, fileName);
+ }
+
+ return null;
+
+ }
+
+}
diff --git a/src/main/java/org/openecomp/sparky/util/EncryptConvertor.java b/src/main/java/org/openecomp/sparky/util/EncryptConvertor.java
new file mode 100644
index 0000000..6b03302
--- /dev/null
+++ b/src/main/java/org/openecomp/sparky/util/EncryptConvertor.java
@@ -0,0 +1,150 @@
+/**
+ * ============LICENSE_START===================================================
+ * SPARKY (AAI UI service)
+ * ============================================================================
+ * Copyright © 2017 AT&T Intellectual Property.
+ * Copyright © 2017 Amdocs
+ * All rights reserved.
+ * ============================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file 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.
+ * ============LICENSE_END=====================================================
+ *
+ * ECOMP and OpenECOMP are trademarks
+ * and service marks of AT&T Intellectual Property.
+ */
+
+package org.openecomp.sparky.util;
+
+/**
+ * The Class EncryptConvertor.
+ */
+public class EncryptConvertor {
+
+ private static final char[] HEX_CHARS = "0123456789abcdef".toCharArray();
+
+ /**
+ * toHexString(String) - convert a string into its hex equivalent.
+ *
+ * @param buf the buf
+ * @return the string
+ */
+ public static final String toHexString(String buf) {
+ if (buf == null) {
+ return "";
+ }
+ return toHexString(buf.getBytes());
+ }
+
+ /**
+ * toHexString(byte[]) - convert a byte-string into its hex equivalent.
+ *
+ * @param buf the buf
+ * @return the string
+ */
+ public static final 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);
+ }
+
+ /**
+ * Convert a hex string to its equivalent value.
+ *
+ * @param hexString the hex string
+ * @return the string
+ * @throws Exception the exception
+ */
+ public static final String stringFromHex(String hexString) throws Exception {
+ if (hexString == null) {
+ return "";
+ }
+ return stringFromHex(hexString.toCharArray());
+ }
+
+ /**
+ * String from hex.
+ *
+ * @param hexCharArray the hex char array
+ * @return the string
+ * @throws Exception the exception
+ */
+ public static final String stringFromHex(char[] hexCharArray) throws Exception {
+ if (hexCharArray == null) {
+ return "";
+ }
+ return new String(bytesFromHex(hexCharArray));
+ }
+
+ /**
+ * Bytes from hex.
+ *
+ * @param hexString the hex string
+ * @return the byte[]
+ * @throws Exception the exception
+ */
+ public static final byte[] bytesFromHex(String hexString) throws Exception {
+ if (hexString == null) {
+ return new byte[0];
+ }
+ return bytesFromHex(hexString.toCharArray());
+ }
+
+ /**
+ * Bytes from hex.
+ *
+ * @param hexCharArray the hex char array
+ * @return the byte[]
+ * @throws Exception the exception
+ */
+ public static final 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: '" + String.valueOf(hexCharArray) + "'");
+ }
+ byte[] txtInByte = new byte[len / 2];
+ int counter = 0;
+ for (int i = 0; i < len; i += 2) {
+ txtInByte[counter++] =
+ (byte) (((fromHexDigit(hexCharArray[i], i) << 4) | fromHexDigit(hexCharArray[i + 1], i))
+ & 0xFF);
+ }
+ return txtInByte;
+ }
+
+ /**
+ * From hex digit.
+ *
+ * @param ch the ch
+ * @param index the index
+ * @return the int
+ * @throws Exception the exception
+ */
+ protected static final 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/src/main/java/org/openecomp/sparky/util/Encryptor.java b/src/main/java/org/openecomp/sparky/util/Encryptor.java
new file mode 100644
index 0000000..87abe16
--- /dev/null
+++ b/src/main/java/org/openecomp/sparky/util/Encryptor.java
@@ -0,0 +1,137 @@
+/**
+ * ============LICENSE_START===================================================
+ * SPARKY (AAI UI service)
+ * ============================================================================
+ * Copyright © 2017 AT&T Intellectual Property.
+ * Copyright © 2017 Amdocs
+ * All rights reserved.
+ * ============================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file 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.
+ * ============LICENSE_END=====================================================
+ *
+ * ECOMP and OpenECOMP are trademarks
+ * and service marks of AT&T Intellectual Property.
+ */
+
+package org.openecomp.sparky.util;
+
+import org.apache.commons.cli.BasicParser;
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.CommandLineParser;
+import org.apache.commons.cli.Options;
+import org.apache.commons.cli.ParseException;
+import org.eclipse.jetty.util.security.Password;
+
+/**
+ * The Class Encryptor.
+ */
+public class Encryptor {
+
+ /**
+ * Instantiates a new encryptor.
+ */
+ public Encryptor() {
+ }
+
+ /**
+ * Decrypt value.
+ *
+ * @param value the value
+ * @return the string
+ */
+ public String decryptValue(String value) {
+ String decyptedValue = "";
+
+ try {
+ decyptedValue = Password.deobfuscate(value);
+ } catch (Exception exc) {
+ System.err.println("Cannot decrypt '" + value + "': " + exc.toString());
+ }
+
+ return decyptedValue;
+ }
+
+ /**
+ * Usage.
+ */
+ public static void usage() {
+ usage(null);
+ }
+
+ /**
+ * Usage.
+ *
+ * @param msg the msg
+ */
+ public static void usage(String msg) {
+ if (msg != null) {
+ System.err.println(msg);
+ }
+ System.err.println("Usage: java Encryptor -e value");
+ System.err.println("\tEncrypt the given value");
+ System.err.println("Usage: java Encryptor -d value");
+ System.err.println("\tDecrypt the given value");
+ System.exit(1);
+ }
+
+ /**
+ * The main method.
+ *
+ * @param args the arguments
+ */
+ public static void main(String[] args) {
+
+ Options options = new Options();
+ options.addOption("d", true, "value to decrypt");
+ options.addOption("h", false, "show help");
+ options.addOption("?", false, "show help");
+
+ String value = null;
+ boolean encrypt = false;
+ boolean decrypt = false;
+
+ CommandLineParser parser = new BasicParser();
+ CommandLine cmd = null;
+
+ try {
+ cmd = parser.parse(options, args);
+
+ if (cmd.hasOption("d")) {
+ value = cmd.getOptionValue("d");
+ decrypt = true;
+ }
+
+ if (cmd.hasOption("?") || cmd.hasOption("h")) {
+ usage();
+ System.exit(0);
+ }
+
+ if ((encrypt && decrypt) || (!encrypt && !decrypt)) {
+ usage("Must specify one (and only one) of the -e or -d options");
+ }
+
+ Encryptor encryptor = new Encryptor();
+
+ if (decrypt) {
+ String out = encryptor.decryptValue(value);
+ System.out.println(out);
+ }
+ } catch (ParseException exc) {
+ System.out.println("Failed to parse command line properties: " + exc.toString());
+ } catch (Exception exc) {
+ System.out.println("Failure: " + exc.toString());
+ }
+
+ System.exit(0);
+ }
+}
diff --git a/src/main/java/org/openecomp/sparky/util/ErrorUtil.java b/src/main/java/org/openecomp/sparky/util/ErrorUtil.java
new file mode 100644
index 0000000..9cea8b3
--- /dev/null
+++ b/src/main/java/org/openecomp/sparky/util/ErrorUtil.java
@@ -0,0 +1,63 @@
+/**
+ * ============LICENSE_START===================================================
+ * SPARKY (AAI UI service)
+ * ============================================================================
+ * Copyright © 2017 AT&T Intellectual Property.
+ * Copyright © 2017 Amdocs
+ * All rights reserved.
+ * ============================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file 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.
+ * ============LICENSE_END=====================================================
+ *
+ * ECOMP and OpenECOMP are trademarks
+ * and service marks of AT&T Intellectual Property.
+ */
+
+
+package org.openecomp.sparky.util;
+
+/**
+ * The Class ErrorUtil.
+ */
+public class ErrorUtil {
+
+ /**
+ * Extract stack trace elements.
+ *
+ * @param maxNumberOfElementsToCapture the max number of elements to capture
+ * @param exc the exc
+ * @return the string
+ */
+ public static String extractStackTraceElements(int maxNumberOfElementsToCapture, Exception exc) {
+ StringBuilder sb = new StringBuilder(128);
+
+ StackTraceElement[] stackTraceElements = exc.getStackTrace();
+
+ if (stackTraceElements != null) {
+
+ /*
+ * We want to avoid an index out-of-bounds error, so we will make sure to only extract the
+ * number of frames from the stack trace that actually exist.
+ */
+
+ int numFramesToExtract = Math.min(maxNumberOfElementsToCapture, stackTraceElements.length);
+
+ for (int x = 0; x < numFramesToExtract; x++) {
+ sb.append(stackTraceElements[x]).append("\n");
+ }
+
+ }
+
+ return sb.toString();
+ }
+}
diff --git a/src/main/java/org/openecomp/sparky/util/JsonXmlConverter.java b/src/main/java/org/openecomp/sparky/util/JsonXmlConverter.java
new file mode 100644
index 0000000..845e0af
--- /dev/null
+++ b/src/main/java/org/openecomp/sparky/util/JsonXmlConverter.java
@@ -0,0 +1,80 @@
+/**
+ * ============LICENSE_START===================================================
+ * SPARKY (AAI UI service)
+ * ============================================================================
+ * Copyright © 2017 AT&T Intellectual Property.
+ * Copyright © 2017 Amdocs
+ * All rights reserved.
+ * ============================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file 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.
+ * ============LICENSE_END=====================================================
+ *
+ * ECOMP and OpenECOMP are trademarks
+ * and service marks of AT&T Intellectual Property.
+ */
+
+package org.openecomp.sparky.util;
+
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+import org.json.XML;
+
+/**
+ * The Class JsonXmlConverter.
+ */
+public class JsonXmlConverter {
+
+ /**
+ * Checks if is valid json.
+ *
+ * @param text the text
+ * @return true, if is valid json
+ */
+ public static boolean isValidJson(String text) {
+ try {
+ new JSONObject(text);
+ } catch (JSONException ex) {
+ try {
+ new JSONArray(text);
+ } catch (JSONException ex1) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ /**
+ * Convert jsonto xml.
+ *
+ * @param jsonText the json text
+ * @return the string
+ */
+ public static String convertJsontoXml(String jsonText) {
+ JSONObject jsonObj = new JSONObject(jsonText);
+ String xmlText = XML.toString(jsonObj);
+ return xmlText;
+ }
+
+ /**
+ * Convert xmlto json.
+ *
+ * @param xmlText the xml text
+ * @return the string
+ */
+ public static String convertXmltoJson(String xmlText) {
+ JSONObject jsonObj = XML.toJSONObject(xmlText);
+ return jsonObj.toString();
+ }
+}
diff --git a/src/main/java/org/openecomp/sparky/util/KeystoreBuilder.java b/src/main/java/org/openecomp/sparky/util/KeystoreBuilder.java
new file mode 100644
index 0000000..6361e95
--- /dev/null
+++ b/src/main/java/org/openecomp/sparky/util/KeystoreBuilder.java
@@ -0,0 +1,525 @@
+/**
+ * ============LICENSE_START===================================================
+ * SPARKY (AAI UI service)
+ * ============================================================================
+ * Copyright © 2017 AT&T Intellectual Property.
+ * Copyright © 2017 Amdocs
+ * All rights reserved.
+ * ============================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file 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.
+ * ============LICENSE_END=====================================================
+ *
+ * ECOMP and OpenECOMP are trademarks
+ * and service marks of AT&T Intellectual Property.
+ */
+
+package org.openecomp.sparky.util;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.UnknownHostException;
+import java.security.KeyManagementException;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.security.cert.CertificateEncodingException;
+import java.security.cert.CertificateException;
+import java.security.cert.CertificateParsingException;
+import java.security.cert.X509Certificate;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLException;
+import javax.net.ssl.SSLSocket;
+import javax.net.ssl.SSLSocketFactory;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.TrustManagerFactory;
+import javax.net.ssl.X509TrustManager;
+
+/**
+ * The Class KeystoreBuilder.
+ */
+public class KeystoreBuilder {
+
+ /**
+ * The Class EndPoint.
+ */
+ private class EndPoint {
+ private String hostname;
+ private int port;
+
+ /**
+ * Instantiates a new end point.
+ */
+ @SuppressWarnings("unused")
+ public EndPoint() {}
+
+ /**
+ * Instantiates a new end point.
+ *
+ * @param host the host
+ * @param port the port
+ */
+ public EndPoint(String host, int port) {
+ this.hostname = host;
+ this.port = port;
+ }
+
+ public String getHostname() {
+ return hostname;
+ }
+
+ @SuppressWarnings("unused")
+ public void setHostname(String hostname) {
+ this.hostname = hostname;
+ }
+
+ public int getPort() {
+ return port;
+ }
+
+ public void setPort(int port) {
+ this.port = port;
+ }
+
+ /* (non-Javadoc)
+ * @see java.lang.Object#toString()
+ */
+ @Override
+ public String toString() {
+ return "EndPoint [hostname=" + hostname + ", port=" + port + "]";
+ }
+
+ }
+
+ private List<EndPoint> endpoints = new ArrayList<EndPoint>();
+
+ /**
+ * Initialize end points list.
+ *
+ * @param endpointList the endpoint list
+ */
+ private void initializeEndPointsList(String endpointList) {
+ String[] endpointUris = endpointList.split(";");
+
+ for (String endpointUri : endpointUris) {
+
+ String ipAndPort = endpointUri.replaceAll("http://", "");
+ ipAndPort = endpointUri.replaceAll("https://", "");
+
+ // System.out.println("ipAndPortUrl = " + ipAndPort);
+
+ String[] hostAndPort = ipAndPort.split(":");
+
+ String hostname = hostAndPort[0];
+ int port = Integer.parseInt(hostAndPort[1]);
+
+ EndPoint ep = new EndPoint(hostname, port);
+ endpoints.add(ep);
+ }
+
+ }
+
+ /**
+ * Instantiates a new keystore builder.
+ *
+ * @param endpointList the endpoint list
+ * @throws NoSuchAlgorithmException the no such algorithm exception
+ */
+ public KeystoreBuilder(String endpointList) throws NoSuchAlgorithmException {
+ initializeEndPointsList(endpointList);
+ sha1 = MessageDigest.getInstance("SHA1");
+ md5 = MessageDigest.getInstance("MD5");
+ }
+
+ private static final String SEP = File.separator;
+ private SavingTrustManager savingTrustManager;
+ private SSLSocketFactory sslSocketFactory;
+ private MessageDigest sha1;
+ private MessageDigest md5;
+ private KeyStore ks;
+ private String keystoreFileName;
+ private String keystorePassword;
+ private boolean dumpCertDetails = false;
+
+ public void setDumpCertDetails(boolean shouldSet) {
+ dumpCertDetails = shouldSet;
+ }
+
+ /**
+ * Update keystore.
+ *
+ * @param keystoreFileName the keystore file name
+ * @param keystorePassword the keystore password
+ * @throws KeyStoreException the key store exception
+ * @throws NoSuchAlgorithmException the no such algorithm exception
+ * @throws CertificateException the certificate exception
+ * @throws IOException Signals that an I/O exception has occurred.
+ * @throws KeyManagementException the key management exception
+ */
+ public void updateKeystore(String keystoreFileName, String keystorePassword)
+ throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException,
+ KeyManagementException {
+
+ this.keystoreFileName = keystoreFileName;
+ this.keystorePassword = keystorePassword;
+
+ File file = new File(keystoreFileName);
+ String password = keystorePassword;
+
+ if (file.isFile() == false) {
+
+ File dir = new File(System.getProperty("java.home") + SEP + "lib" + SEP + "security");
+ file = new File(dir, "jssecacerts");
+ if (file.isFile() == false) {
+
+ file = new File(dir, "cacerts");
+ System.out.println("keystore file doesn't exist, preloading new file with cacerts");
+
+ } else {
+ System.out.println("keystore file doesn't exist, preloading new file with jssecacerts");
+ }
+ password = "changeit";
+
+ }
+
+ InputStream in = new FileInputStream(file);
+ ks = KeyStore.getInstance(KeyStore.getDefaultType());
+ ks.load(in, password.toCharArray());
+ in.close();
+
+ SSLContext context = SSLContext.getInstance("TLS");
+ TrustManagerFactory tmf =
+ TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
+ tmf.init(ks);
+ X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
+ savingTrustManager = new SavingTrustManager(defaultTrustManager);
+ context.init(null, new TrustManager[] {savingTrustManager}, null);
+ sslSocketFactory = context.getSocketFactory();
+
+ System.out.println("About to add the following endpoint server certificates to the keystore:");
+ for (EndPoint ep : endpoints) {
+ System.out.println("\t--------------------------");
+ System.out.println("\t" + ep.toString());
+
+ X509Certificate[] certChain =
+ getCertificateChainForRemoteEndpoint(ep.getHostname(), ep.getPort());
+
+ if (certChain == null) {
+ System.out.println("Could not obtain server certificate chain");
+ return;
+ }
+
+ dumpCertChainInfo(certChain);
+
+ updateKeyStoreWithCertChain(certChain);
+
+ }
+
+ }
+
+ /**
+ * Gets the certificate chain for remote endpoint.
+ *
+ * @param hostname the hostname
+ * @param port the port
+ * @return the certificate chain for remote endpoint
+ * @throws UnknownHostException the unknown host exception
+ * @throws IOException Signals that an I/O exception has occurred.
+ */
+ private X509Certificate[] getCertificateChainForRemoteEndpoint(String hostname, int port)
+ throws UnknownHostException, IOException {
+
+ System.out.println("Opening connection to localhost:8442..");
+ SSLSocket socket = (SSLSocket) sslSocketFactory.createSocket("aai-int1.dev.att.com", 8440);
+ socket.setSoTimeout(10000);
+
+ try {
+ System.out.println("Starting SSL handshake...");
+ socket.startHandshake();
+ socket.close();
+ System.out.println("\nNo errors, certificate is already trusted");
+ System.exit(0);
+ } catch (SSLException exc) {
+ System.out.println("\nCaught SSL exception, we are not authorized to access this server yet");
+ // e.printStackTrace(System.out);
+ }
+
+ return savingTrustManager.chain;
+
+ }
+
+ /**
+ * Dump cert chain info.
+ *
+ * @param chain the chain
+ * @throws NoSuchAlgorithmException the no such algorithm exception
+ * @throws CertificateEncodingException the certificate encoding exception
+ * @throws CertificateParsingException the certificate parsing exception
+ */
+ private void dumpCertChainInfo(X509Certificate[] chain)
+ throws NoSuchAlgorithmException, CertificateEncodingException, CertificateParsingException {
+
+ System.out.println();
+ System.out.println("Server sent " + chain.length + " certificate(s):");
+ System.out.println();
+
+ for (int i = 0; i < chain.length; i++) {
+ X509Certificate cert = chain[i];
+
+ if (dumpCertDetails) {
+ System.out.println("Full cert details @ index = " + i + " \n" + cert.toString());
+ }
+
+ System.out.println("Subject: " + cert.getSubjectDN());
+ System.out.println("Issuer: " + cert.getIssuerDN());
+ System.out.println("SubjectAlternativeNames: ");
+
+ /*
+ * RFC-5280, pg. 38, section 4.2.1.6 ( Subject Alternative Names )
+ *
+ * Finally, the semantics of subject alternative names that include wildcard characters (e.g.,
+ * as a placeholder for a set of names) are not addressed by this specification. Applications
+ * with specific requirements MAY use such names, but they must define the semantics.
+ *
+ * id-ce-subjectAltName OBJECT IDENTIFIER ::= { id-ce 17 }
+ *
+ * SubjectAltName ::= GeneralNames
+ *
+ * GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
+ *
+ * GeneralName ::= CHOICE { otherName [0] OtherName, rfc822Name [1] IA5String, dNSName [2]
+ * IA5String, <-- the 2 in the output is a type operand x400Address [3] ORAddress,
+ * directoryName [4] Name, ediPartyName [5] EDIPartyName, uniformResourceIdentifier [6]
+ * IA5String, iPAddress [7] OCTET STRING, registeredID [8] OBJECT IDENTIFIER }
+ *
+ * OtherName ::= SEQUENCE { type-id OBJECT IDENTIFIER, value [0] EXPLICIT ANY DEFINED BY
+ * type-id }
+ *
+ * EDIPartyName ::= SEQUENCE { nameAssigner [0] DirectoryString OPTIONAL, partyName [1]
+ * DirectoryString }
+ *
+ */
+
+ Collection<List<?>> sans = cert.getSubjectAlternativeNames();
+
+ for (List<?> san : sans) {
+
+ /*
+ * It seems the structure of the array elements contained within the SAN is: [<sanType>,
+ * <sanValue>]*
+ *
+ */
+
+ int type = ((Integer) san.get(0)).intValue();
+ String typeStr = getSanType(type);
+ String value = (String) san.get(1);
+
+ System.out.println(String.format("\tType:'%s', Value: '%s'.", typeStr, value));
+
+ }
+
+ }
+
+ }
+
+ /**
+ * Gets the subject alternative names.
+ *
+ * @param cert the cert
+ * @return the subject alternative names
+ * @throws CertificateParsingException the certificate parsing exception
+ */
+ private List<String> getSubjectAlternativeNames(X509Certificate cert)
+ throws CertificateParsingException {
+
+ Collection<List<?>> sans = cert.getSubjectAlternativeNames();
+ List<String> subjectAlternativeNames = new ArrayList<String>();
+
+ for (List<?> san : sans) {
+
+ /*
+ * It seems the structure of the array elements contained within the SAN is: [<sanType>,
+ * <sanValue>]*
+ *
+ */
+
+ String value = (String) san.get(1);
+ subjectAlternativeNames.add(value);
+ }
+
+ return subjectAlternativeNames;
+ }
+
+ /**
+ * Update key store with cert chain.
+ *
+ * @param chain the chain
+ * @throws NoSuchAlgorithmException the no such algorithm exception
+ * @throws KeyStoreException the key store exception
+ * @throws CertificateException the certificate exception
+ * @throws IOException Signals that an I/O exception has occurred.
+ */
+ private void updateKeyStoreWithCertChain(X509Certificate[] chain)
+ throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException {
+
+ for (X509Certificate cert : chain) {
+
+ List<String> sans = getSubjectAlternativeNames(cert);
+
+ for (String san : sans) {
+ ks.setCertificateEntry(san, cert);
+ System.out.println(
+ "Added certificate to keystore '" + keystoreFileName + "' using alias '" + san + "'");
+ }
+ }
+
+ OutputStream out = new FileOutputStream(keystoreFileName);
+ ks.store(out, keystorePassword.toCharArray());
+ out.close();
+
+ }
+
+
+ /**
+ * The Class SavingTrustManager.
+ */
+ private static class SavingTrustManager implements X509TrustManager {
+
+ private final X509TrustManager tm;
+ private X509Certificate[] chain;
+
+ /**
+ * Instantiates a new saving trust manager.
+ *
+ * @param tm the tm
+ */
+ SavingTrustManager(X509TrustManager tm) {
+ this.tm = tm;
+ }
+
+ @Override
+ public X509Certificate[] getAcceptedIssuers() {
+ throw new UnsupportedOperationException();
+ }
+
+ /* (non-Javadoc)
+ * @see javax.net.ssl.X509TrustManager#checkClientTrusted(java.security.cert.X509Certificate[], java.lang.String)
+ */
+ @Override
+ public void checkClientTrusted(X509Certificate[] chain, String authType)
+ throws CertificateException {
+ throw new UnsupportedOperationException();
+ }
+
+ /* (non-Javadoc)
+ * @see javax.net.ssl.X509TrustManager#checkServerTrusted(java.security.cert.X509Certificate[], java.lang.String)
+ */
+ @Override
+ public void checkServerTrusted(X509Certificate[] chain, String authType)
+ throws CertificateException {
+ this.chain = chain;
+ tm.checkServerTrusted(chain, authType);
+ }
+ }
+
+ private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray();
+
+ /**
+ * Gets the san type.
+ *
+ * @param type the type
+ * @return the san type
+ */
+ // TODO: convert to enum(int,string)
+ private String getSanType(int type) {
+ switch (type) {
+ case 0:
+ return "otherName";
+ case 1:
+ return "rfc822Name";
+ case 2:
+ return "dNSName";
+ case 3:
+ return "x400Address";
+ case 4:
+ return "directoryName";
+ case 5:
+ return "ediPartyName";
+ case 6:
+ return "uniformResourceIdentifier";
+ case 7:
+ return "iPAddress";
+ case 8:
+ return "registeredID";
+ default:
+ return "unknownSanType";
+ }
+ }
+
+
+ /**
+ * To hex string.
+ *
+ * @param bytes the bytes
+ * @return the string
+ */
+ private static String toHexString(byte[] bytes) {
+ StringBuilder sb = new StringBuilder(bytes.length * 3);
+ for (int b : bytes) {
+ b &= 0xff;
+ sb.append(HEXDIGITS[b >> 4]);
+ sb.append(HEXDIGITS[b & 15]);
+ sb.append(' ');
+ }
+ return sb.toString();
+ }
+
+
+
+ /**
+ * The main method.
+ *
+ * @param args the arguments
+ * @throws Exception the exception
+ */
+ public static void main(String[] args) throws Exception {
+
+ // String endpointList = "aai-int1.test.att.com:8440;aai-int1.dev.att.com:8442";
+
+ /*
+ * Examples: localhost:8440;localhost:8442 d:\1\adhoc_keystore.jks aaiDomain2 false
+ * localhost:8440;localhost:8442 d:\1\adhoc_keystore.jks aaiDomain2 true
+ */
+
+ if (args.length != 4) {
+ System.out.println(
+ "Usage: KeyBuilder <[ip:port];*> <keystoreFileName>"
+ + " <keystorePassword> <dumpCertDetails> ");
+ System.exit(1);
+ }
+ KeystoreBuilder kb = new KeystoreBuilder(args[0]);
+ kb.setDumpCertDetails(Boolean.parseBoolean(args[3]));
+ kb.updateKeystore(args[1], args[2]);
+
+ }
+}
+
+
diff --git a/src/main/java/org/openecomp/sparky/util/NodeUtils.java b/src/main/java/org/openecomp/sparky/util/NodeUtils.java
new file mode 100644
index 0000000..1789fcf
--- /dev/null
+++ b/src/main/java/org/openecomp/sparky/util/NodeUtils.java
@@ -0,0 +1,714 @@
+/**
+ * ============LICENSE_START===================================================
+ * SPARKY (AAI UI service)
+ * ============================================================================
+ * Copyright © 2017 AT&T Intellectual Property.
+ * Copyright © 2017 Amdocs
+ * All rights reserved.
+ * ============================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file 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.
+ * ============LICENSE_END=====================================================
+ *
+ * ECOMP and OpenECOMP are trademarks
+ * and service marks of AT&T Intellectual Property.
+ */
+
+package org.openecomp.sparky.util;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.lang.Thread.UncaughtExceptionHandler;
+import java.nio.ByteBuffer;
+import java.security.SecureRandom;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Date;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.TimeZone;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.TimeUnit;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.xml.stream.XMLStreamConstants;
+
+import org.openecomp.cl.api.Logger;
+import org.openecomp.sparky.logging.AaiUiMsgs;
+import org.openecomp.sparky.viewandinspect.config.TierSupportUiConstants;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.ObjectWriter;
+import com.fasterxml.jackson.databind.SerializationFeature;
+import com.google.common.util.concurrent.ThreadFactoryBuilder;
+
+
+/**
+ * The Class NodeUtils.
+ */
+public class NodeUtils {
+ private static SecureRandom sRandom = new SecureRandom();
+
+ public static synchronized String getRandomTxnId(){
+ byte bytes[] = new byte[6];
+ sRandom.nextBytes(bytes);
+ return Integer.toUnsignedString(ByteBuffer.wrap(bytes).getInt());
+ }
+
+ /**
+ * Builds the depth padding.
+ *
+ * @param depth the depth
+ * @return the string
+ */
+ public static String buildDepthPadding(int depth) {
+ StringBuilder sb = new StringBuilder(32);
+
+ for (int x = 0; x < depth; x++) {
+ sb.append(" ");
+ }
+
+ return sb.toString();
+ }
+
+ /**
+ * Checks if is numeric.
+ *
+ * @param numberStr the number str
+ * @return true, if is numeric
+ */
+ public static boolean isNumeric(String numberStr) {
+
+ try {
+ Double.parseDouble(numberStr);
+ } catch (Exception exc) {
+ return false;
+ }
+
+ return true;
+
+ }
+
+ /**
+ * Creates the named executor.
+ *
+ * @param name the name
+ * @param numWorkers the num workers
+ * @param logger the logger
+ * @return the executor service
+ */
+ public static ExecutorService createNamedExecutor(String name, int numWorkers, final Logger logger) {
+ UncaughtExceptionHandler uncaughtExceptionHandler = new Thread.UncaughtExceptionHandler() {
+
+ @Override
+ public void uncaughtException(Thread thread, Throwable exc) {
+
+ logger.error(AaiUiMsgs.ERROR_GENERIC, thread.getName() + ": " + exc);
+
+ }
+ };
+
+ ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat(name + "-%d")
+ .setUncaughtExceptionHandler(uncaughtExceptionHandler).build();
+
+ return Executors.newScheduledThreadPool(numWorkers + 1, namedThreadFactory);
+ }
+
+ /**
+ * Calculate edit attribute uri.
+ *
+ * @param link the link
+ * @return the string
+ */
+ public static String calculateEditAttributeUri(String link) {
+ String uri = null;
+
+ if (link != null) {
+
+ Pattern pattern = Pattern.compile(TierSupportUiConstants.URI_VERSION_REGEX_PATTERN);
+ Matcher matcher = pattern.matcher(link);
+ if (matcher.find()) {
+ uri = link.substring(matcher.end());
+ }
+ }
+ return uri;
+ }
+
+ /**
+ * Generate unique sha digest.
+ *
+ * @param keys the keys
+ * @return the string
+ */
+ public static String generateUniqueShaDigest(String... keys) {
+
+ if ((keys == null) || keys.length == 0) {
+ return null;
+ }
+
+ final String keysStr = Arrays.asList(keys).toString();
+ final String hashedId = org.apache.commons.codec.digest.DigestUtils.sha256Hex(keysStr);
+
+ return hashedId;
+ }
+
+ /**
+ * Gets the node field as text.
+ *
+ * @param node the node
+ * @param fieldName the field name
+ * @return the node field as text
+ */
+ public static String getNodeFieldAsText(JsonNode node, String fieldName) {
+
+ String fieldValue = null;
+
+ JsonNode valueNode = node.get(fieldName);
+
+ if (valueNode != null) {
+ fieldValue = valueNode.asText();
+ }
+
+ return fieldValue;
+ }
+
+ private static final String ENTITY_RESOURCE_KEY_FORMAT = "%s.%s";
+
+ /**
+ * Convert a millisecond duration to a string format
+ *
+ * @param millis A duration to convert to a string form
+ * @return A string of the form "X Days Y Hours Z Minutes A Seconds".
+ */
+
+ private static final String TIME_BREAK_DOWN_FORMAT =
+ "[ %d days, %d hours, %d minutes, %d seconds ]";
+
+ /**
+ * Gets the duration breakdown.
+ *
+ * @param millis the millis
+ * @return the duration breakdown
+ */
+ public static String getDurationBreakdown(long millis) {
+
+ if (millis < 0) {
+ return String.format(TIME_BREAK_DOWN_FORMAT, 0, 0, 0, 0);
+ }
+
+ long days = TimeUnit.MILLISECONDS.toDays(millis);
+ millis -= TimeUnit.DAYS.toMillis(days);
+ long hours = TimeUnit.MILLISECONDS.toHours(millis);
+ millis -= TimeUnit.HOURS.toMillis(hours);
+ long minutes = TimeUnit.MILLISECONDS.toMinutes(millis);
+ millis -= TimeUnit.MINUTES.toMillis(minutes);
+ long seconds = TimeUnit.MILLISECONDS.toSeconds(millis);
+
+ return String.format(TIME_BREAK_DOWN_FORMAT, days, hours, minutes, seconds);
+
+ }
+
+ /**
+ * Checks if is equal.
+ *
+ * @param n1 the n 1
+ * @param n2 the n 2
+ * @return true, if is equal
+ */
+ public static boolean isEqual(JsonNode n1, JsonNode n2) {
+
+ /*
+ * due to the inherent nature of json being unordered, comparing object representations of the
+ * same keys and values but different order makes comparison challenging. Let's try an
+ * experiment where we compare the structure of the json, and then simply compare the sorted
+ * order of that structure which should be good enough for what we are trying to accomplish.
+ */
+
+ TreeWalker walker = new TreeWalker();
+ List<String> n1Paths = new ArrayList<String>();
+ List<String> n2Paths = new ArrayList<String>();
+
+ walker.walkTree(n1Paths, n1);
+ walker.walkTree(n2Paths, n2);
+
+ Collections.sort(n1Paths);
+ Collections.sort(n2Paths);
+
+ return n1Paths.equals(n2Paths);
+
+ }
+
+ /**
+ * Concat array.
+ *
+ * @param list the list
+ * @return the string
+ */
+ public static String concatArray(List<String> list) {
+ return concatArray(list, " ");
+ }
+
+ /**
+ * Concat array.
+ *
+ * @param list the list
+ * @param delimiter the delimiter
+ * @return the string
+ */
+ public static String concatArray(List<String> list, String delimiter) {
+
+ if (list == null || list.size() == 0) {
+ return "";
+ }
+
+ StringBuilder result = new StringBuilder(64);
+
+ boolean firstValue = true;
+
+ for (String item : list) {
+
+ if (firstValue) {
+ result.append(item);
+ firstValue = false;
+ } else {
+ result.append(delimiter).append(item);
+ }
+
+ }
+
+ return result.toString();
+
+ }
+
+ /**
+ * Concat array.
+ *
+ * @param values the values
+ * @return the string
+ */
+ public static String concatArray(String[] values) {
+
+ if (values == null || values.length == 0) {
+ return "";
+ }
+
+ StringBuilder result = new StringBuilder(64);
+
+ boolean firstValue = true;
+
+ for (String item : values) {
+
+ if (firstValue) {
+ result.append(item);
+ firstValue = false;
+ } else {
+ result.append(".").append(item);
+ }
+
+ }
+
+ return result.toString();
+
+ }
+
+ /**
+ * Builds the entity resource key.
+ *
+ * @param entityType the entity type
+ * @param resourceId the resource id
+ * @return the string
+ */
+ public static String buildEntityResourceKey(String entityType, String resourceId) {
+ return String.format(ENTITY_RESOURCE_KEY_FORMAT, entityType, resourceId);
+ }
+
+ /**
+ * Extract resource id from link.
+ *
+ * @param link the link
+ * @return the string
+ */
+ public static String extractResourceIdFromLink(String link) {
+
+ if (link == null) {
+ return null;
+ }
+
+ int linkLength = link.length();
+ if (linkLength == 0) {
+ return null;
+ }
+
+ /*
+ * if the last character != / then we need to change the lastIndex position
+ */
+
+ int startIndex = 0;
+ String resourceId = null;
+ if ("/".equals(link.substring(linkLength - 1))) {
+ // Use-case:
+ // https://aai-ext1.test.att.com:9292/aai/v7/business/customers/customer/1607_20160524Func_Ak1_01/service-subscriptions/service-subscription/uCPE-VMS/
+ startIndex = link.lastIndexOf("/", linkLength - 2);
+ resourceId = link.substring(startIndex + 1, linkLength - 1);
+ } else {
+ // Use-case:
+ // https://aai-ext1.test.att.com:9292/aai/v7/business/customers/customer/1607_20160524Func_Ak1_01/service-subscriptions/service-subscription/uCPE-VMS
+ startIndex = link.lastIndexOf("/");
+ resourceId = link.substring(startIndex + 1, linkLength);
+ }
+
+ String result = null;
+
+ if (resourceId != null) {
+ try {
+ result = java.net.URLDecoder.decode(resourceId, "UTF-8");
+ } catch (Exception exc) {
+ /*
+ * if there is a failure decoding the parameter we will just return the original value.
+ */
+ result = resourceId;
+ }
+ }
+
+ return result;
+
+ }
+
+ /**
+ * Gets the xml stream constant as str.
+ *
+ * @param value the value
+ * @return the xml stream constant as str
+ */
+ public static String getXmlStreamConstantAsStr(int value) {
+ switch (value) {
+ case XMLStreamConstants.ATTRIBUTE:
+ return "ATTRIBUTE";
+ case XMLStreamConstants.CDATA:
+ return "CDATA";
+ case XMLStreamConstants.CHARACTERS:
+ return "CHARACTERS";
+ case XMLStreamConstants.COMMENT:
+ return "COMMENT";
+ case XMLStreamConstants.DTD:
+ return "DTD";
+ case XMLStreamConstants.END_DOCUMENT:
+ return "END_DOCUMENT";
+ case XMLStreamConstants.END_ELEMENT:
+ return "END_ELEMENT";
+ case XMLStreamConstants.ENTITY_DECLARATION:
+ return "ENTITY_DECLARATION";
+ case XMLStreamConstants.ENTITY_REFERENCE:
+ return "ENTITY_REFERENCE";
+ case XMLStreamConstants.NAMESPACE:
+ return "NAMESPACE";
+ case XMLStreamConstants.NOTATION_DECLARATION:
+ return "NOTATION_DECLARATION";
+ case XMLStreamConstants.PROCESSING_INSTRUCTION:
+ return "PROCESSING_INSTRUCTION";
+ case XMLStreamConstants.SPACE:
+ return "SPACE";
+ case XMLStreamConstants.START_DOCUMENT:
+ return "START_DOCUMENT";
+ case XMLStreamConstants.START_ELEMENT:
+ return "START_ELEMENT";
+
+ default:
+ return "Unknown(" + value + ")";
+ }
+ }
+
+ /**
+ * Convert object to json.
+ *
+ * @param object the object
+ * @param pretty the pretty
+ * @return the string
+ * @throws JsonProcessingException the json processing exception
+ */
+ public static String convertObjectToJson(Object object, boolean pretty)
+ throws JsonProcessingException {
+ ObjectWriter ow = null;
+
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
+
+ if (pretty) {
+ ow = mapper.writer().withDefaultPrettyPrinter();
+
+ } else {
+ ow = mapper.writer();
+ }
+
+ return ow.writeValueAsString(object);
+ }
+
+ /**
+ * Convert json str to json node.
+ *
+ * @param jsonStr the json str
+ * @return the json node
+ * @throws IOException Signals that an I/O exception has occurred.
+ */
+ public static JsonNode convertJsonStrToJsonNode(String jsonStr) throws IOException {
+ ObjectMapper mapper = new ObjectMapper();
+ if (jsonStr == null || jsonStr.length() == 0) {
+ return null;
+ }
+
+ return mapper.readTree(jsonStr);
+ }
+
+ /**
+ * Convert object to xml.
+ *
+ * @param object the object
+ * @return the string
+ * @throws JsonProcessingException the json processing exception
+ */
+ public static String convertObjectToXml(Object object) throws JsonProcessingException {
+ ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
+ String jsonOutput = ow.writeValueAsString(object);
+
+ if (jsonOutput == null) {
+ return null;
+ }
+
+ return JsonXmlConverter.convertJsontoXml(jsonOutput);
+
+ }
+
+ /**
+ * Extract objects by key.
+ *
+ * @param node the node
+ * @param searchKey the search key
+ * @param foundObjects the found objects
+ */
+ public static void extractObjectsByKey(JsonNode node, String searchKey,
+ Collection<JsonNode> foundObjects) {
+
+ if ( node == null ) {
+ return;
+ }
+
+ if (node.isObject()) {
+ Iterator<Map.Entry<String, JsonNode>> nodeIterator = node.fields();
+
+ while (nodeIterator.hasNext()) {
+ Map.Entry<String, JsonNode> entry = nodeIterator.next();
+ if (!entry.getValue().isValueNode()) {
+ extractObjectsByKey(entry.getValue(), searchKey, foundObjects);
+ }
+
+ String name = entry.getKey();
+ if (name.equalsIgnoreCase(searchKey)) {
+
+ JsonNode entryNode = entry.getValue();
+
+ if (entryNode.isArray()) {
+
+ Iterator<JsonNode> arrayItemsIterator = entryNode.elements();
+ while (arrayItemsIterator.hasNext()) {
+ foundObjects.add(arrayItemsIterator.next());
+ }
+
+ } else {
+ foundObjects.add(entry.getValue());
+ }
+
+
+ }
+ }
+ } else if (node.isArray()) {
+ Iterator<JsonNode> arrayItemsIterator = node.elements();
+ while (arrayItemsIterator.hasNext()) {
+ extractObjectsByKey(arrayItemsIterator.next(), searchKey, foundObjects);
+ }
+
+ }
+
+ }
+
+ /**
+ * Convert array into list.
+ *
+ * @param node the node
+ * @param instances the instances
+ */
+ public static void convertArrayIntoList(JsonNode node, Collection<JsonNode> instances) {
+
+ if (node.isArray()) {
+ Iterator<JsonNode> arrayItemsIterator = node.elements();
+ while (arrayItemsIterator.hasNext()) {
+ instances.add(arrayItemsIterator.next());
+ }
+
+ } else {
+ instances.add(node);
+ }
+
+ }
+
+ /**
+ * Extract field values from object.
+ *
+ * @param node the node
+ * @param attributesToExtract the attributes to extract
+ * @param fieldValues the field values
+ */
+ public static void extractFieldValuesFromObject(JsonNode node,
+ Collection<String> attributesToExtract, Collection<String> fieldValues) {
+
+ if (node == null) {
+ return;
+ }
+
+ if (node.isObject()) {
+
+ JsonNode valueNode = null;
+
+ for (String attrToExtract : attributesToExtract) {
+
+ valueNode = node.get(attrToExtract);
+
+ if (valueNode != null) {
+
+ if (valueNode.isValueNode()) {
+ fieldValues.add(valueNode.asText());
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Extract field value from object.
+ *
+ * @param node the node
+ * @param fieldName the field name
+ * @return the string
+ */
+ public static String extractFieldValueFromObject(JsonNode node, String fieldName) {
+
+ if (node == null) {
+ return null;
+ }
+
+ if (node.isObject()) {
+
+ JsonNode valueNode = node.get(fieldName);
+
+ if (valueNode != null) {
+
+ if (valueNode.isValueNode()) {
+ return valueNode.asText();
+ }
+ }
+
+ }
+ return null;
+
+ }
+
+ /**
+ * Format timestamp.
+ *
+ * @param timestamp the timestamp
+ * @return the string
+ */
+ public static String formatTimestamp(String timestamp) {
+ try {
+ SimpleDateFormat originalFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
+ originalFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
+ Date toDate = originalFormat.parse(timestamp);
+ SimpleDateFormat newFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
+ newFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
+ return newFormat.format(toDate);
+
+ } catch (ParseException pe) {
+ return timestamp;
+ }
+ }
+
+ /**
+ * Gets the HttpRequest payload.
+ *
+ * @param request the request
+ * @return the body
+ * @throws IOException Signals that an I/O exception has occurred.
+ */
+ public static String getBody(HttpServletRequest request) throws IOException {
+
+ String body = null;
+ StringBuilder stringBuilder = new StringBuilder();
+ BufferedReader bufferedReader = null;
+
+ try {
+ InputStream inputStream = request.getInputStream();
+ if (inputStream != null) {
+ bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
+ char[] charBuffer = new char[128];
+ int bytesRead = -1;
+ while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
+ stringBuilder.append(charBuffer, 0, bytesRead);
+ }
+ } else {
+ stringBuilder.append("");
+ }
+ } catch (IOException ex) {
+ throw ex;
+ } finally {
+ if (bufferedReader != null) {
+ try {
+ bufferedReader.close();
+ } catch (IOException ex) {
+ throw ex;
+ }
+ }
+ }
+
+ body = stringBuilder.toString();
+ return body;
+ }
+
+ /**
+ * The main method.
+ *
+ * @param args the arguments
+ * @throws ParseException the parse exception
+ */
+ public static void main(String[] args) throws ParseException {
+ String date = "20170110T112312Z";
+ SimpleDateFormat originalFormat = new SimpleDateFormat("yyyyMMdd'T'hhmmss'Z'");
+ Date toDate = originalFormat.parse(date);
+ SimpleDateFormat newFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss'Z'");
+ System.out.println(newFormat.format(toDate));
+
+ }
+
+
+
+}
diff --git a/src/main/java/org/openecomp/sparky/util/RawByteHelper.java b/src/main/java/org/openecomp/sparky/util/RawByteHelper.java
new file mode 100644
index 0000000..f929acf
--- /dev/null
+++ b/src/main/java/org/openecomp/sparky/util/RawByteHelper.java
@@ -0,0 +1,177 @@
+/**
+ * ============LICENSE_START===================================================
+ * SPARKY (AAI UI service)
+ * ============================================================================
+ * Copyright © 2017 AT&T Intellectual Property.
+ * Copyright © 2017 Amdocs
+ * All rights reserved.
+ * ============================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file 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.
+ * ============LICENSE_END=====================================================
+ *
+ * ECOMP and OpenECOMP are trademarks
+ * and service marks of AT&T Intellectual Property.
+ */
+
+package org.openecomp.sparky.util;
+
+/**
+ * The Class RawByteHelper.
+ */
+public class RawByteHelper {
+ private static final byte[] HEX_CHAR =
+ new byte[] {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
+
+ /**
+ * Dump bytes.
+ *
+ * @param buffer the buffer
+ * @return the string
+ */
+ /*
+ * TODO -> DOCUMENT ME!
+ *
+ * @param buffer DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ public static String dumpBytes(byte[] buffer) {
+ if (buffer == null) {
+ return "";
+ }
+ String newLine = System.getProperty("line.separator");
+ StringBuffer sb = new StringBuffer();
+
+ for (int i = 0; i < buffer.length; i++) {
+ if (i != 0 && i % 16 == 0) {
+ sb.append(newLine);
+ }
+ // sb.append("0x").append((char) (HEX_CHAR[(buffer[i] & 0x00F0) >> 4])).append((char)
+ // (HEX_CHAR[buffer[i] & 0x000F])).append(" ");
+ sb.append((char) (HEX_CHAR[(buffer[i] & 0x00F0) >> 4]))
+ .append((char) (HEX_CHAR[buffer[i] & 0x000F])).append(" ");
+ }
+
+ return sb.toString();
+ }
+
+ // if you're trying to figure out why or's w/ FF's see:
+ /**
+ * Bytes to int.
+ *
+ * @param one the one
+ * @param two the two
+ * @param three the three
+ * @param four the four
+ * @return the int
+ */
+ // http://www.darksleep.com/player/JavaAndUnsignedTypes.html
+ public static int bytesToInt(byte one, byte two, byte three, byte four) {
+ return (((0xFF & one) << 24) | ((0xFF & two) << 16) | ((0xFF & three) << 8) | ((0xFF & four)));
+ }
+
+ /**
+ * Bytes to short.
+ *
+ * @param one the one
+ * @param two the two
+ * @return the short
+ */
+ public static short bytesToShort(byte one, byte two) {
+ return (short) (((0xFF & one) << 8) | (0xFF & two));
+ }
+
+ /**
+ * First byte.
+ *
+ * @param num the num
+ * @return the byte
+ */
+ // short helper functions
+ static byte firstByte(short num) {
+ return (byte) ((num >> 8) & 0xFF);
+ }
+
+ /**
+ * First byte.
+ *
+ * @param num the num
+ * @return the byte
+ */
+ // Int helper functions
+ static byte firstByte(int num) {
+ return (byte) ((num >> 24) & 0xFF);
+ }
+
+ /**
+ * Second byte.
+ *
+ * @param num the num
+ * @return the byte
+ */
+ static byte secondByte(short num) {
+ return (byte) (num & 0xFF);
+ }
+
+ /**
+ * Second byte.
+ *
+ * @param num the num
+ * @return the byte
+ */
+ static byte secondByte(int num) {
+ return (byte) ((num >> 16) & 0xFF);
+ }
+
+ /**
+ * Third byte.
+ *
+ * @param num the num
+ * @return the byte
+ */
+ static byte thirdByte(int num) {
+ return (byte) ((num >> 8) & 0xFF);
+ }
+
+ /**
+ * Fourth byte.
+ *
+ * @param num the num
+ * @return the byte
+ */
+ static byte fourthByte(int num) {
+ return (byte) (num & 0xFF);
+ }
+
+ /**
+ * Int to byte.
+ *
+ * @param value the value
+ * @return the byte
+ */
+ public static byte intToByte(int value) {
+ return fourthByte(value);
+ }
+
+ /**
+ * Int to short.
+ *
+ * @param value the value
+ * @return the short
+ */
+ public static short intToShort(int value) {
+ return (short) ((value & 0xFF00) | (value & 0xFF));
+ }
+
+}
+
diff --git a/src/main/java/org/openecomp/sparky/util/ServletUtils.java b/src/main/java/org/openecomp/sparky/util/ServletUtils.java
new file mode 100644
index 0000000..e56a98a
--- /dev/null
+++ b/src/main/java/org/openecomp/sparky/util/ServletUtils.java
@@ -0,0 +1,164 @@
+/**
+ * ============LICENSE_START===================================================
+ * SPARKY (AAI UI service)
+ * ============================================================================
+ * Copyright © 2017 AT&T Intellectual Property.
+ * Copyright © 2017 Amdocs
+ * All rights reserved.
+ * ============================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file 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.
+ * ============LICENSE_END=====================================================
+ *
+ * ECOMP and OpenECOMP are trademarks
+ * and service marks of AT&T Intellectual Property.
+ */
+
+package org.openecomp.sparky.util;
+
+import java.io.IOException;
+import java.io.PrintWriter;
+
+import javax.servlet.http.HttpServletResponse;
+
+import org.openecomp.cl.api.Logger;
+import org.openecomp.sparky.logging.AaiUiMsgs;
+import org.openecomp.sparky.dal.elasticsearch.SearchAdapter;
+import org.openecomp.sparky.dal.elasticsearch.config.ElasticSearchConfig;
+import org.openecomp.sparky.dal.rest.OperationResult;
+
+/**
+ * The Class ServletUtils.
+ */
+public class ServletUtils {
+
+ /**
+ * Execute get query.
+ *
+ * @param logger the logger
+ * @param search the search
+ * @param response the response
+ * @param requestUrl the request url
+ * @return the operation result
+ * @throws Exception the exception
+ */
+ public static OperationResult executeGetQuery(Logger logger, SearchAdapter search,
+ HttpServletResponse response, String requestUrl) throws Exception {
+
+ OperationResult opResult = search.doGet(requestUrl, "application/json");
+
+ if (opResult.getResultCode() > 300) {
+ setServletResponse(logger, true, opResult.getResultCode(), response, opResult.getResult());
+ } else {
+ response.setStatus(opResult.getResultCode());
+ }
+
+ return opResult;
+
+ }
+
+ /**
+ * Execute post query.
+ *
+ * @param logger the logger
+ * @param search the search
+ * @param response the response
+ * @param requestUrl the request url
+ * @param requestJsonPayload the request json payload
+ * @return the operation result
+ * @throws Exception the exception
+ */
+ public static OperationResult executePostQuery(Logger logger, SearchAdapter search,
+ HttpServletResponse response, String requestUrl, String requestJsonPayload) throws Exception {
+
+ OperationResult opResult = search.doPost(requestUrl, requestJsonPayload, "application/json");
+
+ if (opResult.getResultCode() > 300) {
+ setServletResponse(logger, true, opResult.getResultCode(), response, opResult.getResult());
+
+ } else {
+ response.setStatus(opResult.getResultCode());
+ }
+
+ return opResult;
+ }
+
+ /**
+ * Handle search servlet errors.
+ *
+ * @param logger the logger
+ * @param errorMsg the error msg
+ * @param exc the exc
+ * @param response the response
+ * @throws IOException Signals that an I/O exception has occurred.
+ */
+ public static void handleSearchServletErrors(Logger logger, String errorMsg, Exception exc,
+ HttpServletResponse response) throws IOException {
+ String errorLogMsg = (exc == null ? errorMsg : errorMsg + ". Error:"
+ + exc.getLocalizedMessage());
+ logger.error(AaiUiMsgs.ERROR_GENERIC, errorLogMsg);
+ response.setContentType("application/json");
+ PrintWriter out = response.getWriter();
+ out.println(generateJsonErrorResponse(errorMsg));
+ out.close();
+ }
+
+ /**
+ * Generate json error response.
+ *
+ * @param message the message
+ * @return the string
+ */
+ public static String generateJsonErrorResponse(String message) {
+ return String.format("{ \"errorMessage\" : %s }", message);
+ }
+
+ /**
+ * Sets the servlet response.
+ *
+ * @param logger the logger
+ * @param isError the is error
+ * @param responseCode the response code
+ * @param response the response
+ * @param postPayload the post payload
+ * @throws IOException Signals that an I/O exception has occurred.
+ */
+ public static void setServletResponse(Logger logger, boolean isError, int responseCode,
+ HttpServletResponse response, String postPayload) throws IOException {
+
+ if (isError) {
+ logger.error(AaiUiMsgs.ERROR_GENERIC, postPayload);
+ }
+
+ response.setStatus(responseCode);
+
+ if (postPayload != null) {
+ response.setContentType("application/json");
+ PrintWriter out = response.getWriter();
+ out.println(postPayload);
+ out.close();
+ }
+ }
+
+ /**
+ * Gets the full url.
+ *
+ * @param elasticConfig the elastic config
+ * @param resourceUrl the resource url
+ * @return the full url
+ */
+ public static String getFullUrl(ElasticSearchConfig elasticConfig, String resourceUrl) {
+ final String host = elasticConfig.getIpAddress();
+ final String port = elasticConfig.getHttpPort();
+ return String.format("http://%s:%s%s", host, port, resourceUrl);
+ }
+}
diff --git a/src/main/java/org/openecomp/sparky/util/SuggestionsPermutation.java b/src/main/java/org/openecomp/sparky/util/SuggestionsPermutation.java
new file mode 100644
index 0000000..876b2f4
--- /dev/null
+++ b/src/main/java/org/openecomp/sparky/util/SuggestionsPermutation.java
@@ -0,0 +1,82 @@
+/**
+ * ============LICENSE_START===================================================
+ * SPARKY (AAI UI service)
+ * ============================================================================
+ * Copyright © 2017 AT&T Intellectual Property.
+ * Copyright © 2017 Amdocs
+ * All rights reserved.
+ * ============================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file 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.
+ * ============LICENSE_END=====================================================
+ *
+ * ECOMP and OpenECOMP are trademarks
+ * and service marks of AT&T Intellectual Property.
+ */
+package org.openecomp.sparky.util;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class SuggestionsPermutation {
+
+ /*
+ * Will return all the unique combinations of the suggestions provided.
+ * The order of the permutation is not taken into account when computing
+ * the uniqueness.
+ * eg: A list of A,B,C,D will return
+ * [[A], [A, B, C, D], [A, C, D], [A, D], [B], [B, C, D], [B, D], [C], [C, D], [D]]
+ *
+ * @param list The list to create the unique permutations
+ * @return A Arraylist which contains a array list of all possible combinations
+ */
+ @SuppressWarnings("serial")
+ public ArrayList<ArrayList<String>> getSuggestionsPermutation(List<String> list) {
+ List<String> statusList = new ArrayList<>(list);
+ List<String> dupStatusList;
+ ArrayList<ArrayList<String>> uniqueList = new ArrayList<ArrayList<String>>();
+ int mainLoopIndexCounter = 0;
+ for (String status : statusList) {
+ // Add the single entity subset
+ uniqueList.add(new ArrayList<String>() {
+ {
+ add(status);
+ }
+ });
+ // Remove all the elements to left till the current index
+ dupStatusList = truncateListUntill(statusList, mainLoopIndexCounter);
+
+ while (dupStatusList.size() > 0) {
+ ArrayList<String> suggListInIterate= new ArrayList<>();
+ suggListInIterate.add(status);
+ for (String dupStatus : dupStatusList) {
+ suggListInIterate.add(dupStatus);
+ }
+ uniqueList.add(suggListInIterate);
+ dupStatusList.remove(0);
+ }
+ mainLoopIndexCounter++;
+ }
+ return uniqueList;
+
+ }
+
+ private List<String> truncateListUntill(List<String> lists, int index) {
+ List<String> truncatedList = new ArrayList<>(lists);
+ int counter = 0;
+ while (counter <= index) {
+ truncatedList.remove(0);
+ counter++;
+ }
+ return truncatedList;
+ }
+}
diff --git a/src/main/java/org/openecomp/sparky/util/TreeWalker.java b/src/main/java/org/openecomp/sparky/util/TreeWalker.java
new file mode 100644
index 0000000..c9a804d
--- /dev/null
+++ b/src/main/java/org/openecomp/sparky/util/TreeWalker.java
@@ -0,0 +1,137 @@
+/**
+ * ============LICENSE_START===================================================
+ * SPARKY (AAI UI service)
+ * ============================================================================
+ * Copyright © 2017 AT&T Intellectual Property.
+ * Copyright © 2017 Amdocs
+ * All rights reserved.
+ * ============================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file 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.
+ * ============LICENSE_END=====================================================
+ *
+ * ECOMP and OpenECOMP are trademarks
+ * and service marks of AT&T Intellectual Property.
+ */
+
+package org.openecomp.sparky.util;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.collect.Lists;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * The Class TreeWalker.
+ */
+public class TreeWalker {
+
+ /**
+ * Convert json to node.
+ *
+ * @param json the json
+ * @return the json node
+ * @throws JsonProcessingException the json processing exception
+ * @throws IOException Signals that an I/O exception has occurred.
+ */
+ public JsonNode convertJsonToNode(String json) throws JsonProcessingException, IOException {
+ ObjectMapper mapper = new ObjectMapper();
+
+ if (json == null) {
+ return null;
+ }
+
+ return mapper.readTree(json);
+
+ }
+
+ /**
+ * Walk tree.
+ *
+ * @param paths the paths
+ * @param root the root
+ */
+ public void walkTree(List<String> paths, JsonNode root) {
+ walker(paths, null, root);
+ }
+
+ /**
+ * Walker.
+ *
+ * @param paths the paths
+ * @param nodename the nodename
+ * @param node the node
+ */
+ private void walker(List<String> paths, String nodename, JsonNode node) {
+
+ if (node == null) {
+ return;
+ }
+
+ /*
+ * if ( nodename != null ) { paths.add(nodename); }
+ */
+
+ // System.out.println("path: " + nameToPrint);
+ if (node.isObject()) {
+ Iterator<Map.Entry<String, JsonNode>> iterator = node.fields();
+
+ ArrayList<Map.Entry<String, JsonNode>> nodesList = Lists.newArrayList(iterator);
+ // System.out.println("Walk Tree - root:" + node + ", elements
+ // keys:" + nodesList);
+
+ if (nodesList.isEmpty()) {
+
+ if (nodename != null) {
+ paths.add(nodename);
+ }
+
+ } else {
+
+ for (Map.Entry<String, JsonNode> nodEntry : nodesList) {
+ String name = nodEntry.getKey();
+ JsonNode newNode = nodEntry.getValue();
+
+ if (newNode.isValueNode()) {
+ if (nodename == null) {
+ paths.add(name + "=" + newNode.asText());
+ } else {
+ paths.add(nodename + "." + name + "=" + newNode.asText());
+ }
+ } else {
+
+ if (nodename == null) {
+ walker(paths, name, newNode);
+ } else {
+ walker(paths, nodename + "." + name, newNode);
+ }
+ }
+
+ }
+ }
+ } else if (node.isArray()) {
+ Iterator<JsonNode> arrayItemsIterator = node.elements();
+ ArrayList<JsonNode> arrayItemsList = Lists.newArrayList(arrayItemsIterator);
+ for (JsonNode arrayNode : arrayItemsList) {
+ walker(paths, nodename, arrayNode);
+ }
+ } else if (node.isValueNode()) {
+ paths.add(nodename + "=" + node.asText());
+ }
+ }
+}