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.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;
47 import java.io.ByteArrayInputStream;
48 import java.io.IOException;
49 import java.io.InputStream;
50 import java.text.ParseException;
53 public class ResponseParser {
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";
63 static Logger logger = LoggerFactory.getLogger(ResponseParser.class);
65 public static String getValueFromJsonResponse(String response, String fieldName) {
67 String[] split = fieldName.split(":");
68 String fieldValue = response;
70 for (int i = 0; i < split.length; i++) {
71 fieldValue = parser(fieldValue, split[i]);
74 } catch (Exception e) {
80 private static String parser(String response, String field) {
81 JSONObject fieldValue = (JSONObject) JSONValue.parse(response);
82 return fieldValue.get(field).toString();
85 public static String getUniqueIdFromResponse(RestResponse response) {
86 return getValueFromJsonResponse(response.getResponse(), UNIQUE_ID);
89 public static String getInvariantUuid(RestResponse response) {
90 return getValueFromJsonResponse(response.getResponse(), INVARIANT_UUID);
93 public static String getUuidFromResponse(RestResponse response) {
94 return getValueFromJsonResponse(response.getResponse(), UUID);
97 public static String getNameFromResponse(RestResponse response) {
98 return getValueFromJsonResponse(response.getResponse(), NAME);
101 public static String getVersionFromResponse(RestResponse response) {
102 return ResponseParser.getValueFromJsonResponse(response.getResponse(), VERSION);
105 public static String getComponentTypeFromResponse(RestResponse response) {
106 return ResponseParser.getValueFromJsonResponse(response.getResponse(), ORIGIN_TYPE);
109 public static String getToscaResourceNameFromResponse(RestResponse response) {
110 return getValueFromJsonResponse(response.getResponse(), TOSCA_RESOURCE_NAME);
113 @SuppressWarnings("unchecked")
114 public static ResourceRespJavaObject parseJsonListReturnResourceDetailsObj(RestResponse restResponse,
115 String resourceType, String searchPattern, String expectedResult) throws Exception {
117 // Gson gson = new Gson;
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();
126 for (int counter = 0; counter < arrayOfObjects.size(); counter++) {
127 JsonObject jHitObject = (JsonObject) arrayOfObjects.get(counter);
129 map = (Map<String, Object>) gson.fromJson(jHitObject.toString(), map.getClass());
130 if (map.get(searchPattern).toString().contains(expectedResult)) {
132 jsonToJavaObject = gson.fromJson(jObject, ResourceRespJavaObject.class);
136 return jsonToJavaObject;
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);
148 public static Resource convertResourceResponseToJavaObject(String response) {
149 ObjectMapper mapper = newObjectMapper();
150 Resource resource = null;
152 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
153 resource = mapper.readValue(response, Resource.class);
155 logger.debug(resource.toString());
156 } catch (IOException e) {
158 List<Resource> resources = Arrays.asList(mapper.readValue(response.toString(), Resource[].class));
159 resource = resources.get(0);
160 } catch (Exception e1) {
161 e1.printStackTrace();
168 public static ComponentInstanceProperty convertPropertyResponseToJavaObject(String response) {
170 ObjectMapper mapper = newObjectMapper();
171 ComponentInstanceProperty propertyDefinition = null;
173 propertyDefinition = mapper.readValue(response, ComponentInstanceProperty.class);
174 logger.debug(propertyDefinition.toString());
175 } catch (IOException e) {
178 return propertyDefinition;
181 public static GroupDefinition convertPropertyResponseToObject(String response) {
183 ObjectMapper mapper = newObjectMapper();
184 GroupDefinition groupDefinition = null;
186 groupDefinition = mapper.readValue(response, GroupDefinition.class);
187 logger.debug(groupDefinition.toString());
188 } catch (IOException e) {
191 return groupDefinition;
194 public static String toJson(Object object) {
195 Gson gson = new Gson();
196 return gson.toJson(object);
199 public static ArtifactDefinition convertArtifactDefinitionResponseToJavaObject(String response) {
200 ObjectMapper mapper = new ObjectMapper();
201 ArtifactDefinition artifactDefinition = null;
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) {
210 return artifactDefinition;
214 public static ArtifactReqDetails convertArtifactReqDetailsToJavaObject(String response) {
216 ArtifactReqDetails artifactReqDetails = null;
217 Gson gson = new Gson();
218 artifactReqDetails = gson.fromJson(response, ArtifactReqDetails.class);
219 return artifactReqDetails;
222 public static <T> T parseToObject(String json, Class<T> clazz) {
223 Gson gson = new Gson();
226 object = gson.fromJson(json, clazz);
227 } catch (Exception e) {
228 object = parseToObjectUsingMapper(json, clazz);
233 public static <T> T parseToObjectUsingMapper(String json, Class<T> clazz) {
235 ObjectMapper mapper = newObjectMapper();
238 object = mapper.readValue(json, clazz);
239 } catch (IOException e) {
246 public static ArtifactReqDetails convertArtifactDefinitionToArtifactReqDetailsObject(
247 ArtifactDefinition artifactDefinition) {
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;
256 public static Service convertServiceResponseToJavaObject(String response) {
258 ObjectMapper mapper = newObjectMapper();
259 Service service = null;
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);
268 } catch (IOException e) {
276 public static Product convertProductResponseToJavaObject(String response) {
278 ObjectMapper mapper = newObjectMapper();
279 Product product = null;
281 product = mapper.readValue(response, Product.class);
282 logger.debug(product.toString());
283 } catch (IOException e) {
290 public static ComponentInstance convertComponentInstanceResponseToJavaObject(String response) {
292 ObjectMapper mapper = newObjectMapper();
293 ComponentInstance componentInstance = null;
295 componentInstance = mapper.readValue(response, ComponentInstance.class);
296 logger.debug(componentInstance.toString());
297 } catch (IOException e) {
298 // TODO Auto-generated catch block
302 return componentInstance;
305 public static List<String> getValuesFromJsonArray(RestResponse message) throws Exception {
306 List<String> artifactTypesArrayFromApi = new ArrayList<>();
308 org.json.JSONObject responseObject = new org.json.JSONObject(message.getResponse());
309 JSONArray jArr = responseObject.getJSONArray("artifactTypes");
311 for (int i = 0; i < jArr.length(); i++) {
312 org.json.JSONObject jObj = jArr.getJSONObject(i);
313 String value = jObj.get("name").toString();
315 artifactTypesArrayFromApi.add(value);
317 return artifactTypesArrayFromApi;
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);
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;
337 public static List<Map<String, Object>> getAuditFromMessage(Map<String, Object> auditingMessage) {
338 List<Map<String, Object>> auditList = new ArrayList<>();
339 auditList.add(auditingMessage);
343 public static List<CategoryDefinition> parseCategories(RestResponse getAllCategoriesRest) {
345 List<CategoryDefinition> categories = new ArrayList<>();
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);
356 } catch (Exception e) {
363 public static JSONArray getListFromJson(RestResponse res, String field) throws JSONException {
364 String valueFromJsonResponse = getValueFromJsonResponse(res.getResponse(), field);
365 JSONArray jArr = new JSONArray(valueFromJsonResponse);
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));
380 public static Map<String, Object> convertStringToMap(String obj) {
381 Map<String, Object> object = (Map<String, Object>) JSONValue.parse(obj);
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);
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);
402 public static String getJsonObjectValueByKey(String metadata, String key) {
403 JsonElement jelement = new JsonParser().parse(metadata);
405 JsonObject jobject = jelement.getAsJsonObject();
406 Object obj = jobject.get(key);
410 return obj.toString();
414 public static Map<String, List<Component>> convertCatalogResponseToJavaObject(String response) {
415 Map<String, List<Component>> map = new HashMap<>();
417 JsonElement jElement = new JsonParser().parse(response);
418 JsonObject jObject = jElement.getAsJsonObject();
419 JsonArray jArrReousrces = jObject.getAsJsonArray("resources");
420 JsonArray jArrServices = jObject.getAsJsonArray("services");
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);
432 map.put("resources", restResponseArray);
434 ///////// SERVICE/////////////////////////////
436 restResponseArray = new ArrayList<>();
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);
444 map.put("services", restResponseArray);
447 map.put("resources", new ArrayList<>());
448 map.put("services", new ArrayList<>());
455 public static Map<Long, ServiceDistributionStatus> convertServiceDistributionStatusToObject(String response) throws ParseException {
457 Map<Long, ServiceDistributionStatus> serviceDistributionStatusMap = new HashMap<>();
458 ServiceDistributionStatus serviceDistributionStatusObject = null;
460 JsonElement jElement = new JsonParser().parse(response);
461 JsonObject jObject = jElement.getAsJsonObject();
462 JsonArray jDistrStatusArray = jObject.getAsJsonArray("distributionStatusOfServiceList");
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);
471 return serviceDistributionStatusMap;
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);
486 return propertiesMap;
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);
496 if (resourceName.contains(parsedResponse.getName()) && parsedResponse.getName().contains(resourceName)) {
497 return parsedResponse;
504 public static Map<String, VfModuleDefinition> convertVfModuleJsonResponseToJavaObject(String response) {
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();
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);
523 public static InterfaceDefinition convertInterfaceDefinitionResponseToJavaObject(String response) {
524 ObjectMapper mapper = new ObjectMapper();
525 InterfaceDefinition interfaceDefinition = null;
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);
533 return interfaceDefinition;