2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6 * Copyright © 2017 Amdocs
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END=========================================================
21 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
23 package org.onap.aai.sparky.util;
25 import java.io.BufferedReader;
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.io.InputStreamReader;
29 import java.lang.Thread.UncaughtExceptionHandler;
31 import java.nio.ByteBuffer;
32 import java.security.SecureRandom;
33 import java.sql.Timestamp;
34 import java.text.ParseException;
35 import java.text.SimpleDateFormat;
36 import java.util.ArrayList;
37 import java.util.Arrays;
38 import java.util.Collection;
39 import java.util.Collections;
40 import java.util.Date;
41 import java.util.Iterator;
42 import java.util.List;
44 import java.util.TimeZone;
45 import java.util.concurrent.ExecutorService;
46 import java.util.concurrent.Executors;
47 import java.util.concurrent.ThreadFactory;
48 import java.util.concurrent.TimeUnit;
49 import java.util.regex.Matcher;
50 import java.util.regex.Pattern;
52 import javax.servlet.http.HttpServletRequest;
53 import javax.xml.stream.XMLStreamConstants;
55 import org.onap.aai.cl.api.Logger;
56 import org.onap.aai.sparky.logging.AaiUiMsgs;
57 import org.onap.aai.sparky.viewandinspect.config.SparkyConstants;
58 import org.restlet.Request;
60 import com.fasterxml.jackson.core.JsonProcessingException;
61 import com.fasterxml.jackson.databind.JsonNode;
62 import com.fasterxml.jackson.databind.ObjectMapper;
63 import com.fasterxml.jackson.databind.ObjectWriter;
64 import com.fasterxml.jackson.databind.SerializationFeature;
65 import com.fasterxml.jackson.databind.ser.FilterProvider;
66 import com.google.common.util.concurrent.ThreadFactoryBuilder;
70 * The Class NodeUtils.
72 public class NodeUtils {
73 private static SecureRandom sRandom = new SecureRandom();
75 private static final Pattern AAI_VERSION_PREFIX = Pattern.compile("/aai/v[0-9]+/(.*)");
76 private static final Pattern GIZMO_VERSION_PREFIX = Pattern.compile("[/]*services/inventory/v[0-9]+/(.*)");
77 private static final Pattern GIZMO_RELATIONSHIP_VERSION_PREFIX = Pattern.compile("services/inventory/relationships/v[0-9]+/(.*)");
80 public static synchronized String getRandomTxnId(){
81 byte bytes[] = new byte[6];
82 sRandom.nextBytes(bytes);
83 return Integer.toUnsignedString(ByteBuffer.wrap(bytes).getInt());
87 * Builds the depth padding.
89 * @param depth the depth
92 public static String buildDepthPadding(int depth) {
93 StringBuilder sb = new StringBuilder(32);
95 for (int x = 0; x < depth; x++) {
103 public static String extractRawPathWithoutVersion(String selfLinkUri) {
107 String rawPath = new URI(selfLinkUri).getRawPath();
109 Matcher m = AAI_VERSION_PREFIX.matcher(rawPath);
113 if ( m.groupCount() >= 1) {
118 } catch (Exception e) {
125 public static String extractRawGizmoPathWithoutVersion(String resourceLink) {
129 String rawPath = new URI(resourceLink).getRawPath();
131 Matcher m = GIZMO_VERSION_PREFIX.matcher(rawPath);
135 if ( m.groupCount() >= 1) {
140 } catch (Exception e) {
147 public static String extractRawGizmoRelationshipPathWithoutVersion(String resourceLink) {
151 String rawPath = new URI(resourceLink).getRawPath();
153 Matcher m = GIZMO_RELATIONSHIP_VERSION_PREFIX.matcher(rawPath);
157 if ( m.groupCount() >= 1) {
162 } catch (Exception e) {
173 * Checks if is numeric.
175 * @param numberStr the number str
176 * @return true, if is numeric
178 public static boolean isNumeric(String numberStr) {
181 Double.parseDouble(numberStr);
182 } catch (Exception exc) {
191 * Creates the named executor.
193 * @param name the name
194 * @param numWorkers the num workers
195 * @param logger the logger
196 * @return the executor service
198 public static ExecutorService createNamedExecutor(String name, int numWorkers, final Logger logger) {
199 UncaughtExceptionHandler uncaughtExceptionHandler = new Thread.UncaughtExceptionHandler() {
202 public void uncaughtException(Thread thread, Throwable exc) {
204 logger.error(AaiUiMsgs.ERROR_GENERIC, thread.getName() + ": " + exc);
209 ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat(name + "-%d")
210 .setUncaughtExceptionHandler(uncaughtExceptionHandler).build();
212 return Executors.newScheduledThreadPool(numWorkers + 1, namedThreadFactory);
216 public static String calculateEditAttributeUri(String link) {
221 Pattern pattern = Pattern.compile(SparkyConstants.URI_VERSION_REGEX_PATTERN);
222 Matcher matcher = pattern.matcher(link);
223 if (matcher.find()) {
224 uri = link.substring(matcher.end());
232 * Generate unique sha digest.
234 * @param keys the keys
237 public static String generateUniqueShaDigest(String... keys) {
239 if ((keys == null) || keys.length == 0) {
243 final String keysStr = Arrays.asList(keys).toString();
244 final String hashedId = org.apache.commons.codec.digest.DigestUtils.sha256Hex(keysStr);
250 * Gets the node field as text.
252 * @param node the node
253 * @param fieldName the field name
254 * @return the node field as text
256 public static String getNodeFieldAsText(JsonNode node, String fieldName) {
258 String fieldValue = null;
260 JsonNode valueNode = node.get(fieldName);
262 if (valueNode != null) {
263 fieldValue = valueNode.asText();
269 private static final String ENTITY_RESOURCE_KEY_FORMAT = "%s.%s";
272 * Convert a millisecond duration to a string format
274 * @param millis A duration to convert to a string form
275 * @return A string of the form "X Days Y Hours Z Minutes A Seconds".
278 private static final String TIME_BREAK_DOWN_FORMAT =
279 "[ %d days, %d hours, %d minutes, %d seconds ]";
282 * Gets the duration breakdown.
284 * @param millis the millis
285 * @return the duration breakdown
287 public static String getDurationBreakdown(long millis) {
290 return String.format(TIME_BREAK_DOWN_FORMAT, 0, 0, 0, 0);
293 long days = TimeUnit.MILLISECONDS.toDays(millis);
294 millis -= TimeUnit.DAYS.toMillis(days);
295 long hours = TimeUnit.MILLISECONDS.toHours(millis);
296 millis -= TimeUnit.HOURS.toMillis(hours);
297 long minutes = TimeUnit.MILLISECONDS.toMinutes(millis);
298 millis -= TimeUnit.MINUTES.toMillis(minutes);
299 long seconds = TimeUnit.MILLISECONDS.toSeconds(millis);
301 return String.format(TIME_BREAK_DOWN_FORMAT, days, hours, minutes, seconds);
306 * Checks if is equal.
310 * @return true, if is equal
312 public static boolean isEqual(JsonNode n1, JsonNode n2) {
315 * due to the inherent nature of json being unordered, comparing object representations of the
316 * same keys and values but different order makes comparison challenging. Let's try an
317 * experiment where we compare the structure of the json, and then simply compare the sorted
318 * order of that structure which should be good enough for what we are trying to accomplish.
321 TreeWalker walker = new TreeWalker();
322 List<String> n1Paths = new ArrayList<String>();
323 List<String> n2Paths = new ArrayList<String>();
325 walker.walkTree(n1Paths, n1);
326 walker.walkTree(n2Paths, n2);
328 Collections.sort(n1Paths);
329 Collections.sort(n2Paths);
331 return n1Paths.equals(n2Paths);
338 * @param list the list
341 public static String concatArray(List<String> list) {
342 return concatArray(list, " ");
345 private static final String TIMESTAMP_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
347 public static String getCurrentTimeStamp() {
348 SimpleDateFormat dateFormat = new SimpleDateFormat(TIMESTAMP_FORMAT);
349 Timestamp timestamp = new Timestamp(System.currentTimeMillis());
350 return dateFormat.format(timestamp);
356 * @param list the list
357 * @param delimiter the delimiter
360 public static String concatArray(List<String> list, String delimiter) {
362 if (list == null || list.size() == 0) {
366 StringBuilder result = new StringBuilder(64);
368 boolean firstValue = true;
370 for (String item : list) {
376 result.append(delimiter).append(item);
381 return result.toString();
388 * @param values the values
391 public static String concatArray(String[] values) {
393 if (values == null || values.length == 0) {
397 StringBuilder result = new StringBuilder(64);
399 boolean firstValue = true;
401 for (String item : values) {
407 result.append(".").append(item);
412 return result.toString();
417 * Builds the entity resource key.
419 * @param entityType the entity type
420 * @param resourceId the resource id
423 public static String buildEntityResourceKey(String entityType, String resourceId) {
424 return String.format(ENTITY_RESOURCE_KEY_FORMAT, entityType, resourceId);
428 * Extract resource id from link.
430 * @param link the link
433 public static String extractResourceIdFromLink(String link) {
439 int linkLength = link.length();
440 if (linkLength == 0) {
445 * if the last character != / then we need to change the lastIndex position
449 String resourceId = null;
450 if ("/".equals(link.substring(linkLength - 1))) {
452 // https://ext1.test.onap.com:9292/aai/v7/business/customers/customer/customer-1/service-subscriptions/service-subscription/service-subscription-1/
453 startIndex = link.lastIndexOf("/", linkLength - 2);
454 resourceId = link.substring(startIndex + 1, linkLength - 1);
457 // https://ext1.test.onap.com:9292/aai/v7/business/customers/customer/customer-1/service-subscriptions/service-subscription/service-subscription-1
458 startIndex = link.lastIndexOf("/");
459 resourceId = link.substring(startIndex + 1, linkLength);
462 String result = null;
464 if (resourceId != null) {
466 result = java.net.URLDecoder.decode(resourceId, "UTF-8");
467 } catch (Exception exc) {
469 * if there is a failure decoding the parameter we will just return the original value.
480 * Gets the xml stream constant as str.
482 * @param value the value
483 * @return the xml stream constant as str
485 public static String getXmlStreamConstantAsStr(int value) {
487 case XMLStreamConstants.ATTRIBUTE:
489 case XMLStreamConstants.CDATA:
491 case XMLStreamConstants.CHARACTERS:
493 case XMLStreamConstants.COMMENT:
495 case XMLStreamConstants.DTD:
497 case XMLStreamConstants.END_DOCUMENT:
498 return "END_DOCUMENT";
499 case XMLStreamConstants.END_ELEMENT:
500 return "END_ELEMENT";
501 case XMLStreamConstants.ENTITY_DECLARATION:
502 return "ENTITY_DECLARATION";
503 case XMLStreamConstants.ENTITY_REFERENCE:
504 return "ENTITY_REFERENCE";
505 case XMLStreamConstants.NAMESPACE:
507 case XMLStreamConstants.NOTATION_DECLARATION:
508 return "NOTATION_DECLARATION";
509 case XMLStreamConstants.PROCESSING_INSTRUCTION:
510 return "PROCESSING_INSTRUCTION";
511 case XMLStreamConstants.SPACE:
513 case XMLStreamConstants.START_DOCUMENT:
514 return "START_DOCUMENT";
515 case XMLStreamConstants.START_ELEMENT:
516 return "START_ELEMENT";
519 return "Unknown(" + value + ")";
524 * Convert object to json.
526 * @param object the object
527 * @param pretty the pretty
529 * @throws JsonProcessingException the json processing exception
531 public static String convertObjectToJson(Object object, boolean pretty)
532 throws JsonProcessingException {
533 ObjectWriter ow = null;
535 ObjectMapper mapper = new ObjectMapper();
536 mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
539 ow = mapper.writer().withDefaultPrettyPrinter();
542 ow = mapper.writer();
545 return ow.writeValueAsString(object);
549 * Convert object to json by selectively choosing certain fields thru filters.
551 * based on request type we might need to send different serialization of the UiViewFilterEntity
553 * @param object the object
554 * @param pretty the pretty
556 * @throws JsonProcessingException the json processing exception
558 public static String convertObjectToJson(Object object, boolean pretty, FilterProvider filters)
559 throws JsonProcessingException {
560 ObjectWriter ow = null;
562 ObjectMapper mapper = new ObjectMapper();
563 mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
566 ow = mapper.writer(filters).withDefaultPrettyPrinter();
569 ow = mapper.writer(filters);
572 return ow.writeValueAsString(object);
577 * Convert json str to json node.
579 * @param jsonStr the json str
580 * @return the json node
581 * @throws IOException Signals that an I/O exception has occurred.
583 public static JsonNode convertJsonStrToJsonNode(String jsonStr) throws IOException {
584 ObjectMapper mapper = new ObjectMapper();
585 if (jsonStr == null || jsonStr.length() == 0) {
589 return mapper.readTree(jsonStr);
593 * Convert object to xml.
595 * @param object the object
597 * @throws JsonProcessingException the json processing exception
599 public static String convertObjectToXml(Object object) throws JsonProcessingException {
600 ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
601 String jsonOutput = ow.writeValueAsString(object);
603 if (jsonOutput == null) {
607 return JsonXmlConverter.convertJsontoXml(jsonOutput);
612 * Extract objects by key.
614 * @param node the node
615 * @param searchKey the search key
616 * @param foundObjects the found objects
618 public static void extractObjectsByKey(JsonNode node, String searchKey,
619 Collection<JsonNode> foundObjects) {
621 if ( node == null ) {
625 if (node.isObject()) {
626 Iterator<Map.Entry<String, JsonNode>> nodeIterator = node.fields();
628 while (nodeIterator.hasNext()) {
629 Map.Entry<String, JsonNode> entry = nodeIterator.next();
630 if (!entry.getValue().isValueNode()) {
631 extractObjectsByKey(entry.getValue(), searchKey, foundObjects);
634 String name = entry.getKey();
635 if (name.equalsIgnoreCase(searchKey)) {
637 JsonNode entryNode = entry.getValue();
639 if (entryNode.isArray()) {
641 Iterator<JsonNode> arrayItemsIterator = entryNode.elements();
642 while (arrayItemsIterator.hasNext()) {
643 foundObjects.add(arrayItemsIterator.next());
647 foundObjects.add(entry.getValue());
653 } else if (node.isArray()) {
654 Iterator<JsonNode> arrayItemsIterator = node.elements();
655 while (arrayItemsIterator.hasNext()) {
656 extractObjectsByKey(arrayItemsIterator.next(), searchKey, foundObjects);
662 public static String extractObjectValueByKey(JsonNode node, String searchKey) {
668 if (node.isObject()) {
669 Iterator<Map.Entry<String, JsonNode>> nodeIterator = node.fields();
671 while (nodeIterator.hasNext()) {
672 Map.Entry<String, JsonNode> entry = nodeIterator.next();
673 if (!entry.getValue().isValueNode()) {
674 return extractObjectValueByKey(entry.getValue(), searchKey);
677 String name = entry.getKey();
678 if (name.equalsIgnoreCase(searchKey)) {
680 JsonNode entryNode = entry.getValue();
682 if (entryNode.isArray()) {
684 Iterator<JsonNode> arrayItemsIterator = entryNode.elements();
685 while (arrayItemsIterator.hasNext()) {
686 return arrayItemsIterator.next().asText();
690 return entry.getValue().asText();
696 } else if (node.isArray()) {
697 Iterator<JsonNode> arrayItemsIterator = node.elements();
698 while (arrayItemsIterator.hasNext()) {
699 return extractObjectValueByKey(arrayItemsIterator.next(), searchKey);
709 * Convert array into list.
711 * @param node the node
712 * @param instances the instances
714 public static void convertArrayIntoList(JsonNode node, Collection<JsonNode> instances) {
716 if (node.isArray()) {
717 Iterator<JsonNode> arrayItemsIterator = node.elements();
718 while (arrayItemsIterator.hasNext()) {
719 instances.add(arrayItemsIterator.next());
729 * Extract field values from object.
731 * @param node the node
732 * @param attributesToExtract the attributes to extract
733 * @param fieldValues the field values
735 public static void extractFieldValuesFromObject(JsonNode node,
736 Collection<String> attributesToExtract, Collection<String> fieldValues) {
742 if (node.isObject()) {
744 JsonNode valueNode = null;
746 for (String attrToExtract : attributesToExtract) {
748 valueNode = node.get(attrToExtract);
750 if (valueNode != null) {
752 if (valueNode.isValueNode()) {
753 fieldValues.add(valueNode.asText());
761 * Extract field value from object.
763 * @param node the node
764 * @param fieldName the field name
767 public static String extractFieldValueFromObject(JsonNode node, String fieldName) {
773 if (node.isObject()) {
775 JsonNode valueNode = node.get(fieldName);
777 if (valueNode != null) {
779 if (valueNode.isValueNode()) {
780 return valueNode.asText();
792 * @param timestamp the timestamp
795 public static String formatTimestamp(String timestamp) {
797 SimpleDateFormat originalFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
798 originalFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
799 Date toDate = originalFormat.parse(timestamp);
800 SimpleDateFormat newFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
801 newFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
802 return newFormat.format(toDate);
804 } catch (ParseException pe) {
810 * Gets the HttpRequest payload.
812 * @param request the request
814 * @throws IOException Signals that an I/O exception has occurred.
816 public static String getBody(HttpServletRequest request) throws IOException {
817 InputStream inputStream = request.getInputStream();
818 return getBodyFromStream(inputStream);
824 * Gets the Restlet Request payload.
826 * @param request the request
828 * @throws IOException Signals that an I/O exception has occurred.
830 public static String getBody(Request request) throws IOException {
831 InputStream inputStream = request.getEntity().getStream();
832 return getBodyFromStream(inputStream);
837 * Gets the payload from the input stream of a request.
839 * @param request the request
841 * @throws IOException Signals that an I/O exception has occurred.
843 public static String getBodyFromStream(InputStream inputStream) throws IOException {
846 StringBuilder stringBuilder = new StringBuilder();
847 BufferedReader bufferedReader = null;
850 if (inputStream != null) {
851 bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
852 char[] charBuffer = new char[128];
854 while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
855 stringBuilder.append(charBuffer, 0, bytesRead);
858 stringBuilder.append("");
860 } catch (IOException ex) {
863 if (bufferedReader != null) {
865 bufferedReader.close();
866 } catch (IOException ex) {
872 body = stringBuilder.toString();
880 * @param args the arguments
881 * @throws ParseException the parse exception
883 public static void main(String[] args) throws ParseException {
884 String date = "20170110T112312Z";
885 SimpleDateFormat originalFormat = new SimpleDateFormat("yyyyMMdd'T'hhmmss'Z'");
886 Date toDate = originalFormat.parse(date);
887 SimpleDateFormat newFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss'Z'");
888 System.out.println(newFormat.format(toDate));