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