changed the header license to new license
[aai/sparky-be.git] / src / main / java / org / onap / aai / sparky / util / NodeUtils.java
index a34c07d..dbb9877 100644 (file)
@@ -2,8 +2,8 @@
  * ============LICENSE_START=======================================================
  * org.onap.aai
  * ================================================================================
- * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
- * Copyright © 2017 Amdocs
+ * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright © 2017-2018 Amdocs
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -17,8 +17,6 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  * ============LICENSE_END=========================================================
- *
- * ECOMP is a trademark and service mark of AT&T Intellectual Property.
  */
 package org.onap.aai.sparky.util;
 
@@ -54,7 +52,7 @@ 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.TierSupportUiConstants;
+import org.onap.aai.sparky.viewandinspect.config.SparkyConstants;
 import org.restlet.Request;
 
 import com.fasterxml.jackson.core.JsonProcessingException;
@@ -71,14 +69,16 @@ import com.google.common.util.concurrent.ThreadFactoryBuilder;
  */
 public class NodeUtils {
   private static SecureRandom sRandom = new SecureRandom();
-
+  
   private static final Pattern AAI_VERSION_PREFIX = Pattern.compile("/aai/v[0-9]+/(.*)");
-
-
-  public static synchronized String getRandomTxnId() {
-    byte bytes[] = new byte[6];
-    sRandom.nextBytes(bytes);
-    return Integer.toUnsignedString(ByteBuffer.wrap(bytes).getInt());
+  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());
   }
 
   /**
@@ -96,31 +96,76 @@ public class NodeUtils {
 
     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()) {
 
-        // System.out.println(m.group(0));
-        if (m.groupCount() >= 1) {
+        if ( m.groupCount() >= 1) {
           return m.group(1);
         }
-        // System.out.println(m.group(2));
+          
+      }
+    } 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.
@@ -148,8 +193,7 @@ public class NodeUtils {
    * @param logger the logger
    * @return the executor service
    */
-  public static ExecutorService createNamedExecutor(String name, int numWorkers,
-      final Logger logger) {
+  public static ExecutorService createNamedExecutor(String name, int numWorkers, final Logger logger) {
     UncaughtExceptionHandler uncaughtExceptionHandler = new Thread.UncaughtExceptionHandler() {
 
       @Override
@@ -166,18 +210,13 @@ public class NodeUtils {
     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);
+      Pattern pattern = Pattern.compile(SparkyConstants.URI_VERSION_REGEX_PATTERN);
       Matcher matcher = pattern.matcher(link);
       if (matcher.find()) {
         uri = link.substring(matcher.end());
@@ -186,6 +225,7 @@ public class NodeUtils {
     return uri;
   }
 
+  
   /**
    * Generate unique sha digest.
    *
@@ -299,15 +339,15 @@ public class NodeUtils {
   public static String concatArray(List<String> list) {
     return concatArray(list, " ");
   }
-
 private static final String TIMESTAMP_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
-
+  
+ 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.
    *
@@ -407,12 +447,12 @@ public class NodeUtils {
     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/
+      // 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://aai-ext1.test.att.com:9292/aai/v7/business/customers/customer/1607_20160524Func_Ak1_01/service-subscriptions/service-subscription/uCPE-VMS
+      // 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);
     }
@@ -492,7 +532,7 @@ public class NodeUtils {
 
     ObjectMapper mapper = new ObjectMapper();
     mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
-
+    
     if (pretty) {
       ow = mapper.writer().withDefaultPrettyPrinter();
 
@@ -502,9 +542,10 @@ public class NodeUtils {
 
     return ow.writeValueAsString(object);
   }
-
+  
   /**
-   * Convert object to json by selectively choosing certain fields thru filters. Example use case:
+   * 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
@@ -518,7 +559,7 @@ public class NodeUtils {
 
     ObjectMapper mapper = new ObjectMapper();
     mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
-
+    
     if (pretty) {
       ow = mapper.writer(filters).withDefaultPrettyPrinter();
 
@@ -528,7 +569,7 @@ public class NodeUtils {
 
     return ow.writeValueAsString(object);
   }
-
+  
 
   /**
    * Convert json str to json node.
@@ -575,10 +616,10 @@ public class NodeUtils {
   public static void extractObjectsByKey(JsonNode node, String searchKey,
       Collection<JsonNode> foundObjects) {
 
-    if (node == null) {
+    if ( node == null ) {
       return;
     }
-
+    
     if (node.isObject()) {
       Iterator<Map.Entry<String, JsonNode>> nodeIterator = node.fields();
 
@@ -614,6 +655,51 @@ public class NodeUtils {
       }
 
     }
+  }
+    
+  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;
 
   }
 
@@ -717,7 +803,7 @@ public class NodeUtils {
       return timestamp;
     }
   }
-
   /**
    * Gets the HttpRequest payload.
    *
@@ -729,8 +815,8 @@ public class NodeUtils {
     InputStream inputStream = request.getInputStream();
     return getBodyFromStream(inputStream);
   }
-
-
+  
+  
 
   /**
    * Gets the Restlet Request payload.
@@ -743,7 +829,7 @@ public class NodeUtils {
     InputStream inputStream = request.getEntity().getStream();
     return getBodyFromStream(inputStream);
   }
-
+  
 
   /**
    * Gets the payload from the input stream of a request.
@@ -785,7 +871,7 @@ public class NodeUtils {
     return body;
   }
 
-
+  
   /**
    * The main method.
    *