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