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]+/(.*)");
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) {
124 * Checks if is numeric.
126 * @param numberStr the number str
127 * @return true, if is numeric
129 public static boolean isNumeric(String numberStr) {
132 Double.parseDouble(numberStr);
133 } catch (Exception exc) {
142 * Creates the named executor.
144 * @param name the name
145 * @param numWorkers the num workers
146 * @param logger the logger
147 * @return the executor service
149 public static ExecutorService createNamedExecutor(String name, int numWorkers, final Logger logger) {
150 UncaughtExceptionHandler uncaughtExceptionHandler = new Thread.UncaughtExceptionHandler() {
153 public void uncaughtException(Thread thread, Throwable exc) {
155 logger.error(AaiUiMsgs.ERROR_GENERIC, thread.getName() + ": " + exc);
160 ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat(name + "-%d")
161 .setUncaughtExceptionHandler(uncaughtExceptionHandler).build();
163 return Executors.newScheduledThreadPool(numWorkers + 1, namedThreadFactory);
167 * Calculate edit attribute uri.
169 * @param link the link
172 public static String calculateEditAttributeUri(String link) {
177 Pattern pattern = Pattern.compile(SparkyConstants.URI_VERSION_REGEX_PATTERN);
178 Matcher matcher = pattern.matcher(link);
179 if (matcher.find()) {
180 uri = link.substring(matcher.end());
187 * Generate unique sha digest.
189 * @param keys the keys
192 public static String generateUniqueShaDigest(String... keys) {
194 if ((keys == null) || keys.length == 0) {
198 final String keysStr = Arrays.asList(keys).toString();
199 final String hashedId = org.apache.commons.codec.digest.DigestUtils.sha256Hex(keysStr);
205 * Gets the node field as text.
207 * @param node the node
208 * @param fieldName the field name
209 * @return the node field as text
211 public static String getNodeFieldAsText(JsonNode node, String fieldName) {
213 String fieldValue = null;
215 JsonNode valueNode = node.get(fieldName);
217 if (valueNode != null) {
218 fieldValue = valueNode.asText();
224 private static final String ENTITY_RESOURCE_KEY_FORMAT = "%s.%s";
227 * Convert a millisecond duration to a string format
229 * @param millis A duration to convert to a string form
230 * @return A string of the form "X Days Y Hours Z Minutes A Seconds".
233 private static final String TIME_BREAK_DOWN_FORMAT =
234 "[ %d days, %d hours, %d minutes, %d seconds ]";
237 * Gets the duration breakdown.
239 * @param millis the millis
240 * @return the duration breakdown
242 public static String getDurationBreakdown(long millis) {
245 return String.format(TIME_BREAK_DOWN_FORMAT, 0, 0, 0, 0);
248 long days = TimeUnit.MILLISECONDS.toDays(millis);
249 millis -= TimeUnit.DAYS.toMillis(days);
250 long hours = TimeUnit.MILLISECONDS.toHours(millis);
251 millis -= TimeUnit.HOURS.toMillis(hours);
252 long minutes = TimeUnit.MILLISECONDS.toMinutes(millis);
253 millis -= TimeUnit.MINUTES.toMillis(minutes);
254 long seconds = TimeUnit.MILLISECONDS.toSeconds(millis);
256 return String.format(TIME_BREAK_DOWN_FORMAT, days, hours, minutes, seconds);
261 * Checks if is equal.
265 * @return true, if is equal
267 public static boolean isEqual(JsonNode n1, JsonNode n2) {
270 * due to the inherent nature of json being unordered, comparing object representations of the
271 * same keys and values but different order makes comparison challenging. Let's try an
272 * experiment where we compare the structure of the json, and then simply compare the sorted
273 * order of that structure which should be good enough for what we are trying to accomplish.
276 TreeWalker walker = new TreeWalker();
277 List<String> n1Paths = new ArrayList<String>();
278 List<String> n2Paths = new ArrayList<String>();
280 walker.walkTree(n1Paths, n1);
281 walker.walkTree(n2Paths, n2);
283 Collections.sort(n1Paths);
284 Collections.sort(n2Paths);
286 return n1Paths.equals(n2Paths);
293 * @param list the list
296 public static String concatArray(List<String> list) {
297 return concatArray(list, " ");
300 private static final String TIMESTAMP_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
302 public static String getCurrentTimeStamp() {
303 SimpleDateFormat dateFormat = new SimpleDateFormat(TIMESTAMP_FORMAT);
304 Timestamp timestamp = new Timestamp(System.currentTimeMillis());
305 return dateFormat.format(timestamp);
311 * @param list the list
312 * @param delimiter the delimiter
315 public static String concatArray(List<String> list, String delimiter) {
317 if (list == null || list.size() == 0) {
321 StringBuilder result = new StringBuilder(64);
323 boolean firstValue = true;
325 for (String item : list) {
331 result.append(delimiter).append(item);
336 return result.toString();
343 * @param values the values
346 public static String concatArray(String[] values) {
348 if (values == null || values.length == 0) {
352 StringBuilder result = new StringBuilder(64);
354 boolean firstValue = true;
356 for (String item : values) {
362 result.append(".").append(item);
367 return result.toString();
372 * Builds the entity resource key.
374 * @param entityType the entity type
375 * @param resourceId the resource id
378 public static String buildEntityResourceKey(String entityType, String resourceId) {
379 return String.format(ENTITY_RESOURCE_KEY_FORMAT, entityType, resourceId);
383 * Extract resource id from link.
385 * @param link the link
388 public static String extractResourceIdFromLink(String link) {
394 int linkLength = link.length();
395 if (linkLength == 0) {
400 * if the last character != / then we need to change the lastIndex position
404 String resourceId = null;
405 if ("/".equals(link.substring(linkLength - 1))) {
407 // https://ext1.test.onap.com:9292/aai/v7/business/customers/customer/customer-1/service-subscriptions/service-subscription/service-subscription-1/
408 startIndex = link.lastIndexOf("/", linkLength - 2);
409 resourceId = link.substring(startIndex + 1, linkLength - 1);
412 // https://ext1.test.onap.com:9292/aai/v7/business/customers/customer/customer-1/service-subscriptions/service-subscription/service-subscription-1
413 startIndex = link.lastIndexOf("/");
414 resourceId = link.substring(startIndex + 1, linkLength);
417 String result = null;
419 if (resourceId != null) {
421 result = java.net.URLDecoder.decode(resourceId, "UTF-8");
422 } catch (Exception exc) {
424 * if there is a failure decoding the parameter we will just return the original value.
435 * Gets the xml stream constant as str.
437 * @param value the value
438 * @return the xml stream constant as str
440 public static String getXmlStreamConstantAsStr(int value) {
442 case XMLStreamConstants.ATTRIBUTE:
444 case XMLStreamConstants.CDATA:
446 case XMLStreamConstants.CHARACTERS:
448 case XMLStreamConstants.COMMENT:
450 case XMLStreamConstants.DTD:
452 case XMLStreamConstants.END_DOCUMENT:
453 return "END_DOCUMENT";
454 case XMLStreamConstants.END_ELEMENT:
455 return "END_ELEMENT";
456 case XMLStreamConstants.ENTITY_DECLARATION:
457 return "ENTITY_DECLARATION";
458 case XMLStreamConstants.ENTITY_REFERENCE:
459 return "ENTITY_REFERENCE";
460 case XMLStreamConstants.NAMESPACE:
462 case XMLStreamConstants.NOTATION_DECLARATION:
463 return "NOTATION_DECLARATION";
464 case XMLStreamConstants.PROCESSING_INSTRUCTION:
465 return "PROCESSING_INSTRUCTION";
466 case XMLStreamConstants.SPACE:
468 case XMLStreamConstants.START_DOCUMENT:
469 return "START_DOCUMENT";
470 case XMLStreamConstants.START_ELEMENT:
471 return "START_ELEMENT";
474 return "Unknown(" + value + ")";
479 * Convert object to json.
481 * @param object the object
482 * @param pretty the pretty
484 * @throws JsonProcessingException the json processing exception
486 public static String convertObjectToJson(Object object, boolean pretty)
487 throws JsonProcessingException {
488 ObjectWriter ow = null;
490 ObjectMapper mapper = new ObjectMapper();
491 mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
494 ow = mapper.writer().withDefaultPrettyPrinter();
497 ow = mapper.writer();
500 return ow.writeValueAsString(object);
504 * Convert object to json by selectively choosing certain fields thru filters.
506 * based on request type we might need to send different serialization of the UiViewFilterEntity
508 * @param object the object
509 * @param pretty the pretty
511 * @throws JsonProcessingException the json processing exception
513 public static String convertObjectToJson(Object object, boolean pretty, FilterProvider filters)
514 throws JsonProcessingException {
515 ObjectWriter ow = null;
517 ObjectMapper mapper = new ObjectMapper();
518 mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
521 ow = mapper.writer(filters).withDefaultPrettyPrinter();
524 ow = mapper.writer(filters);
527 return ow.writeValueAsString(object);
532 * Convert json str to json node.
534 * @param jsonStr the json str
535 * @return the json node
536 * @throws IOException Signals that an I/O exception has occurred.
538 public static JsonNode convertJsonStrToJsonNode(String jsonStr) throws IOException {
539 ObjectMapper mapper = new ObjectMapper();
540 if (jsonStr == null || jsonStr.length() == 0) {
544 return mapper.readTree(jsonStr);
548 * Convert object to xml.
550 * @param object the object
552 * @throws JsonProcessingException the json processing exception
554 public static String convertObjectToXml(Object object) throws JsonProcessingException {
555 ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
556 String jsonOutput = ow.writeValueAsString(object);
558 if (jsonOutput == null) {
562 return JsonXmlConverter.convertJsontoXml(jsonOutput);
567 * Extract objects by key.
569 * @param node the node
570 * @param searchKey the search key
571 * @param foundObjects the found objects
573 public static void extractObjectsByKey(JsonNode node, String searchKey,
574 Collection<JsonNode> foundObjects) {
576 if ( node == null ) {
580 if (node.isObject()) {
581 Iterator<Map.Entry<String, JsonNode>> nodeIterator = node.fields();
583 while (nodeIterator.hasNext()) {
584 Map.Entry<String, JsonNode> entry = nodeIterator.next();
585 if (!entry.getValue().isValueNode()) {
586 extractObjectsByKey(entry.getValue(), searchKey, foundObjects);
589 String name = entry.getKey();
590 if (name.equalsIgnoreCase(searchKey)) {
592 JsonNode entryNode = entry.getValue();
594 if (entryNode.isArray()) {
596 Iterator<JsonNode> arrayItemsIterator = entryNode.elements();
597 while (arrayItemsIterator.hasNext()) {
598 foundObjects.add(arrayItemsIterator.next());
602 foundObjects.add(entry.getValue());
608 } else if (node.isArray()) {
609 Iterator<JsonNode> arrayItemsIterator = node.elements();
610 while (arrayItemsIterator.hasNext()) {
611 extractObjectsByKey(arrayItemsIterator.next(), searchKey, foundObjects);
619 * Convert array into list.
621 * @param node the node
622 * @param instances the instances
624 public static void convertArrayIntoList(JsonNode node, Collection<JsonNode> instances) {
626 if (node.isArray()) {
627 Iterator<JsonNode> arrayItemsIterator = node.elements();
628 while (arrayItemsIterator.hasNext()) {
629 instances.add(arrayItemsIterator.next());
639 * Extract field values from object.
641 * @param node the node
642 * @param attributesToExtract the attributes to extract
643 * @param fieldValues the field values
645 public static void extractFieldValuesFromObject(JsonNode node,
646 Collection<String> attributesToExtract, Collection<String> fieldValues) {
652 if (node.isObject()) {
654 JsonNode valueNode = null;
656 for (String attrToExtract : attributesToExtract) {
658 valueNode = node.get(attrToExtract);
660 if (valueNode != null) {
662 if (valueNode.isValueNode()) {
663 fieldValues.add(valueNode.asText());
671 * Extract field value from object.
673 * @param node the node
674 * @param fieldName the field name
677 public static String extractFieldValueFromObject(JsonNode node, String fieldName) {
683 if (node.isObject()) {
685 JsonNode valueNode = node.get(fieldName);
687 if (valueNode != null) {
689 if (valueNode.isValueNode()) {
690 return valueNode.asText();
702 * @param timestamp the timestamp
705 public static String formatTimestamp(String timestamp) {
707 SimpleDateFormat originalFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
708 originalFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
709 Date toDate = originalFormat.parse(timestamp);
710 SimpleDateFormat newFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
711 newFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
712 return newFormat.format(toDate);
714 } catch (ParseException pe) {
720 * Gets the HttpRequest payload.
722 * @param request the request
724 * @throws IOException Signals that an I/O exception has occurred.
726 public static String getBody(HttpServletRequest request) throws IOException {
727 InputStream inputStream = request.getInputStream();
728 return getBodyFromStream(inputStream);
734 * Gets the Restlet Request payload.
736 * @param request the request
738 * @throws IOException Signals that an I/O exception has occurred.
740 public static String getBody(Request request) throws IOException {
741 InputStream inputStream = request.getEntity().getStream();
742 return getBodyFromStream(inputStream);
747 * Gets the payload from the input stream of a request.
749 * @param request the request
751 * @throws IOException Signals that an I/O exception has occurred.
753 public static String getBodyFromStream(InputStream inputStream) throws IOException {
756 StringBuilder stringBuilder = new StringBuilder();
757 BufferedReader bufferedReader = null;
760 if (inputStream != null) {
761 bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
762 char[] charBuffer = new char[128];
764 while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
765 stringBuilder.append(charBuffer, 0, bytesRead);
768 stringBuilder.append("");
770 } catch (IOException ex) {
773 if (bufferedReader != null) {
775 bufferedReader.close();
776 } catch (IOException ex) {
782 body = stringBuilder.toString();
790 * @param args the arguments
791 * @throws ParseException the parse exception
793 public static void main(String[] args) throws ParseException {
794 String date = "20170110T112312Z";
795 SimpleDateFormat originalFormat = new SimpleDateFormat("yyyyMMdd'T'hhmmss'Z'");
796 Date toDate = originalFormat.parse(date);
797 SimpleDateFormat newFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss'Z'");
798 System.out.println(newFormat.format(toDate));