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.openecomp.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;
30 import java.nio.ByteBuffer;
31 import java.security.SecureRandom;
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.openecomp.cl.api.Logger;
54 import org.openecomp.sparky.logging.AaiUiMsgs;
55 import org.openecomp.sparky.viewandinspect.config.TierSupportUiConstants;
57 import com.fasterxml.jackson.core.JsonProcessingException;
58 import com.fasterxml.jackson.databind.JsonNode;
59 import com.fasterxml.jackson.databind.ObjectMapper;
60 import com.fasterxml.jackson.databind.ObjectWriter;
61 import com.fasterxml.jackson.databind.SerializationFeature;
62 import com.google.common.util.concurrent.ThreadFactoryBuilder;
66 * The Class NodeUtils.
68 public class NodeUtils {
69 private static SecureRandom sRandom = new SecureRandom();
71 public static synchronized String getRandomTxnId(){
72 byte bytes[] = new byte[6];
73 sRandom.nextBytes(bytes);
74 return Integer.toUnsignedString(ByteBuffer.wrap(bytes).getInt());
78 * Builds the depth padding.
80 * @param depth the depth
83 public static String buildDepthPadding(int depth) {
84 StringBuilder sb = new StringBuilder(32);
86 for (int x = 0; x < depth; x++) {
94 * Checks if is numeric.
96 * @param numberStr the number str
97 * @return true, if is numeric
99 public static boolean isNumeric(String numberStr) {
102 Double.parseDouble(numberStr);
103 } catch (Exception exc) {
112 * Creates the named executor.
114 * @param name the name
115 * @param numWorkers the num workers
116 * @param logger the logger
117 * @return the executor service
119 public static ExecutorService createNamedExecutor(String name, int numWorkers, final Logger logger) {
120 UncaughtExceptionHandler uncaughtExceptionHandler = new Thread.UncaughtExceptionHandler() {
123 public void uncaughtException(Thread thread, Throwable exc) {
125 logger.error(AaiUiMsgs.ERROR_GENERIC, thread.getName() + ": " + exc);
130 ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat(name + "-%d")
131 .setUncaughtExceptionHandler(uncaughtExceptionHandler).build();
133 return Executors.newScheduledThreadPool(numWorkers + 1, namedThreadFactory);
137 * Calculate edit attribute uri.
139 * @param link the link
142 public static String calculateEditAttributeUri(String link) {
147 Pattern pattern = Pattern.compile(TierSupportUiConstants.URI_VERSION_REGEX_PATTERN);
148 Matcher matcher = pattern.matcher(link);
149 if (matcher.find()) {
150 uri = link.substring(matcher.end());
157 * Generate unique sha digest.
159 * @param keys the keys
162 public static String generateUniqueShaDigest(String... keys) {
164 if ((keys == null) || keys.length == 0) {
168 final String keysStr = Arrays.asList(keys).toString();
169 final String hashedId = org.apache.commons.codec.digest.DigestUtils.sha256Hex(keysStr);
175 * Gets the node field as text.
177 * @param node the node
178 * @param fieldName the field name
179 * @return the node field as text
181 public static String getNodeFieldAsText(JsonNode node, String fieldName) {
183 String fieldValue = null;
185 JsonNode valueNode = node.get(fieldName);
187 if (valueNode != null) {
188 fieldValue = valueNode.asText();
194 private static final String ENTITY_RESOURCE_KEY_FORMAT = "%s.%s";
197 * Convert a millisecond duration to a string format
199 * @param millis A duration to convert to a string form
200 * @return A string of the form "X Days Y Hours Z Minutes A Seconds".
203 private static final String TIME_BREAK_DOWN_FORMAT =
204 "[ %d days, %d hours, %d minutes, %d seconds ]";
207 * Gets the duration breakdown.
209 * @param millis the millis
210 * @return the duration breakdown
212 public static String getDurationBreakdown(long millis) {
215 return String.format(TIME_BREAK_DOWN_FORMAT, 0, 0, 0, 0);
218 long days = TimeUnit.MILLISECONDS.toDays(millis);
219 millis -= TimeUnit.DAYS.toMillis(days);
220 long hours = TimeUnit.MILLISECONDS.toHours(millis);
221 millis -= TimeUnit.HOURS.toMillis(hours);
222 long minutes = TimeUnit.MILLISECONDS.toMinutes(millis);
223 millis -= TimeUnit.MINUTES.toMillis(minutes);
224 long seconds = TimeUnit.MILLISECONDS.toSeconds(millis);
226 return String.format(TIME_BREAK_DOWN_FORMAT, days, hours, minutes, seconds);
231 * Checks if is equal.
235 * @return true, if is equal
237 public static boolean isEqual(JsonNode n1, JsonNode n2) {
240 * due to the inherent nature of json being unordered, comparing object representations of the
241 * same keys and values but different order makes comparison challenging. Let's try an
242 * experiment where we compare the structure of the json, and then simply compare the sorted
243 * order of that structure which should be good enough for what we are trying to accomplish.
246 TreeWalker walker = new TreeWalker();
247 List<String> n1Paths = new ArrayList<String>();
248 List<String> n2Paths = new ArrayList<String>();
250 walker.walkTree(n1Paths, n1);
251 walker.walkTree(n2Paths, n2);
253 Collections.sort(n1Paths);
254 Collections.sort(n2Paths);
256 return n1Paths.equals(n2Paths);
263 * @param list the list
266 public static String concatArray(List<String> list) {
267 return concatArray(list, " ");
273 * @param list the list
274 * @param delimiter the delimiter
277 public static String concatArray(List<String> list, String delimiter) {
279 if (list == null || list.size() == 0) {
283 StringBuilder result = new StringBuilder(64);
285 boolean firstValue = true;
287 for (String item : list) {
293 result.append(delimiter).append(item);
298 return result.toString();
305 * @param values the values
308 public static String concatArray(String[] values) {
310 if (values == null || values.length == 0) {
314 StringBuilder result = new StringBuilder(64);
316 boolean firstValue = true;
318 for (String item : values) {
324 result.append(".").append(item);
329 return result.toString();
334 * Builds the entity resource key.
336 * @param entityType the entity type
337 * @param resourceId the resource id
340 public static String buildEntityResourceKey(String entityType, String resourceId) {
341 return String.format(ENTITY_RESOURCE_KEY_FORMAT, entityType, resourceId);
345 * Extract resource id from link.
347 * @param link the link
350 public static String extractResourceIdFromLink(String link) {
356 int linkLength = link.length();
357 if (linkLength == 0) {
362 * if the last character != / then we need to change the lastIndex position
366 String resourceId = null;
367 if ("/".equals(link.substring(linkLength - 1))) {
369 // https://<AAI-hostname>:9292/aai/v7/business/customers/customer/1607_20160524Func_Ak1_01/service-subscriptions/service-subscription/uCPE-VMS/
370 startIndex = link.lastIndexOf("/", linkLength - 2);
371 resourceId = link.substring(startIndex + 1, linkLength - 1);
374 // https://<AAI-Hostname>:9292/aai/v7/business/customers/customer/1607_20160524Func_Ak1_01/service-subscriptions/service-subscription/uCPE-VMS
375 startIndex = link.lastIndexOf("/");
376 resourceId = link.substring(startIndex + 1, linkLength);
379 String result = null;
381 if (resourceId != null) {
383 result = java.net.URLDecoder.decode(resourceId, "UTF-8");
384 } catch (Exception exc) {
386 * if there is a failure decoding the parameter we will just return the original value.
397 * Gets the xml stream constant as str.
399 * @param value the value
400 * @return the xml stream constant as str
402 public static String getXmlStreamConstantAsStr(int value) {
404 case XMLStreamConstants.ATTRIBUTE:
406 case XMLStreamConstants.CDATA:
408 case XMLStreamConstants.CHARACTERS:
410 case XMLStreamConstants.COMMENT:
412 case XMLStreamConstants.DTD:
414 case XMLStreamConstants.END_DOCUMENT:
415 return "END_DOCUMENT";
416 case XMLStreamConstants.END_ELEMENT:
417 return "END_ELEMENT";
418 case XMLStreamConstants.ENTITY_DECLARATION:
419 return "ENTITY_DECLARATION";
420 case XMLStreamConstants.ENTITY_REFERENCE:
421 return "ENTITY_REFERENCE";
422 case XMLStreamConstants.NAMESPACE:
424 case XMLStreamConstants.NOTATION_DECLARATION:
425 return "NOTATION_DECLARATION";
426 case XMLStreamConstants.PROCESSING_INSTRUCTION:
427 return "PROCESSING_INSTRUCTION";
428 case XMLStreamConstants.SPACE:
430 case XMLStreamConstants.START_DOCUMENT:
431 return "START_DOCUMENT";
432 case XMLStreamConstants.START_ELEMENT:
433 return "START_ELEMENT";
436 return "Unknown(" + value + ")";
441 * Convert object to json.
443 * @param object the object
444 * @param pretty the pretty
446 * @throws JsonProcessingException the json processing exception
448 public static String convertObjectToJson(Object object, boolean pretty)
449 throws JsonProcessingException {
450 ObjectWriter ow = null;
452 ObjectMapper mapper = new ObjectMapper();
453 mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
456 ow = mapper.writer().withDefaultPrettyPrinter();
459 ow = mapper.writer();
462 return ow.writeValueAsString(object);
466 * Convert json str to json node.
468 * @param jsonStr the json str
469 * @return the json node
470 * @throws IOException Signals that an I/O exception has occurred.
472 public static JsonNode convertJsonStrToJsonNode(String jsonStr) throws IOException {
473 ObjectMapper mapper = new ObjectMapper();
474 if (jsonStr == null || jsonStr.length() == 0) {
478 return mapper.readTree(jsonStr);
482 * Convert object to xml.
484 * @param object the object
486 * @throws JsonProcessingException the json processing exception
488 public static String convertObjectToXml(Object object) throws JsonProcessingException {
489 ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
490 String jsonOutput = ow.writeValueAsString(object);
492 if (jsonOutput == null) {
496 return JsonXmlConverter.convertJsontoXml(jsonOutput);
501 * Extract objects by key.
503 * @param node the node
504 * @param searchKey the search key
505 * @param foundObjects the found objects
507 public static void extractObjectsByKey(JsonNode node, String searchKey,
508 Collection<JsonNode> foundObjects) {
510 if ( node == null ) {
514 if (node.isObject()) {
515 Iterator<Map.Entry<String, JsonNode>> nodeIterator = node.fields();
517 while (nodeIterator.hasNext()) {
518 Map.Entry<String, JsonNode> entry = nodeIterator.next();
519 if (!entry.getValue().isValueNode()) {
520 extractObjectsByKey(entry.getValue(), searchKey, foundObjects);
523 String name = entry.getKey();
524 if (name.equalsIgnoreCase(searchKey)) {
526 JsonNode entryNode = entry.getValue();
528 if (entryNode.isArray()) {
530 Iterator<JsonNode> arrayItemsIterator = entryNode.elements();
531 while (arrayItemsIterator.hasNext()) {
532 foundObjects.add(arrayItemsIterator.next());
536 foundObjects.add(entry.getValue());
542 } else if (node.isArray()) {
543 Iterator<JsonNode> arrayItemsIterator = node.elements();
544 while (arrayItemsIterator.hasNext()) {
545 extractObjectsByKey(arrayItemsIterator.next(), searchKey, foundObjects);
553 * Convert array into list.
555 * @param node the node
556 * @param instances the instances
558 public static void convertArrayIntoList(JsonNode node, Collection<JsonNode> instances) {
560 if (node.isArray()) {
561 Iterator<JsonNode> arrayItemsIterator = node.elements();
562 while (arrayItemsIterator.hasNext()) {
563 instances.add(arrayItemsIterator.next());
573 * Extract field values from object.
575 * @param node the node
576 * @param attributesToExtract the attributes to extract
577 * @param fieldValues the field values
579 public static void extractFieldValuesFromObject(JsonNode node,
580 Collection<String> attributesToExtract, Collection<String> fieldValues) {
586 if (node.isObject()) {
588 JsonNode valueNode = null;
590 for (String attrToExtract : attributesToExtract) {
592 valueNode = node.get(attrToExtract);
594 if (valueNode != null) {
596 if (valueNode.isValueNode()) {
597 fieldValues.add(valueNode.asText());
605 * Extract field value from object.
607 * @param node the node
608 * @param fieldName the field name
611 public static String extractFieldValueFromObject(JsonNode node, String fieldName) {
617 if (node.isObject()) {
619 JsonNode valueNode = node.get(fieldName);
621 if (valueNode != null) {
623 if (valueNode.isValueNode()) {
624 return valueNode.asText();
636 * @param timestamp the timestamp
639 public static String formatTimestamp(String timestamp) {
641 SimpleDateFormat originalFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
642 originalFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
643 Date toDate = originalFormat.parse(timestamp);
644 SimpleDateFormat newFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
645 newFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
646 return newFormat.format(toDate);
648 } catch (ParseException pe) {
654 * Gets the HttpRequest payload.
656 * @param request the request
658 * @throws IOException Signals that an I/O exception has occurred.
660 public static String getBody(HttpServletRequest request) throws IOException {
663 StringBuilder stringBuilder = new StringBuilder();
664 BufferedReader bufferedReader = null;
667 InputStream inputStream = request.getInputStream();
668 if (inputStream != null) {
669 bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
670 char[] charBuffer = new char[128];
672 while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
673 stringBuilder.append(charBuffer, 0, bytesRead);
676 stringBuilder.append("");
678 } catch (IOException ex) {
681 if (bufferedReader != null) {
683 bufferedReader.close();
684 } catch (IOException ex) {
690 body = stringBuilder.toString();
697 * @param args the arguments
698 * @throws ParseException the parse exception
700 public static void main(String[] args) throws ParseException {
701 String date = "20170110T112312Z";
702 SimpleDateFormat originalFormat = new SimpleDateFormat("yyyyMMdd'T'hhmmss'Z'");
703 Date toDate = originalFormat.parse(date);
704 SimpleDateFormat newFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss'Z'");
705 System.out.println(newFormat.format(toDate));