summaryrefslogtreecommitdiffstats
path: root/sparkybe-onap-service/src/main/java/org/onap/aai/sparky/util
diff options
context:
space:
mode:
Diffstat (limited to 'sparkybe-onap-service/src/main/java/org/onap/aai/sparky/util')
-rw-r--r--sparkybe-onap-service/src/main/java/org/onap/aai/sparky/util/ConfigHelper.java193
-rw-r--r--sparkybe-onap-service/src/main/java/org/onap/aai/sparky/util/EncryptConvertor.java149
-rw-r--r--sparkybe-onap-service/src/main/java/org/onap/aai/sparky/util/Encryptor.java155
-rw-r--r--sparkybe-onap-service/src/main/java/org/onap/aai/sparky/util/ErrorUtil.java61
-rw-r--r--sparkybe-onap-service/src/main/java/org/onap/aai/sparky/util/JsonXmlConverter.java79
-rw-r--r--sparkybe-onap-service/src/main/java/org/onap/aai/sparky/util/NodeUtils.java896
-rw-r--r--sparkybe-onap-service/src/main/java/org/onap/aai/sparky/util/RawByteHelper.java176
-rw-r--r--sparkybe-onap-service/src/main/java/org/onap/aai/sparky/util/RestletUtils.java119
-rw-r--r--sparkybe-onap-service/src/main/java/org/onap/aai/sparky/util/SuggestionsPermutation.java100
-rw-r--r--sparkybe-onap-service/src/main/java/org/onap/aai/sparky/util/TreeWalker.java136
10 files changed, 2064 insertions, 0 deletions
diff --git a/sparkybe-onap-service/src/main/java/org/onap/aai/sparky/util/ConfigHelper.java b/sparkybe-onap-service/src/main/java/org/onap/aai/sparky/util/ConfigHelper.java
new file mode 100644
index 0000000..cb6cc53
--- /dev/null
+++ b/sparkybe-onap-service/src/main/java/org/onap/aai/sparky/util/ConfigHelper.java
@@ -0,0 +1,193 @@
+/**
+ * ============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.onap.aai.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.onap.aai.cl.api.Logger;
+import org.onap.aai.cl.eelf.LoggerFactory;
+import org.onap.aai.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/sparkybe-onap-service/src/main/java/org/onap/aai/sparky/util/EncryptConvertor.java b/sparkybe-onap-service/src/main/java/org/onap/aai/sparky/util/EncryptConvertor.java
new file mode 100644
index 0000000..623ce38
--- /dev/null
+++ b/sparkybe-onap-service/src/main/java/org/onap/aai/sparky/util/EncryptConvertor.java
@@ -0,0 +1,149 @@
+/**
+ * ============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.onap.aai.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/sparkybe-onap-service/src/main/java/org/onap/aai/sparky/util/Encryptor.java b/sparkybe-onap-service/src/main/java/org/onap/aai/sparky/util/Encryptor.java
new file mode 100644
index 0000000..948df51
--- /dev/null
+++ b/sparkybe-onap-service/src/main/java/org/onap/aai/sparky/util/Encryptor.java
@@ -0,0 +1,155 @@
+/**
+ * ============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.onap.aai.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;
+import org.onap.aai.cl.api.Logger;
+import org.onap.aai.cl.eelf.LoggerFactory;
+import org.onap.aai.sparky.logging.AaiUiMsgs;
+
+/**
+ * The Class Encryptor.
+ */
+public class Encryptor {
+
+ private static final Logger LOG = LoggerFactory.getInstance().getLogger(Encryptor.class);
+ /**
+ * Instantiates a new encryptor.
+ */
+ public Encryptor() {
+ }
+
+ /**
+ * Encrypt value.
+ *
+ * @param value to encrypt
+ * @return the encrypted string
+ */
+ public String encryptValue(String value) {
+ String encyptedValue = "";
+ try {
+ encyptedValue = Password.obfuscate(value);
+ } catch (Exception exc) {
+ LOG.error(AaiUiMsgs.ENCRYPTION_ERROR, value, exc.toString());
+ }
+ return encyptedValue;
+ }
+
+ /**
+ * Decrypt value.
+ *
+ * @param value the value
+ * @return the string
+ */
+ public String decryptValue(String value) {
+ String decyptedValue = "";
+ try {
+ decyptedValue = Password.deobfuscate(value);
+ } catch (Exception exc) {
+ LOG.error(AaiUiMsgs.DECRYPTION_ERROR, 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/sparkybe-onap-service/src/main/java/org/onap/aai/sparky/util/ErrorUtil.java b/sparkybe-onap-service/src/main/java/org/onap/aai/sparky/util/ErrorUtil.java
new file mode 100644
index 0000000..d2bea64
--- /dev/null
+++ b/sparkybe-onap-service/src/main/java/org/onap/aai/sparky/util/ErrorUtil.java
@@ -0,0 +1,61 @@
+/**
+ * ============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.onap.aai.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/sparkybe-onap-service/src/main/java/org/onap/aai/sparky/util/JsonXmlConverter.java b/sparkybe-onap-service/src/main/java/org/onap/aai/sparky/util/JsonXmlConverter.java
new file mode 100644
index 0000000..af2e8ca
--- /dev/null
+++ b/sparkybe-onap-service/src/main/java/org/onap/aai/sparky/util/JsonXmlConverter.java
@@ -0,0 +1,79 @@
+/**
+ * ============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.onap.aai.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/sparkybe-onap-service/src/main/java/org/onap/aai/sparky/util/NodeUtils.java b/sparkybe-onap-service/src/main/java/org/onap/aai/sparky/util/NodeUtils.java
new file mode 100644
index 0000000..68645e2
--- /dev/null
+++ b/sparkybe-onap-service/src/main/java/org/onap/aai/sparky/util/NodeUtils.java
@@ -0,0 +1,896 @@
+/**
+ * ============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.onap.aai.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.net.URI;
+import java.nio.ByteBuffer;
+import java.security.SecureRandom;
+import java.sql.Timestamp;
+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.onap.aai.cl.api.Logger;
+import org.onap.aai.sparky.logging.AaiUiMsgs;
+import org.onap.aai.sparky.viewandinspect.config.SparkyConstants;
+import org.restlet.Request;
+
+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.fasterxml.jackson.databind.ser.FilterProvider;
+import com.google.common.util.concurrent.ThreadFactoryBuilder;
+
+
+/**
+ * The Class NodeUtils.
+ */
+public class NodeUtils {
+ private static SecureRandom sRandom = new SecureRandom();
+
+ private static final Pattern AAI_VERSION_PREFIX = Pattern.compile("/aai/v[0-9]+/(.*)");
+ private static final Pattern GIZMO_VERSION_PREFIX = Pattern.compile("[/]*services/inventory/v[0-9]+/(.*)");
+ private static final Pattern GIZMO_RELATIONSHIP_VERSION_PREFIX = Pattern.compile("services/inventory/relationships/v[0-9]+/(.*)");
+
+
+ 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();
+ }
+
+
+ public static String extractRawPathWithoutVersion(String selfLinkUri) {
+
+ try {
+
+ String rawPath = new URI(selfLinkUri).getRawPath();
+
+ Matcher m = AAI_VERSION_PREFIX.matcher(rawPath);
+
+ if (m.matches()) {
+
+ if ( m.groupCount() >= 1) {
+ return m.group(1);
+ }
+
+ }
+ } catch (Exception e) {
+ }
+
+ return null;
+
+ }
+
+ public static String extractRawGizmoPathWithoutVersion(String resourceLink) {
+
+ try {
+
+ String rawPath = new URI(resourceLink).getRawPath();
+
+ Matcher m = GIZMO_VERSION_PREFIX.matcher(rawPath);
+
+ if (m.matches()) {
+
+ if ( m.groupCount() >= 1) {
+ return m.group(1);
+ }
+
+ }
+ } catch (Exception e) {
+ }
+
+ return null;
+
+ }
+
+ public static String extractRawGizmoRelationshipPathWithoutVersion(String resourceLink) {
+
+ try {
+
+ String rawPath = new URI(resourceLink).getRawPath();
+
+ Matcher m = GIZMO_RELATIONSHIP_VERSION_PREFIX.matcher(rawPath);
+
+ if (m.matches()) {
+
+ if ( m.groupCount() >= 1) {
+ return m.group(1);
+ }
+
+ }
+ } catch (Exception e) {
+ }
+
+ return null;
+
+ }
+
+
+
+
+ /**
+ * 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);
+ }
+
+
+ public static String calculateEditAttributeUri(String link) {
+ String uri = null;
+
+ if (link != null) {
+
+ Pattern pattern = Pattern.compile(SparkyConstants.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, " ");
+ }
+
+ private static final String TIMESTAMP_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
+
+ public static String getCurrentTimeStamp() {
+ SimpleDateFormat dateFormat = new SimpleDateFormat(TIMESTAMP_FORMAT);
+ Timestamp timestamp = new Timestamp(System.currentTimeMillis());
+ return dateFormat.format(timestamp);
+ }
+
+ /**
+ * 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://ext1.test.onap.com:9292/aai/v7/business/customers/customer/customer-1/service-subscriptions/service-subscription/service-subscription-1/
+ startIndex = link.lastIndexOf("/", linkLength - 2);
+ resourceId = link.substring(startIndex + 1, linkLength - 1);
+ } else {
+ // Use-case:
+ // https://ext1.test.onap.com:9292/aai/v7/business/customers/customer/customer-1/service-subscriptions/service-subscription/service-subscription-1
+ 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 object to json by selectively choosing certain fields thru filters.
+ * Example use case:
+ * based on request type we might need to send different serialization of the UiViewFilterEntity
+ *
+ * @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, FilterProvider filters)
+ throws JsonProcessingException {
+ ObjectWriter ow = null;
+
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
+
+ if (pretty) {
+ ow = mapper.writer(filters).withDefaultPrettyPrinter();
+
+ } else {
+ ow = mapper.writer(filters);
+ }
+
+ 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);
+ }
+
+ }
+ }
+
+ public static String extractObjectValueByKey(JsonNode node, String searchKey) {
+
+ if (node == null) {
+ return null;
+ }
+
+ 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()) {
+ return extractObjectValueByKey(entry.getValue(), searchKey);
+ }
+
+ String name = entry.getKey();
+ if (name.equalsIgnoreCase(searchKey)) {
+
+ JsonNode entryNode = entry.getValue();
+
+ if (entryNode.isArray()) {
+
+ Iterator<JsonNode> arrayItemsIterator = entryNode.elements();
+ while (arrayItemsIterator.hasNext()) {
+ return arrayItemsIterator.next().asText();
+ }
+
+ } else {
+ return entry.getValue().asText();
+ }
+
+
+ }
+ }
+ } else if (node.isArray()) {
+ Iterator<JsonNode> arrayItemsIterator = node.elements();
+ while (arrayItemsIterator.hasNext()) {
+ return extractObjectValueByKey(arrayItemsIterator.next(), searchKey);
+ }
+
+ }
+
+ return null;
+
+ }
+
+ /**
+ * 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 {
+ InputStream inputStream = request.getInputStream();
+ return getBodyFromStream(inputStream);
+ }
+
+
+
+ /**
+ * Gets the Restlet Request payload.
+ *
+ * @param request the request
+ * @return the body
+ * @throws IOException Signals that an I/O exception has occurred.
+ */
+ public static String getBody(Request request) throws IOException {
+ InputStream inputStream = request.getEntity().getStream();
+ return getBodyFromStream(inputStream);
+ }
+
+
+ /**
+ * Gets the payload from the input stream of a request.
+ *
+ * @param request the request
+ * @return the body
+ * @throws IOException Signals that an I/O exception has occurred.
+ */
+ public static String getBodyFromStream(InputStream inputStream) throws IOException {
+
+ String body = null;
+ StringBuilder stringBuilder = new StringBuilder();
+ BufferedReader bufferedReader = null;
+
+ try {
+ 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/sparkybe-onap-service/src/main/java/org/onap/aai/sparky/util/RawByteHelper.java b/sparkybe-onap-service/src/main/java/org/onap/aai/sparky/util/RawByteHelper.java
new file mode 100644
index 0000000..99166ca
--- /dev/null
+++ b/sparkybe-onap-service/src/main/java/org/onap/aai/sparky/util/RawByteHelper.java
@@ -0,0 +1,176 @@
+/**
+ * ============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.onap.aai.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/sparkybe-onap-service/src/main/java/org/onap/aai/sparky/util/RestletUtils.java b/sparkybe-onap-service/src/main/java/org/onap/aai/sparky/util/RestletUtils.java
new file mode 100644
index 0000000..26dbf62
--- /dev/null
+++ b/sparkybe-onap-service/src/main/java/org/onap/aai/sparky/util/RestletUtils.java
@@ -0,0 +1,119 @@
+/**
+ * ============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.onap.aai.sparky.util;
+
+import javax.servlet.http.HttpServletResponse;
+
+import org.onap.aai.cl.api.Logger;
+import org.onap.aai.restclient.client.OperationResult;
+import org.onap.aai.sparky.logging.AaiUiMsgs;
+import org.onap.aai.sparky.search.SearchServiceAdapter;
+import org.restlet.Response;
+import org.restlet.data.MediaType;
+import org.restlet.data.Status;
+
+public class RestletUtils {
+ /**
+ * Returns an HttpServletResponse based on values from a Restlet Response
+ *
+ * @param restletResponse Restlet Response to be converted to an HttpServletResponse
+ * @return An HttpServletResponse object built from the values of a Restlet Response
+ */
+ public HttpServletResponse convertRestletResponseToHttpServletResponse(Response restletResponse) {
+ return org.restlet.ext.servlet.ServletUtils.getResponse(restletResponse);
+ }
+
+ /**
+ * Execute post query
+ *
+ * @param logger The logger
+ * @param search The searchAdapter
+ * @param response The response
+ * @param requestUrl The request URL
+ * @param requestJsonPayload The request JSON payload
+ * @return The operation result
+ */
+ public OperationResult executePostQuery(Logger logger, SearchServiceAdapter search,
+ Response response, String requestUrl, String requestJsonPayload) {
+
+ OperationResult opResult = search.doPost(requestUrl, requestJsonPayload, "application/json");
+
+ if (opResult.getResultCode() > 300) {
+ setRestletResponse(logger, true, opResult.getResultCode(), response, opResult.getResult());
+ } else {
+ response.setStatus(new Status(opResult.getResultCode()));
+ }
+
+ return opResult;
+ }
+
+ /**
+ * Generate JSON error response
+ *
+ * @param message The error message
+ * @return The error message formatted as a JSON string
+ */
+ public String generateJsonErrorResponse(String message) {
+ return String.format("{ \"errorMessage\" : \"%s\" }", message);
+ }
+
+ /**
+ * Log Restlet exceptions/errors & prepare Response object with exception/errors info
+ *
+ * @param logger The logger
+ * @param errorMsg The error message
+ * @param exc The exception
+ * @param response The response
+ */
+ public void handleRestletErrors(Logger logger, String errorMsg, Exception exc,
+ Response response) {
+ String errorLogMsg = (exc == null ? errorMsg : errorMsg + ". Error:" + exc.getLocalizedMessage());
+ logger.error(AaiUiMsgs.ERROR_GENERIC, errorLogMsg);
+ response.setEntity(generateJsonErrorResponse(errorMsg), MediaType.APPLICATION_JSON);
+ }
+
+ /**
+ * Sets the Restlet response
+ *
+ * @param logger The logger
+ * @param isError The error
+ * @param responseCode The response code
+ * @param response The response
+ * @param postPayload The post payload
+ */
+ public void setRestletResponse(Logger logger, boolean isError, int responseCode,
+ Response response, String postPayload) {
+
+ if (isError) {
+ logger.error(AaiUiMsgs.ERROR_GENERIC, postPayload);
+ }
+
+ response.setStatus(new Status(responseCode));
+
+ if (postPayload != null) {
+ response.setEntity(postPayload, MediaType.APPLICATION_JSON);
+ }
+ }
+}
diff --git a/sparkybe-onap-service/src/main/java/org/onap/aai/sparky/util/SuggestionsPermutation.java b/sparkybe-onap-service/src/main/java/org/onap/aai/sparky/util/SuggestionsPermutation.java
new file mode 100644
index 0000000..05f6996
--- /dev/null
+++ b/sparkybe-onap-service/src/main/java/org/onap/aai/sparky/util/SuggestionsPermutation.java
@@ -0,0 +1,100 @@
+/**
+ * ============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.onap.aai.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
+ */
+ public static ArrayList<ArrayList<String>> getUniqueListForSuggestions(
+ List<String> originalList) {
+ ArrayList<ArrayList<String>> lists = new ArrayList<ArrayList<String>>();
+ if (originalList.isEmpty()) {
+ lists.add(new ArrayList<String>());
+ return lists;
+ }
+ List<String> list = new ArrayList<String>(originalList);
+ String head = list.get(0);
+ ArrayList<String> rest = new ArrayList<String>(list.subList(1, list.size()));
+
+ for (ArrayList<String> activeList : getUniqueListForSuggestions(rest)) {
+ ArrayList<String> newList = new ArrayList<String>();
+ newList.add(head);
+ newList.addAll(activeList);
+ lists.add(newList);
+ lists.add(activeList);
+ }
+ return lists;
+ }
+
+ public static ArrayList<ArrayList<String>> getNonEmptyUniqueLists(List<String> list){
+ ArrayList<ArrayList<String>> lists = getUniqueListForSuggestions(list);
+ // remove empty list from the power set
+ for (ArrayList<String> emptyList : lists ){
+ if ( emptyList.isEmpty() ) {
+ lists.remove(emptyList);
+ break;
+ }
+ }
+ return lists;
+ }
+
+ public static List<List<String>> getListPermutations(List<String> list) {
+ List<String> inputList = new ArrayList<String>();
+ inputList.addAll(list);
+ if (inputList.size() == 0) {
+ List<List<String>> result = new ArrayList<List<String>>();
+ result.add(new ArrayList<String>());
+ return result;
+ }
+
+ List<List<String>> listOfLists = new ArrayList<List<String>>();
+
+ String firstElement = inputList.remove(0);
+
+ List<List<String>> recursiveReturn = getListPermutations(inputList);
+ for (List<String> li : recursiveReturn) {
+
+ for (int index = 0; index <= li.size(); index++) {
+ List<String> temp = new ArrayList<String>(li);
+ temp.add(index, firstElement);
+ listOfLists.add(temp);
+ }
+
+ }
+ return listOfLists;
+ }
+
+}
diff --git a/sparkybe-onap-service/src/main/java/org/onap/aai/sparky/util/TreeWalker.java b/sparkybe-onap-service/src/main/java/org/onap/aai/sparky/util/TreeWalker.java
new file mode 100644
index 0000000..d8bb7b9
--- /dev/null
+++ b/sparkybe-onap-service/src/main/java/org/onap/aai/sparky/util/TreeWalker.java
@@ -0,0 +1,136 @@
+/**
+ * ============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.onap.aai.sparky.util;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.collect.Lists;
+
+/**
+ * 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());
+ }
+ }
+}