2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.sdc.backend.ci.tests.utils.rest;
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;
47 import java.io.ByteArrayInputStream;
48 import java.io.IOException;
49 import java.io.InputStream;
50 import java.text.ParseException;
54 public class ResponseParser {
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";
64 static Logger logger = LogManager.getLogger(ResponseParser.class);
66 public static String getValueFromJsonResponse(String response, String fieldName) {
68 String[] split = fieldName.split(":");
69 String fieldValue = response;
71 for (int i = 0; i < split.length; i++) {
72 fieldValue = parser(fieldValue, split[i]);
75 } catch (Exception e) {
81 private static String parser(String response, String field) {
82 JSONObject fieldValue = (JSONObject) JSONValue.parse(response);
83 return fieldValue.get(field).toString();
86 public static String getUniqueIdFromResponse(RestResponse response) {
87 return getValueFromJsonResponse(response.getResponse(), UNIQUE_ID);
90 public static String getInvariantUuid(RestResponse response) {
91 return getValueFromJsonResponse(response.getResponse(), INVARIANT_UUID);
94 public static String getUuidFromResponse(RestResponse response) {
95 return getValueFromJsonResponse(response.getResponse(), UUID);
98 public static String getNameFromResponse(RestResponse response) {
99 return getValueFromJsonResponse(response.getResponse(), NAME);
102 public static String getVersionFromResponse(RestResponse response) {
103 return ResponseParser.getValueFromJsonResponse(response.getResponse(), VERSION);
106 public static String getComponentTypeFromResponse(RestResponse response) {
107 return ResponseParser.getValueFromJsonResponse(response.getResponse(), ORIGIN_TYPE);
110 public static String getToscaResourceNameFromResponse(RestResponse response) {
111 return getValueFromJsonResponse(response.getResponse(), TOSCA_RESOURCE_NAME);
114 @SuppressWarnings("unchecked")
115 public static ResourceRespJavaObject parseJsonListReturnResourceDetailsObj(RestResponse restResponse,
116 String resourceType, String searchPattern, String expectedResult) throws Exception {
118 // Gson gson = new Gson;
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();
127 for (int counter = 0; counter < arrayOfObjects.size(); counter++) {
128 JsonObject jHitObject = (JsonObject) arrayOfObjects.get(counter);
130 map = (Map<String, Object>) gson.fromJson(jHitObject.toString(), map.getClass());
131 if (map.get(searchPattern).toString().contains(expectedResult)) {
133 jsonToJavaObject = gson.fromJson(jObject, ResourceRespJavaObject.class);
137 return jsonToJavaObject;
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);
149 public static Resource convertResourceResponseToJavaObject(String response) {
150 ObjectMapper mapper = newObjectMapper();
151 Resource resource = null;
153 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
154 resource = mapper.readValue(response, Resource.class);
156 logger.debug(resource.toString());
157 } catch (IOException e) {
159 List<Resource> resources = Arrays.asList(mapper.readValue(response.toString(), Resource[].class));
160 resource = resources.get(0);
161 } catch (Exception e1) {
162 e1.printStackTrace();
169 public static ComponentInstanceProperty convertPropertyResponseToJavaObject(String response) {
171 ObjectMapper mapper = newObjectMapper();
172 ComponentInstanceProperty propertyDefinition = null;
174 propertyDefinition = mapper.readValue(response, ComponentInstanceProperty.class);
175 logger.debug(propertyDefinition.toString());
176 } catch (IOException e) {
179 return propertyDefinition;
182 public static GroupDefinition convertPropertyResponseToObject(String response) {
184 ObjectMapper mapper = newObjectMapper();
185 GroupDefinition groupDefinition = null;
187 groupDefinition = mapper.readValue(response, GroupDefinition.class);
188 logger.debug(groupDefinition.toString());
189 } catch (IOException e) {
192 return groupDefinition;
195 public static String toJson(Object object) {
196 Gson gson = new Gson();
197 return gson.toJson(object);
200 public static ArtifactDefinition convertArtifactDefinitionResponseToJavaObject(String response) {
201 ObjectMapper mapper = new ObjectMapper();
202 ArtifactDefinition artifactDefinition = null;
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) {
211 return artifactDefinition;
215 public static ArtifactReqDetails convertArtifactReqDetailsToJavaObject(String response) {
217 ArtifactReqDetails artifactReqDetails = null;
218 Gson gson = new Gson();
219 artifactReqDetails = gson.fromJson(response, ArtifactReqDetails.class);
220 return artifactReqDetails;
223 public static <T> T parseToObject(String json, Class<T> clazz) {
224 Gson gson = new Gson();
227 object = gson.fromJson(json, clazz);
228 } catch (Exception e) {
229 object = parseToObjectUsingMapper(json, clazz);
234 public static <T> T parseToObjectUsingMapper(String json, Class<T> clazz) {
236 ObjectMapper mapper = newObjectMapper();
239 object = mapper.readValue(json, clazz);
240 } catch (IOException e) {
247 public static ArtifactReqDetails convertArtifactDefinitionToArtifactReqDetailsObject(
248 ArtifactDefinition artifactDefinition) {
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;
257 public static Service convertServiceResponseToJavaObject(String response) {
259 ObjectMapper mapper = newObjectMapper();
260 Service service = null;
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);
269 } catch (IOException e) {
277 public static Product convertProductResponseToJavaObject(String response) {
279 ObjectMapper mapper = newObjectMapper();
280 Product product = null;
282 product = mapper.readValue(response, Product.class);
283 logger.debug(product.toString());
284 } catch (IOException e) {
291 public static ComponentInstance convertComponentInstanceResponseToJavaObject(String response) {
293 ObjectMapper mapper = newObjectMapper();
294 ComponentInstance componentInstance = null;
296 componentInstance = mapper.readValue(response, ComponentInstance.class);
297 logger.debug(componentInstance.toString());
298 } catch (IOException e) {
299 // TODO Auto-generated catch block
303 return componentInstance;
306 public static List<String> getValuesFromJsonArray(RestResponse message) throws Exception {
307 List<String> artifactTypesArrayFromApi = new ArrayList<>();
309 org.json.JSONObject responseObject = new org.json.JSONObject(message.getResponse());
310 JSONArray jArr = responseObject.getJSONArray("artifactTypes");
312 for (int i = 0; i < jArr.length(); i++) {
313 org.json.JSONObject jObj = jArr.getJSONObject(i);
314 String value = jObj.get("name").toString();
316 artifactTypesArrayFromApi.add(value);
318 return artifactTypesArrayFromApi;
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);
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;
338 public static List<Map<String, Object>> getAuditFromMessage(Map<String, Object> auditingMessage) {
339 List<Map<String, Object>> auditList = new ArrayList<>();
340 auditList.add(auditingMessage);
344 public static List<CategoryDefinition> parseCategories(RestResponse getAllCategoriesRest) {
346 List<CategoryDefinition> categories = new ArrayList<>();
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);
357 } catch (Exception e) {
364 public static JSONArray getListFromJson(RestResponse res, String field) throws JSONException {
365 String valueFromJsonResponse = getValueFromJsonResponse(res.getResponse(), field);
366 JSONArray jArr = new JSONArray(valueFromJsonResponse);
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));
381 public static Map<String, Object> convertStringToMap(String obj) {
382 Map<String, Object> object = (Map<String, Object>) JSONValue.parse(obj);
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);
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);
403 public static String getJsonObjectValueByKey(String metadata, String key) {
404 JsonElement jelement = new JsonParser().parse(metadata);
406 JsonObject jobject = jelement.getAsJsonObject();
407 Object obj = jobject.get(key);
411 return obj.toString();
415 public static Map<String, List<Component>> convertCatalogResponseToJavaObject(String response) {
416 Map<String, List<Component>> map = new HashMap<>();
418 JsonElement jElement = new JsonParser().parse(response);
419 JsonObject jObject = jElement.getAsJsonObject();
420 JsonArray jArrReousrces = jObject.getAsJsonArray("resources");
421 JsonArray jArrServices = jObject.getAsJsonArray("services");
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);
433 map.put("resources", restResponseArray);
435 ///////// SERVICE/////////////////////////////
437 restResponseArray = new ArrayList<>();
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);
445 map.put("services", restResponseArray);
448 map.put("resources", new ArrayList<>());
449 map.put("services", new ArrayList<>());
456 public static Map<Long, ServiceDistributionStatus> convertServiceDistributionStatusToObject(String response) throws ParseException {
458 Map<Long, ServiceDistributionStatus> serviceDistributionStatusMap = new HashMap<>();
459 ServiceDistributionStatus serviceDistributionStatusObject = null;
461 JsonElement jElement = new JsonParser().parse(response);
462 JsonObject jObject = jElement.getAsJsonObject();
463 JsonArray jDistrStatusArray = jObject.getAsJsonArray("distributionStatusOfServiceList");
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);
472 return serviceDistributionStatusMap;
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);
487 return propertiesMap;
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);
497 if (resourceName.contains(parsedResponse.getName()) && parsedResponse.getName().contains(resourceName)) {
498 return parsedResponse;
505 public static Map<String, VfModuleDefinition> convertVfModuleJsonResponseToJavaObject(String response) {
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();
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);
524 public static InterfaceDefinition convertInterfaceDefinitionResponseToJavaObject(String response) {
525 ObjectMapper mapper = new ObjectMapper();
526 InterfaceDefinition interfaceDefinition = null;
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) {
534 return interfaceDefinition;