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