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