Remove vulnerable dependency
[sdc.git] / integration-tests / src / test / java / org / onap / sdc / backend / ci / tests / utils / rest / ResponseParser.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.sdc.backend.ci.tests.utils.rest;
22
23 import com.fasterxml.jackson.databind.DeserializationFeature;
24 import com.fasterxml.jackson.databind.ObjectMapper;
25 import com.fasterxml.jackson.databind.exc.InvalidFormatException;
26 import com.fasterxml.jackson.databind.module.SimpleModule;
27 import com.google.gson.*;
28 import org.apache.commons.codec.binary.Base64;
29 import org.openecomp.sdc.logging.api.Logger;
30 import org.openecomp.sdc.logging.api.LoggerFactory;
31 import org.json.JSONArray;
32 import org.json.JSONException;
33 import org.json.simple.JSONObject;
34 import org.json.simple.JSONValue;
35 import org.onap.sdc.backend.ci.tests.datatypes.http.RestResponse;
36 import org.openecomp.sdc.be.model.*;
37 import org.openecomp.sdc.be.model.category.CategoryDefinition;
38 import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
39 import org.onap.sdc.backend.ci.tests.datatypes.ArtifactReqDetails;
40 import org.onap.sdc.backend.ci.tests.datatypes.ResourceAssetStructure;
41 import org.onap.sdc.backend.ci.tests.datatypes.ResourceRespJavaObject;
42 import org.onap.sdc.backend.ci.tests.datatypes.ServiceDistributionStatus;
43 import org.onap.sdc.backend.ci.tests.tosca.datatypes.VfModuleDefinition;
44 import org.onap.sdc.backend.ci.tests.utils.Utils;
45 import org.yaml.snakeyaml.Yaml;
46
47 import java.io.ByteArrayInputStream;
48 import java.io.IOException;
49 import java.io.InputStream;
50 import java.text.ParseException;
51 import java.util.*;
52
53 public class ResponseParser {
54
55     private static final String INVARIANT_UUID = "invariantUUID";
56     public static final String UNIQUE_ID = "uniqueId";
57     public static final String VERSION = "version";
58     public static final String UUID = "uuid";
59     public static final String NAME = "name";
60     public static final String ORIGIN_TYPE = "originType";
61     public static final String TOSCA_RESOURCE_NAME = "toscaResourceName";
62
63     static Logger logger = LoggerFactory.getLogger(ResponseParser.class);
64
65     public static String getValueFromJsonResponse(String response, String fieldName) {
66         try {
67             String[] split = fieldName.split(":");
68             String fieldValue = response;
69
70             for (int i = 0; i < split.length; i++) {
71                 fieldValue = parser(fieldValue, split[i]);
72             }
73             return fieldValue;
74         } catch (Exception e) {
75             return null;
76         }
77
78     }
79
80     private static String parser(String response, String field) {
81         JSONObject fieldValue = (JSONObject) JSONValue.parse(response);
82         return fieldValue.get(field).toString();
83     }
84
85     public static String getUniqueIdFromResponse(RestResponse response) {
86         return getValueFromJsonResponse(response.getResponse(), UNIQUE_ID);
87     }
88
89     public static String getInvariantUuid(RestResponse response) {
90         return getValueFromJsonResponse(response.getResponse(), INVARIANT_UUID);
91     }
92
93     public static String getUuidFromResponse(RestResponse response) {
94         return getValueFromJsonResponse(response.getResponse(), UUID);
95     }
96
97     public static String getNameFromResponse(RestResponse response) {
98         return getValueFromJsonResponse(response.getResponse(), NAME);
99     }
100
101     public static String getVersionFromResponse(RestResponse response) {
102         return ResponseParser.getValueFromJsonResponse(response.getResponse(), VERSION);
103     }
104
105     public static String getComponentTypeFromResponse(RestResponse response) {
106         return ResponseParser.getValueFromJsonResponse(response.getResponse(), ORIGIN_TYPE);
107     }
108
109     public static String getToscaResourceNameFromResponse(RestResponse response) {
110         return getValueFromJsonResponse(response.getResponse(), TOSCA_RESOURCE_NAME);
111     }
112
113     @SuppressWarnings("unchecked")
114     public static ResourceRespJavaObject parseJsonListReturnResourceDetailsObj(RestResponse restResponse,
115                                                                                String resourceType, String searchPattern, String expectedResult) throws Exception {
116
117         // Gson gson = new Gson;
118
119         JsonElement jElement = new JsonParser().parse(restResponse.getResponse());
120         JsonObject jObject = jElement.getAsJsonObject();
121         JsonArray arrayOfObjects = (JsonArray) jObject.get(resourceType);
122         Gson gson = new Gson();
123         Map<String, Object> map = new HashMap<>();
124         ResourceRespJavaObject jsonToJavaObject = new ResourceRespJavaObject();
125
126         for (int counter = 0; counter < arrayOfObjects.size(); counter++) {
127             JsonObject jHitObject = (JsonObject) arrayOfObjects.get(counter);
128
129             map = (Map<String, Object>) gson.fromJson(jHitObject.toString(), map.getClass());
130             if (map.get(searchPattern).toString().contains(expectedResult)) {
131
132                 jsonToJavaObject = gson.fromJson(jObject, ResourceRespJavaObject.class);
133                 break;
134             }
135         }
136         return jsonToJavaObject;
137
138     }
139
140     private static ObjectMapper newObjectMapper() {
141         SimpleModule module = new SimpleModule("customDeserializationModule");
142         module.addDeserializer(PropertyConstraint.class, new PropertyOperation.PropertyConstraintJacksonDeserializer());
143         return new ObjectMapper()
144                 .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
145                 .registerModule(module);
146     }
147
148     public static Resource convertResourceResponseToJavaObject(String response) {
149         ObjectMapper mapper = newObjectMapper();
150         Resource resource = null;
151         try {
152             mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
153             resource = mapper.readValue(response, Resource.class);
154
155             logger.debug(resource.toString());
156         } catch (IOException e) {
157             try {
158                 List<Resource> resources = Arrays.asList(mapper.readValue(response.toString(), Resource[].class));
159                 resource = resources.get(0);
160             } catch (Exception e1) {
161                 e1.printStackTrace();
162             }
163         }
164
165         return resource;
166     }
167
168     public static ComponentInstanceProperty convertPropertyResponseToJavaObject(String response) {
169
170         ObjectMapper mapper = newObjectMapper();
171         ComponentInstanceProperty propertyDefinition = null;
172         try {
173             propertyDefinition = mapper.readValue(response, ComponentInstanceProperty.class);
174             logger.debug(propertyDefinition.toString());
175         } catch (IOException e) {
176             e.printStackTrace();
177         }
178         return propertyDefinition;
179     }
180
181     public static GroupDefinition convertPropertyResponseToObject(String response) {
182
183         ObjectMapper mapper = newObjectMapper();
184         GroupDefinition groupDefinition = null;
185         try {
186             groupDefinition = mapper.readValue(response, GroupDefinition.class);
187             logger.debug(groupDefinition.toString());
188         } catch (IOException e) {
189             e.printStackTrace();
190         }
191         return groupDefinition;
192     }
193
194     public static String toJson(Object object) {
195         Gson gson = new Gson();
196         return gson.toJson(object);
197     }
198
199     public static ArtifactDefinition convertArtifactDefinitionResponseToJavaObject(String response) {
200         ObjectMapper mapper = new ObjectMapper();
201         ArtifactDefinition artifactDefinition = null;
202         try {
203             mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
204             artifactDefinition = mapper.readValue(response, ArtifactDefinition.class);
205             logger.debug(artifactDefinition.toString());
206         } catch (IOException e) {
207             e.printStackTrace();
208         }
209
210         return artifactDefinition;
211
212     }
213
214     public static ArtifactReqDetails convertArtifactReqDetailsToJavaObject(String response) {
215
216         ArtifactReqDetails artifactReqDetails = null;
217         Gson gson = new Gson();
218         artifactReqDetails = gson.fromJson(response, ArtifactReqDetails.class);
219         return artifactReqDetails;
220     }
221
222     public static <T> T parseToObject(String json, Class<T> clazz) {
223         Gson gson = new Gson();
224         T object;
225         try {
226             object = gson.fromJson(json, clazz);
227         } catch (Exception e) {
228             object = parseToObjectUsingMapper(json, clazz);
229         }
230         return object;
231     }
232
233     public static <T> T parseToObjectUsingMapper(String json, Class<T> clazz) {
234         // Generic convert
235         ObjectMapper mapper = newObjectMapper();
236         T object = null;
237         try {
238             object = mapper.readValue(json, clazz);
239         } catch (IOException e) {
240             e.printStackTrace();
241         }
242
243         return object;
244     }
245
246     public static ArtifactReqDetails convertArtifactDefinitionToArtifactReqDetailsObject(
247             ArtifactDefinition artifactDefinition) {
248
249         ArtifactReqDetails artifactReqDetails = null;
250         Gson gson = new Gson();
251         String artDef = gson.toJson(artifactDefinition);
252         artifactReqDetails = gson.fromJson(artDef, ArtifactReqDetails.class);
253         return artifactReqDetails;
254     }
255
256     public static Service convertServiceResponseToJavaObject(String response) {
257
258         ObjectMapper mapper = newObjectMapper();
259         Service service = null;
260         try {
261             service = mapper.readValue(response, Service.class);
262             logger.debug(service.toString());
263             //Temporary catch until bug with distribution status fixed
264         } catch (InvalidFormatException e) {
265             System.out.println("broken service with invalid distribution status : " + response);
266             logger.debug("broken service with invalid distribution status : " + response);
267             return service;
268         } catch (IOException e) {
269
270             e.printStackTrace();
271         }
272
273         return service;
274     }
275
276     public static Product convertProductResponseToJavaObject(String response) {
277
278         ObjectMapper mapper = newObjectMapper();
279         Product product = null;
280         try {
281             product = mapper.readValue(response, Product.class);
282             logger.debug(product.toString());
283         } catch (IOException e) {
284             e.printStackTrace();
285         }
286
287         return product;
288     }
289
290     public static ComponentInstance convertComponentInstanceResponseToJavaObject(String response) {
291
292         ObjectMapper mapper = newObjectMapper();
293         ComponentInstance componentInstance = null;
294         try {
295             componentInstance = mapper.readValue(response, ComponentInstance.class);
296             logger.debug(componentInstance.toString());
297         } catch (IOException e) {
298             // TODO Auto-generated catch block
299             e.printStackTrace();
300         }
301
302         return componentInstance;
303     }
304
305     public static List<String> getValuesFromJsonArray(RestResponse message) throws Exception {
306         List<String> artifactTypesArrayFromApi = new ArrayList<>();
307
308         org.json.JSONObject responseObject = new org.json.JSONObject(message.getResponse());
309         JSONArray jArr = responseObject.getJSONArray("artifactTypes");
310
311         for (int i = 0; i < jArr.length(); i++) {
312             org.json.JSONObject jObj = jArr.getJSONObject(i);
313             String value = jObj.get("name").toString();
314
315             artifactTypesArrayFromApi.add(value);
316         }
317         return artifactTypesArrayFromApi;
318     }
319
320     public static String calculateMD5Header(ArtifactReqDetails artifactDetails) {
321         Gson gson = new Gson();
322         String jsonBody = gson.toJson(artifactDetails);
323         // calculate MD5 for json body
324         return calculateMD5(jsonBody);
325
326     }
327
328     public static String calculateMD5(String data) {
329         String calculatedMd5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(data);
330         // encode base-64 result
331         byte[] encodeBase64 = Base64.encodeBase64(calculatedMd5.getBytes());
332         String encodeBase64Str = new String(encodeBase64);
333         return encodeBase64Str;
334
335     }
336
337     public static List<Map<String, Object>> getAuditFromMessage(Map<String, Object> auditingMessage) {
338         List<Map<String, Object>> auditList = new ArrayList<>();
339         auditList.add(auditingMessage);
340         return auditList;
341     }
342
343     public static List<CategoryDefinition> parseCategories(RestResponse getAllCategoriesRest) {
344
345         List<CategoryDefinition> categories = new ArrayList<>();
346         try {
347             JsonElement jElement = new JsonParser().parse(getAllCategoriesRest.getResponse());
348             JsonArray cagegories = jElement.getAsJsonArray();
349             Iterator<JsonElement> iter = cagegories.iterator();
350             while (iter.hasNext()) {
351                 JsonElement next = iter.next();
352                 CategoryDefinition category = ResponseParser.parseToObject(next.toString(), CategoryDefinition.class);
353                 categories.add(category);
354             }
355
356         } catch (Exception e) {
357             e.printStackTrace();
358         }
359
360         return categories;
361     }
362
363     public static JSONArray getListFromJson(RestResponse res, String field) throws JSONException {
364         String valueFromJsonResponse = getValueFromJsonResponse(res.getResponse(), field);
365         JSONArray jArr = new JSONArray(valueFromJsonResponse);
366
367         return jArr;
368     }
369
370     public static List<String> getDerivedListFromJson(RestResponse res) throws JSONException {
371         JSONArray listFromJson = getListFromJson(res, "derivedFrom");
372         List<String> lst = new ArrayList<>();
373         for (int i = 0; i < listFromJson.length(); i++) {
374             lst.add(listFromJson.getString(i));
375         }
376
377         return lst;
378     }
379
380     public static Map<String, Object> convertStringToMap(String obj) {
381         Map<String, Object> object = (Map<String, Object>) JSONValue.parse(obj);
382         return object;
383     }
384
385     public static List<Map<String, Object>> getListOfMapsFromJson(RestResponse res, String field) throws Exception {
386         List<Map<String, Object>> list = new ArrayList<>();
387         JSONArray listFromJson = getListFromJson(res, field);
388         for (int i = 0; i < listFromJson.length(); i++) {
389             Map<String, Object> convertStringToMap = convertStringToMap(listFromJson.getString(i));
390             list.add(convertStringToMap);
391         }
392         return list;
393
394     }
395
396     public static Map<String, Object> getJsonValueAsMap(RestResponse response, String key) {
397         String valueField = getValueFromJsonResponse(response.getResponse(), key);
398         Map<String, Object> convertToMap = convertStringToMap(valueField);
399         return convertToMap;
400     }
401
402     public static String getJsonObjectValueByKey(String metadata, String key) {
403         JsonElement jelement = new JsonParser().parse(metadata);
404
405         JsonObject jobject = jelement.getAsJsonObject();
406         Object obj = jobject.get(key);
407         if (obj == null) {
408             return null;
409         } else {
410             return obj.toString();
411         }
412     }
413
414     public static Map<String, List<Component>> convertCatalogResponseToJavaObject(String response) {
415         Map<String, List<Component>> map = new HashMap<>();
416
417         JsonElement jElement = new JsonParser().parse(response);
418         JsonObject jObject = jElement.getAsJsonObject();
419         JsonArray jArrReousrces = jObject.getAsJsonArray("resources");
420         JsonArray jArrServices = jObject.getAsJsonArray("services");
421
422         if (jArrReousrces != null && jArrServices != null) {
423             //////// RESOURCE/////////////////////////////
424             ArrayList<Component> restResponseArray = new ArrayList<>();
425             Component component = null;
426             for (int i = 0; i < jArrReousrces.size(); i++) {
427                 String resourceString = (String) jArrReousrces.get(i).toString();
428                 component = ResponseParser.convertResourceResponseToJavaObject(resourceString);
429                 restResponseArray.add(component);
430             }
431
432             map.put("resources", restResponseArray);
433
434             ///////// SERVICE/////////////////////////////
435
436             restResponseArray = new ArrayList<>();
437             component = null;
438             for (int i = 0; i < jArrServices.size(); i++) {
439                 String resourceString = (String) jArrServices.get(i).toString();
440                 component = ResponseParser.convertServiceResponseToJavaObject(resourceString);
441                 restResponseArray.add(component);
442             }
443
444             map.put("services", restResponseArray);
445
446         } else {
447             map.put("resources", new ArrayList<>());
448             map.put("services", new ArrayList<>());
449         }
450
451         return map;
452
453     }
454
455     public static Map<Long, ServiceDistributionStatus> convertServiceDistributionStatusToObject(String response) throws ParseException {
456
457         Map<Long, ServiceDistributionStatus> serviceDistributionStatusMap = new HashMap<>();
458         ServiceDistributionStatus serviceDistributionStatusObject = null;
459
460         JsonElement jElement = new JsonParser().parse(response);
461         JsonObject jObject = jElement.getAsJsonObject();
462         JsonArray jDistrStatusArray = jObject.getAsJsonArray("distributionStatusOfServiceList");
463
464         for (int i = 0; i < jDistrStatusArray.size(); i++) {
465             Gson gson = new Gson();
466             String servDistrStatus = gson.toJson(jDistrStatusArray.get(i));
467             serviceDistributionStatusObject = gson.fromJson(servDistrStatus, ServiceDistributionStatus.class);
468             serviceDistributionStatusMap.put(Utils.getEpochTimeFromUTC(serviceDistributionStatusObject.getTimestamp()), serviceDistributionStatusObject);
469         }
470
471         return serviceDistributionStatusMap;
472
473     }
474
475     public static Map<String, String> getPropertiesNameType(RestResponse restResponse)
476             throws JSONException {
477         Map<String, String> propertiesMap = new HashMap<>();
478         JSONArray propertiesList = getListFromJson(restResponse, "properties");
479         for (int i = 0; i < propertiesList.length(); i++) {
480             JSONObject prop = (JSONObject) JSONValue.parse(propertiesList.get(i).toString());
481             String propName = prop.get("name").toString();
482             String propType = prop.get("type").toString();
483             propertiesMap.put(propName, propType);
484         }
485
486         return propertiesMap;
487     }
488
489     public static ResourceAssetStructure getDataOutOfSearchExternalAPIResponseForResourceName(String response, String resourceName) {
490         Gson gson = new Gson();
491         JsonElement jsonElement = new JsonParser().parse(response);
492         JsonArray jsonArray = jsonElement.getAsJsonArray();
493         for (JsonElement jElement : jsonArray) {
494             ResourceAssetStructure parsedResponse = gson.fromJson(jElement, ResourceAssetStructure.class);
495
496             if (resourceName.contains(parsedResponse.getName()) && parsedResponse.getName().contains(resourceName)) {
497                 return parsedResponse;
498             }
499         }
500
501         return null;
502     }
503
504     public static Map<String, VfModuleDefinition> convertVfModuleJsonResponseToJavaObject(String response) {
505
506         Yaml yaml = new Yaml();
507         InputStream inputStream = null;
508         inputStream = new ByteArrayInputStream(response.getBytes());
509         List<?> list = (List<?>) yaml.load(inputStream);
510         ObjectMapper mapper = new ObjectMapper();
511
512         VfModuleDefinition moduleDefinition;
513         Map<String, VfModuleDefinition> vfModulesMap = new HashMap<>();
514         for (Object obj : list) {
515 //                      TODO Andrey L. uncomment line below in case to ignore on unknown properties, not recommended
516             mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
517             moduleDefinition = mapper.convertValue(obj, VfModuleDefinition.class);
518             vfModulesMap.put(moduleDefinition.vfModuleModelName, moduleDefinition);
519         }
520         return vfModulesMap;
521     }
522
523     public static InterfaceDefinition convertInterfaceDefinitionResponseToJavaObject(String response) {
524         ObjectMapper mapper = new ObjectMapper();
525         InterfaceDefinition interfaceDefinition = null;
526         try {
527             mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
528             interfaceDefinition = mapper.readValue(response, InterfaceDefinition.class);
529             logger.debug(interfaceDefinition.toString());
530         } catch (IOException e) {
531             logger.debug("Failed to convertInterfaceDefinitionResponseToJavaObject", e);
532         }
533         return interfaceDefinition;
534     }
535
536 }