d24a1532ee7a7b622801b29fa8e5ab5047f1cad8
[aai/data-router.git] / src / main / java / org / onap / aai / datarouter / util / RouterServiceUtil.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
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
11  *
12  *       http://www.apache.org/licenses/LICENSE-2.0
13  *
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=========================================================
20  */
21 package org.onap.aai.datarouter.util;
22
23 import com.fasterxml.jackson.databind.JsonNode;
24
25 import org.apache.camel.Exchange;
26 import org.apache.camel.component.cxf.common.message.CxfConstants;
27 import org.apache.cxf.message.Message;
28 import org.json.JSONObject;
29 import org.onap.aai.cl.mdc.MdcContext;
30 import org.onap.aai.restclient.client.Headers;
31
32 import java.util.ArrayList;
33 import java.util.Arrays;
34 import java.util.Collection;
35 import java.util.HashMap;
36 import java.util.Iterator;
37 import java.util.List;
38 import java.util.Map;
39 import java.util.UUID;
40
41 import javax.servlet.ServletRequest;
42
43 public class RouterServiceUtil {
44   
45   public static void setMdcContext(Exchange exchange){
46     String txnID = exchange.getIn().getHeader(Headers.TRANSACTION_ID, 
47         Arrays.asList(UUID.randomUUID())).toString();
48     String remote = exchange.getIn().getHeader(Headers.FROM_APP_ID, "").toString();
49     String remoteAddress = "";
50     Message cxfMessage = exchange.getIn().getHeader(CxfConstants.CAMEL_CXF_MESSAGE, Message.class);
51     if (cxfMessage != null) {
52       ServletRequest request = (ServletRequest) cxfMessage.get("HTTP.REQUEST");
53       if ( request != null)
54         remoteAddress = request.getRemoteAddr();
55     }
56     
57     MdcContext.initialize(txnID, "Synapse", "", remote, remoteAddress);
58   }
59
60   public static Map<String, String> parseJsonPayloadIntoMap(String jsonPayload) {
61
62     JSONObject jsonObject = new JSONObject(jsonPayload);
63     Map<String, String> map = new HashMap<>();
64     Iterator iter = jsonObject.keys();
65     while (iter.hasNext()) {
66       String key = (String) iter.next();
67       String value = jsonObject.getString(key);
68       map.put(key, value);
69     }
70     return map;
71   }
72
73   public static String getNodeFieldAsText(JsonNode node, String fieldName) {
74
75     String fieldValue = null;
76
77     JsonNode valueNode = node.get(fieldName);
78
79     if (valueNode != null) {
80       fieldValue = valueNode.asText();
81     }
82
83     return fieldValue;
84   }
85
86   public static String concatArray(List<String> list) {
87     return concatArray(list, " ");
88   }
89
90   public static String concatArray(List<String> list, String delimiter) {
91
92     if (list == null || !list.isEmpty()) {
93       return "";
94     }
95
96     StringBuilder result = new StringBuilder(64);
97
98     boolean firstValue = true;
99
100     for (String item : list) {
101
102       if (firstValue) {
103         result.append(item);
104         firstValue = false;
105       } else {
106         result.append(delimiter).append(item);
107       }
108     }
109
110     return result.toString();
111
112   }
113
114   public static String concatArray(String[] values) {
115
116     if (values == null || values.length == 0) {
117       return "";
118     }
119
120     StringBuilder result = new StringBuilder(64);
121
122     boolean firstValue = true;
123
124     for (String item : values) {
125
126       if (firstValue) {
127         result.append(item);
128         firstValue = false;
129       } else {
130         result.append(".").append(item);
131       }
132
133     }
134
135     return result.toString();
136
137   }
138
139   public static String recursivelyLookupJsonPayload(JsonNode node, String key) {
140     String value = null;
141     if (node.isObject()) {
142       Iterator<Map.Entry<String, JsonNode>> nodeIterator = node.fields();
143
144       while (nodeIterator.hasNext()) {
145         Map.Entry<String, JsonNode> entry = (Map.Entry<String, JsonNode>) nodeIterator.next();
146         if (!entry.getValue().isValueNode()) {
147           value = recursivelyLookupJsonPayload(entry.getValue(), key);
148           if (value != null) {
149             return value;
150           }
151         }
152
153         String name = entry.getKey();
154         if (name.equalsIgnoreCase(key)) {
155           return entry.getValue().asText();
156         }
157       }
158     } else if (node.isArray()) {
159       Iterator<JsonNode> arrayItemsIterator = node.elements();
160       while (arrayItemsIterator.hasNext()) {
161         value = recursivelyLookupJsonPayload(arrayItemsIterator.next(), key);
162         if (value != null) {
163           return value;
164         }
165       }
166     }
167     return value;
168   }
169
170   public static void extractObjectsByKey(JsonNode node, String searchKey,
171       Collection<JsonNode> foundObjects) {
172
173     if (node.isObject()) {
174       Iterator<Map.Entry<String, JsonNode>> nodeIterator = node.fields();
175
176       while (nodeIterator.hasNext()) {
177         Map.Entry<String, JsonNode> entry = (Map.Entry<String, JsonNode>) nodeIterator.next();
178         if (!entry.getValue().isValueNode()) {
179           extractObjectsByKey(entry.getValue(), searchKey, foundObjects);
180         }
181
182         String name = entry.getKey();
183         if (name.equalsIgnoreCase(searchKey)) {
184
185           JsonNode entryValue = entry.getValue();
186
187           if (entryValue.isArray()) {
188
189             Iterator<JsonNode> arrayItemsIterator = entryValue.elements();
190             while (arrayItemsIterator.hasNext()) {
191               foundObjects.add(arrayItemsIterator.next());
192             }
193
194           } else {
195             foundObjects.add(entry.getValue());
196           }
197         }
198       }
199     } else if (node.isArray()) {
200       Iterator<JsonNode> arrayItemsIterator = node.elements();
201       while (arrayItemsIterator.hasNext()) {
202         extractObjectsByKey(arrayItemsIterator.next(), searchKey, foundObjects);
203       }
204     }
205   }
206
207   public static void convertArrayIntoList(JsonNode node, Collection<JsonNode> instances) {
208
209     if (node.isArray()) {
210       Iterator<JsonNode> arrayItemsIterator = node.elements();
211       while (arrayItemsIterator.hasNext()) {
212         instances.add(arrayItemsIterator.next());
213       }
214     } else {
215       instances.add(node);
216     }
217   }
218
219   public static void extractFieldValuesFromObject(JsonNode node,
220       Collection<String> attributesToExtract, Collection<String> fieldValues) {
221
222     if (node.isObject()) {
223
224       JsonNode valueNode;
225
226       for (String attrToExtract : attributesToExtract) {
227
228         valueNode = node.get(attrToExtract);
229
230         if (valueNode != null) {
231
232           if (valueNode.isValueNode()) {
233             fieldValues.add(valueNode.asText());
234           }
235         }
236       }
237     }
238   }
239
240
241   public static String objToJson(Object obj) {
242     JSONObject jsonObject = new JSONObject(obj);
243     String json = jsonObject.toString();
244     return json;
245   }
246
247   /**
248    * Helper utility to concatenate substrings of a URI together to form a proper URI.
249    * 
250    * @param suburis the list of substrings to concatenate together
251    * @return the concatenated list of substrings
252    */
253   public static String concatSubUri(String... suburis) {
254     String finalUri = "";
255   
256     for (String suburi : suburis) {
257   
258       if (suburi != null) {
259         // Remove any leading / since we only want to append /
260         suburi = suburi.replaceFirst("^/*", "");
261   
262         // Add a trailing / if one isn't already there
263         finalUri += suburi.endsWith("/") ? suburi : suburi + "/";
264       }
265     }
266   
267     return finalUri;
268   }
269 }