2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
6 * Copyright © 2017-2018 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 package org.onap.aai.sparky.util;
23 import java.io.BufferedReader;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.io.InputStreamReader;
27 import java.lang.Thread.UncaughtExceptionHandler;
29 import java.nio.ByteBuffer;
30 import java.security.SecureRandom;
31 import java.sql.Timestamp;
32 import java.text.ParseException;
33 import java.text.SimpleDateFormat;
34 import java.util.ArrayList;
35 import java.util.Arrays;
36 import java.util.Collection;
37 import java.util.Collections;
38 import java.util.Date;
39 import java.util.Iterator;
40 import java.util.List;
42 import java.util.TimeZone;
43 import java.util.concurrent.ExecutorService;
44 import java.util.concurrent.Executors;
45 import java.util.concurrent.ThreadFactory;
46 import java.util.concurrent.TimeUnit;
47 import java.util.regex.Matcher;
48 import java.util.regex.Pattern;
50 import javax.servlet.http.HttpServletRequest;
51 import javax.xml.stream.XMLStreamConstants;
53 import org.onap.aai.cl.api.Logger;
54 import org.onap.aai.sparky.logging.AaiUiMsgs;
55 import org.onap.aai.sparky.viewandinspect.config.SparkyConstants;
56 import org.restlet.Request;
58 import com.fasterxml.jackson.core.JsonProcessingException;
59 import com.fasterxml.jackson.databind.JsonNode;
60 import com.fasterxml.jackson.databind.ObjectMapper;
61 import com.fasterxml.jackson.databind.ObjectWriter;
62 import com.fasterxml.jackson.databind.SerializationFeature;
63 import com.fasterxml.jackson.databind.ser.FilterProvider;
64 import com.google.common.util.concurrent.ThreadFactoryBuilder;
68 * The Class NodeUtils.
70 public class NodeUtils {
71 private static SecureRandom sRandom = new SecureRandom();
73 private static final Pattern AAI_VERSION_PREFIX = Pattern.compile("/aai/v[0-9]+/(.*)");
74 private static final Pattern GIZMO_VERSION_PREFIX = Pattern.compile("[/]*services/inventory/v[0-9]+/(.*)");
75 private static final Pattern GIZMO_RELATIONSHIP_VERSION_PREFIX = Pattern.compile("services/inventory/relationships/v[0-9]+/(.*)");
78 public static synchronized String getRandomTxnId(){
79 byte bytes[] = new byte[6];
80 sRandom.nextBytes(bytes);
81 return Integer.toUnsignedString(ByteBuffer.wrap(bytes).getInt());
85 * Builds the depth padding.
87 * @param depth the depth
90 public static String buildDepthPadding(int depth) {
91 StringBuilder sb = new StringBuilder(32);
93 for (int x = 0; x < depth; x++) {
101 public static String extractRawPathWithoutVersion(String selfLinkUri) {
105 String rawPath = new URI(selfLinkUri).getRawPath();
107 Matcher m = AAI_VERSION_PREFIX.matcher(rawPath);
111 if ( m.groupCount() >= 1) {
116 } catch (Exception e) {
123 public static String extractRawGizmoPathWithoutVersion(String resourceLink) {
127 String rawPath = new URI(resourceLink).getRawPath();
129 Matcher m = GIZMO_VERSION_PREFIX.matcher(rawPath);
133 if ( m.groupCount() >= 1) {
138 } catch (Exception e) {
145 public static String extractRawGizmoRelationshipPathWithoutVersion(String resourceLink) {
149 String rawPath = new URI(resourceLink).getRawPath();
151 Matcher m = GIZMO_RELATIONSHIP_VERSION_PREFIX.matcher(rawPath);
155 if ( m.groupCount() >= 1) {
160 } catch (Exception e) {
171 * Checks if is numeric.
173 * @param numberStr the number str
174 * @return true, if is numeric
176 public static boolean isNumeric(String numberStr) {
179 Double.parseDouble(numberStr);
180 } catch (Exception exc) {
189 * Creates the named executor.
191 * @param name the name
192 * @param numWorkers the num workers
193 * @param logger the logger
194 * @return the executor service
196 public static ExecutorService createNamedExecutor(String name, int numWorkers, final Logger logger) {
197 UncaughtExceptionHandler uncaughtExceptionHandler = new Thread.UncaughtExceptionHandler() {
200 public void uncaughtException(Thread thread, Throwable exc) {
202 logger.error(AaiUiMsgs.ERROR_GENERIC, thread.getName() + ": " + exc);
207 ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat(name + "-%d")
208 .setUncaughtExceptionHandler(uncaughtExceptionHandler).build();
210 return Executors.newScheduledThreadPool(numWorkers + 1, namedThreadFactory);
214 public static String calculateEditAttributeUri(String link) {
219 Pattern pattern = Pattern.compile(SparkyConstants.URI_VERSION_REGEX_PATTERN);
220 Matcher matcher = pattern.matcher(link);
221 if (matcher.find()) {
222 uri = link.substring(matcher.end());
230 * Generate unique sha digest.
232 * @param keys the keys
235 public static String generateUniqueShaDigest(String... keys) {
237 if ((keys == null) || keys.length == 0) {
241 final String keysStr = Arrays.asList(keys).toString();
242 final String hashedId = org.apache.commons.codec.digest.DigestUtils.sha256Hex(keysStr);
248 * Gets the node field as text.
250 * @param node the node
251 * @param fieldName the field name
252 * @return the node field as text
254 public static String getNodeFieldAsText(JsonNode node, String fieldName) {
256 String fieldValue = null;
258 JsonNode valueNode = node.get(fieldName);
260 if (valueNode != null) {
261 fieldValue = valueNode.asText();
267 private static final String ENTITY_RESOURCE_KEY_FORMAT = "%s.%s";
270 * Convert a millisecond duration to a string format
272 * @param millis A duration to convert to a string form
273 * @return A string of the form "X Days Y Hours Z Minutes A Seconds".
276 private static final String TIME_BREAK_DOWN_FORMAT =
277 "[ %d days, %d hours, %d minutes, %d seconds ]";
280 * Gets the duration breakdown.
282 * @param millis the millis
283 * @return the duration breakdown
285 public static String getDurationBreakdown(long millis) {
288 return String.format(TIME_BREAK_DOWN_FORMAT, 0, 0, 0, 0);
291 long days = TimeUnit.MILLISECONDS.toDays(millis);
292 millis -= TimeUnit.DAYS.toMillis(days);
293 long hours = TimeUnit.MILLISECONDS.toHours(millis);
294 millis -= TimeUnit.HOURS.toMillis(hours);
295 long minutes = TimeUnit.MILLISECONDS.toMinutes(millis);
296 millis -= TimeUnit.MINUTES.toMillis(minutes);
297 long seconds = TimeUnit.MILLISECONDS.toSeconds(millis);
299 return String.format(TIME_BREAK_DOWN_FORMAT, days, hours, minutes, seconds);
304 * Checks if is equal.
308 * @return true, if is equal
310 public static boolean isEqual(JsonNode n1, JsonNode n2) {
313 * due to the inherent nature of json being unordered, comparing object representations of the
314 * same keys and values but different order makes comparison challenging. Let's try an
315 * experiment where we compare the structure of the json, and then simply compare the sorted
316 * order of that structure which should be good enough for what we are trying to accomplish.
319 TreeWalker walker = new TreeWalker();
320 List<String> n1Paths = new ArrayList<String>();
321 List<String> n2Paths = new ArrayList<String>();
323 walker.walkTree(n1Paths, n1);
324 walker.walkTree(n2Paths, n2);
326 Collections.sort(n1Paths);
327 Collections.sort(n2Paths);
329 return n1Paths.equals(n2Paths);
336 * @param list the list
339 public static String concatArray(List<String> list) {
340 return concatArray(list, " ");
343 private static final String TIMESTAMP_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
345 public static String getCurrentTimeStamp() {
346 SimpleDateFormat dateFormat = new SimpleDateFormat(TIMESTAMP_FORMAT);
347 Timestamp timestamp = new Timestamp(System.currentTimeMillis());
348 return dateFormat.format(timestamp);
354 * @param list the list
355 * @param delimiter the delimiter
358 public static String concatArray(List<String> list, String delimiter) {
360 if (list == null || list.size() == 0) {
364 StringBuilder result = new StringBuilder(64);
366 boolean firstValue = true;
368 for (String item : list) {
374 result.append(delimiter).append(item);
379 return result.toString();
386 * @param values the values
389 public static String concatArray(String[] values) {
391 if (values == null || values.length == 0) {
395 StringBuilder result = new StringBuilder(64);
397 boolean firstValue = true;
399 for (String item : values) {
405 result.append(".").append(item);
410 return result.toString();
415 * Builds the entity resource key.
417 * @param entityType the entity type
418 * @param resourceId the resource id
421 public static String buildEntityResourceKey(String entityType, String resourceId) {
422 return String.format(ENTITY_RESOURCE_KEY_FORMAT, entityType, resourceId);
426 * Extract resource id from link.
428 * @param link the link
431 public static String extractResourceIdFromLink(String link) {
437 int linkLength = link.length();
438 if (linkLength == 0) {
443 * if the last character != / then we need to change the lastIndex position
447 String resourceId = null;
448 if ("/".equals(link.substring(linkLength - 1))) {
450 // https://ext1.test.onap.com:9292/aai/v7/business/customers/customer/customer-1/service-subscriptions/service-subscription/service-subscription-1/
451 startIndex = link.lastIndexOf("/", linkLength - 2);
452 resourceId = link.substring(startIndex + 1, linkLength - 1);
455 // https://ext1.test.onap.com:9292/aai/v7/business/customers/customer/customer-1/service-subscriptions/service-subscription/service-subscription-1
456 startIndex = link.lastIndexOf("/");
457 resourceId = link.substring(startIndex + 1, linkLength);
460 String result = null;
462 if (resourceId != null) {
464 result = java.net.URLDecoder.decode(resourceId, "UTF-8");
465 } catch (Exception exc) {
467 * if there is a failure decoding the parameter we will just return the original value.
478 * Gets the xml stream constant as str.
480 * @param value the value
481 * @return the xml stream constant as str
483 public static String getXmlStreamConstantAsStr(int value) {
485 case XMLStreamConstants.ATTRIBUTE:
487 case XMLStreamConstants.CDATA:
489 case XMLStreamConstants.CHARACTERS:
491 case XMLStreamConstants.COMMENT:
493 case XMLStreamConstants.DTD:
495 case XMLStreamConstants.END_DOCUMENT:
496 return "END_DOCUMENT";
497 case XMLStreamConstants.END_ELEMENT:
498 return "END_ELEMENT";
499 case XMLStreamConstants.ENTITY_DECLARATION:
500 return "ENTITY_DECLARATION";
501 case XMLStreamConstants.ENTITY_REFERENCE:
502 return "ENTITY_REFERENCE";
503 case XMLStreamConstants.NAMESPACE:
505 case XMLStreamConstants.NOTATION_DECLARATION:
506 return "NOTATION_DECLARATION";
507 case XMLStreamConstants.PROCESSING_INSTRUCTION:
508 return "PROCESSING_INSTRUCTION";
509 case XMLStreamConstants.SPACE:
511 case XMLStreamConstants.START_DOCUMENT:
512 return "START_DOCUMENT";
513 case XMLStreamConstants.START_ELEMENT:
514 return "START_ELEMENT";
517 return "Unknown(" + value + ")";
522 * Convert object to json.
524 * @param object the object
525 * @param pretty the pretty
527 * @throws JsonProcessingException the json processing exception
529 public static String convertObjectToJson(Object object, boolean pretty)
530 throws JsonProcessingException {
531 ObjectWriter ow = null;
533 ObjectMapper mapper = new ObjectMapper();
534 mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
537 ow = mapper.writer().withDefaultPrettyPrinter();
540 ow = mapper.writer();
543 return ow.writeValueAsString(object);
547 * Convert object to json by selectively choosing certain fields thru filters.
549 * based on request type we might need to send different serialization of the UiViewFilterEntity
551 * @param object the object
552 * @param pretty the pretty
554 * @throws JsonProcessingException the json processing exception
556 public static String convertObjectToJson(Object object, boolean pretty, FilterProvider filters)
557 throws JsonProcessingException {
558 ObjectWriter ow = null;
560 ObjectMapper mapper = new ObjectMapper();
561 mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
564 ow = mapper.writer(filters).withDefaultPrettyPrinter();
567 ow = mapper.writer(filters);
570 return ow.writeValueAsString(object);
575 * Convert json str to json node.
577 * @param jsonStr the json str
578 * @return the json node
579 * @throws IOException Signals that an I/O exception has occurred.
581 public static JsonNode convertJsonStrToJsonNode(String jsonStr) throws IOException {
582 ObjectMapper mapper = new ObjectMapper();
583 if (jsonStr == null || jsonStr.length() == 0) {
587 return mapper.readTree(jsonStr);
591 * Convert object to xml.
593 * @param object the object
595 * @throws JsonProcessingException the json processing exception
597 public static String convertObjectToXml(Object object) throws JsonProcessingException {
598 ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
599 String jsonOutput = ow.writeValueAsString(object);
601 if (jsonOutput == null) {
605 return JsonXmlConverter.convertJsontoXml(jsonOutput);
610 * Extract objects by key.
612 * @param node the node
613 * @param searchKey the search key
614 * @param foundObjects the found objects
616 public static void extractObjectsByKey(JsonNode node, String searchKey,
617 Collection<JsonNode> foundObjects) {
619 if ( node == null ) {
623 if (node.isObject()) {
624 Iterator<Map.Entry<String, JsonNode>> nodeIterator = node.fields();
626 while (nodeIterator.hasNext()) {
627 Map.Entry<String, JsonNode> entry = nodeIterator.next();
628 if (!entry.getValue().isValueNode()) {
629 extractObjectsByKey(entry.getValue(), searchKey, foundObjects);
632 String name = entry.getKey();
633 if (name.equalsIgnoreCase(searchKey)) {
635 JsonNode entryNode = entry.getValue();
637 if (entryNode.isArray()) {
639 Iterator<JsonNode> arrayItemsIterator = entryNode.elements();
640 while (arrayItemsIterator.hasNext()) {
641 foundObjects.add(arrayItemsIterator.next());
645 foundObjects.add(entry.getValue());
651 } else if (node.isArray()) {
652 Iterator<JsonNode> arrayItemsIterator = node.elements();
653 while (arrayItemsIterator.hasNext()) {
654 extractObjectsByKey(arrayItemsIterator.next(), searchKey, foundObjects);
660 public static String extractObjectValueByKey(JsonNode node, String searchKey) {
666 if (node.isObject()) {
667 Iterator<Map.Entry<String, JsonNode>> nodeIterator = node.fields();
669 while (nodeIterator.hasNext()) {
670 Map.Entry<String, JsonNode> entry = nodeIterator.next();
671 if (!entry.getValue().isValueNode()) {
672 return extractObjectValueByKey(entry.getValue(), searchKey);
675 String name = entry.getKey();
676 if (name.equalsIgnoreCase(searchKey)) {
678 JsonNode entryNode = entry.getValue();
680 if (entryNode.isArray()) {
682 Iterator<JsonNode> arrayItemsIterator = entryNode.elements();
683 while (arrayItemsIterator.hasNext()) {
684 return arrayItemsIterator.next().asText();
688 return entry.getValue().asText();
694 } else if (node.isArray()) {
695 Iterator<JsonNode> arrayItemsIterator = node.elements();
696 while (arrayItemsIterator.hasNext()) {
697 return extractObjectValueByKey(arrayItemsIterator.next(), searchKey);
707 * Convert array into list.
709 * @param node the node
710 * @param instances the instances
712 public static void convertArrayIntoList(JsonNode node, Collection<JsonNode> instances) {
714 if (node.isArray()) {
715 Iterator<JsonNode> arrayItemsIterator = node.elements();
716 while (arrayItemsIterator.hasNext()) {
717 instances.add(arrayItemsIterator.next());
727 * Extract field values from object.
729 * @param node the node
730 * @param attributesToExtract the attributes to extract
731 * @param fieldValues the field values
733 public static void extractFieldValuesFromObject(JsonNode node,
734 Collection<String> attributesToExtract, Collection<String> fieldValues) {
740 if (node.isObject()) {
742 JsonNode valueNode = null;
744 for (String attrToExtract : attributesToExtract) {
746 valueNode = node.get(attrToExtract);
748 if (valueNode != null) {
750 if (valueNode.isValueNode()) {
751 fieldValues.add(valueNode.asText());
759 * Extract field value from object.
761 * @param node the node
762 * @param fieldName the field name
765 public static String extractFieldValueFromObject(JsonNode node, String fieldName) {
771 if (node.isObject()) {
773 JsonNode valueNode = node.get(fieldName);
775 if (valueNode != null) {
777 if (valueNode.isValueNode()) {
778 return valueNode.asText();
790 * @param timestamp the timestamp
793 public static String formatTimestamp(String timestamp) {
795 SimpleDateFormat originalFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
796 originalFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
797 Date toDate = originalFormat.parse(timestamp);
798 SimpleDateFormat newFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
799 newFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
800 return newFormat.format(toDate);
802 } catch (ParseException pe) {
808 * Gets the HttpRequest payload.
810 * @param request the request
812 * @throws IOException Signals that an I/O exception has occurred.
814 public static String getBody(HttpServletRequest request) throws IOException {
815 InputStream inputStream = request.getInputStream();
816 return getBodyFromStream(inputStream);
822 * Gets the Restlet Request payload.
824 * @param request the request
826 * @throws IOException Signals that an I/O exception has occurred.
828 public static String getBody(Request request) throws IOException {
829 InputStream inputStream = request.getEntity().getStream();
830 return getBodyFromStream(inputStream);
835 * Gets the payload from the input stream of a request.
837 * @param request the request
839 * @throws IOException Signals that an I/O exception has occurred.
841 public static String getBodyFromStream(InputStream inputStream) throws IOException {
844 StringBuilder stringBuilder = new StringBuilder();
845 BufferedReader bufferedReader = null;
848 if (inputStream != null) {
849 bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
850 char[] charBuffer = new char[128];
852 while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
853 stringBuilder.append(charBuffer, 0, bytesRead);
856 stringBuilder.append("");
858 } catch (IOException ex) {
861 if (bufferedReader != null) {
863 bufferedReader.close();
864 } catch (IOException ex) {
870 body = stringBuilder.toString();
878 * @param args the arguments
879 * @throws ParseException the parse exception
881 public static void main(String[] args) throws ParseException {
882 String date = "20170110T112312Z";
883 SimpleDateFormat originalFormat = new SimpleDateFormat("yyyyMMdd'T'hhmmss'Z'");
884 Date toDate = originalFormat.parse(date);
885 SimpleDateFormat newFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss'Z'");
886 System.out.println(newFormat.format(toDate));