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.openecomp.sdc.ci.tests.utils.rest;
23 import com.fasterxml.jackson.databind.DeserializationFeature;
24 import com.fasterxml.jackson.databind.ObjectMapper;
25 import com.fasterxml.jackson.databind.module.SimpleModule;
26 import com.google.gson.Gson;
27 import com.google.gson.JsonArray;
28 import com.google.gson.JsonElement;
29 import com.google.gson.JsonObject;
30 import com.google.gson.JsonParser;
31 import org.apache.commons.codec.binary.Base64;
32 import org.apache.log4j.Logger;
33 import org.json.JSONArray;
34 import org.json.JSONException;
35 import org.json.simple.JSONObject;
36 import org.json.simple.JSONValue;
37 import org.openecomp.sdc.be.model.ArtifactDefinition;
38 import org.openecomp.sdc.be.model.Component;
39 import org.openecomp.sdc.be.model.ComponentInstance;
40 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
41 import org.openecomp.sdc.be.model.GroupDefinition;
42 import org.openecomp.sdc.be.model.Product;
43 import org.openecomp.sdc.be.model.PropertyConstraint;
44 import org.openecomp.sdc.be.model.Resource;
45 import org.openecomp.sdc.be.model.Service;
46 import org.openecomp.sdc.be.model.category.CategoryDefinition;
47 import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintJacksonDeserializer;
48 import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
49 import org.openecomp.sdc.ci.tests.datatypes.ResourceAssetStructure;
50 import org.openecomp.sdc.ci.tests.datatypes.ResourceRespJavaObject;
51 import org.openecomp.sdc.ci.tests.datatypes.ServiceDistributionStatus;
52 import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
53 import org.openecomp.sdc.ci.tests.utils.Utils;
55 import java.io.IOException;
56 import java.text.ParseException;
57 import java.util.ArrayList;
58 import java.util.Arrays;
59 import java.util.HashMap;
60 import java.util.Iterator;
61 import java.util.List;
63 import java.util.List;
66 public class ResponseParser {
68 // comment by Andrey, for test only
69 // public static void main(String[] args) {
71 // "{\"uniqueId\":\"52eb0139-a855-47b9-a0e6-c90f0a90b1d2\",\"resourceName\":\"importResource4test\",\"resourceVersion\":\"0.1\",\"creatorUserId\":\"jh0003\",\"creatorFullName\":\"Jimmy
72 // Hendrix\",\"lastUpdaterUserId\":\"jh0003\",\"lastUpdaterFullName\":\"Jimmy
73 // Hendrix\",\"creationDate\":1446742241514,\"lastUpdateDate\":1446742241514,\"description\":\"Represents
74 // a generic software component that can be managed and run by a Compute
76 // Type.\",\"icon\":\"defaulticon\",\"tags\":[\"importResource4test\"],\"category\":\"Generic/Infrastructure\",\"lifecycleState\":\"NOT_CERTIFIED_CHECKOUT\",\"derivedFrom\":[\"tosca.nodes.Root\"],\"artifacts\":{},\"deploymentArtifacts\":{},\"properties\":[{\"uniqueId\":\"52eb0139-a855-47b9-a0e6-c90f0a90b1d2.port\",\"type\":\"integer\",\"required\":false,\"description\":\"the
77 // port the DBMS service will listen to for data and
78 // requests\",\"password\":false,\"name\":\"port\",\"parentUniqueId\":\"52eb0139-a855-47b9-a0e6-c90f0a90b1d2\",\"definition\":true},{\"uniqueId\":\"52eb0139-a855-47b9-a0e6-c90f0a90b1d2.root_password\",\"type\":\"string\",\"required\":false,\"description\":\"the
79 // optional root password for the DBMS
80 // service\",\"password\":false,\"name\":\"root_password\",\"parentUniqueId\":\"52eb0139-a855-47b9-a0e6-c90f0a90b1d2\",\"definition\":true}],\"interfaces\":{\"standard\":{\"type\":\"tosca.interfaces.node.lifecycle.Standard\",\"uniqueId\":\"tosca.interfaces.node.lifecycle.standard\",\"operations\":{\"stop\":{\"uniqueId\":\"tosca.interfaces.node.lifecycle.standard.stop\",\"description\":\"Standard
82 // operation.\",\"definition\":false},\"start\":{\"uniqueId\":\"tosca.interfaces.node.lifecycle.standard.start\",\"description\":\"Standard
84 // operation.\",\"definition\":false},\"delete\":{\"uniqueId\":\"tosca.interfaces.node.lifecycle.standard.delete\",\"description\":\"Standard
86 // operation.\",\"definition\":false},\"create\":{\"uniqueId\":\"tosca.interfaces.node.lifecycle.standard.create\",\"description\":\"Standard
88 // operation.\",\"definition\":false},\"configure\":{\"uniqueId\":\"tosca.interfaces.node.lifecycle.standard.configure\",\"description\":\"Standard
89 // lifecycle configure
90 // operation.\",\"definition\":false}},\"definition\":false}},\"capabilities\":{\"feature\":{\"uniqueId\":\"capability.8313348e-3623-4f4a-9b8f-d2fbadaf9a31.feature\",\"type\":\"tosca.capabilities.Node\"},\"feature2\":{\"uniqueId\":\"capability.52eb0139-a855-47b9-a0e6-c90f0a90b1d2.feature2\",\"type\":\"tosca.capabilities.Node\"}},\"requirements\":{\"dependency\":{\"uniqueId\":\"8313348e-3623-4f4a-9b8f-d2fbadaf9a31.dependency\",\"capability\":\"tosca.capabilities.Node\",\"node\":\"tosca.nodes.Root\",\"relationship\":\"tosca.relationships.DependsOn\"},\"dependency2\":{\"uniqueId\":\"52eb0139-a855-47b9-a0e6-c90f0a90b1d2.dependency2\",\"capability\":\"tosca.capabilities.Node\",\"node\":\"tosca.nodes.importResource4test\",\"relationship\":\"tosca.relationships.DependsOn\"}},\"vendorName\":\"ATT
91 // (Tosca)\",\"vendorRelease\":\"1.0.0.wd03\",\"contactId\":\"jh0003\",\"systemName\":\"Importresource4test\",\"additionalInformation\":[{\"uniqueId\":\"52eb0139-a855-47b9-a0e6-c90f0a90b1d2.additionalinformation\",\"lastCreatedCounter\":0,\"parentUniqueId\":\"52eb0139-a855-47b9-a0e6-c90f0a90b1d2\",\"parameters\":[]}],\"allVersions\":{\"0.1\":\"52eb0139-a855-47b9-a0e6-c90f0a90b1d2\"},\"abstract\":false,\"highestVersion\":true,\"uuid\":\"2e91a2df-b066-49bb-abde-4c1c01e409db\"}";
92 // convertResourceResponseToJavaObject(response);
95 private static final String INVARIANT_UUID = "invariantUUID";
96 public static final String UNIQUE_ID = "uniqueId";
97 public static final String VERSION = "version";
98 public static final String UUID = "uuid";
99 public static final String NAME = "name";
100 public static final String ORIGIN_TYPE = "originType";
101 public static final String TOSCA_RESOURCE_NAME = "toscaResourceName";
103 static Logger logger = Logger.getLogger(ResponseParser.class.getName());
105 public static String getValueFromJsonResponse(String response, String fieldName) {
107 // JSONObject jsonResp = (JSONObject) JSONValue.parse(response);
108 String[] split = fieldName.split(":");
109 String fieldValue = response;
111 for(int i=0; i<split.length; i++) {
112 fieldValue = parser(fieldValue, split[i]);
115 } catch (Exception e) {
121 private static String parser(String response, String field){
122 JSONObject fieldValue = (JSONObject) JSONValue.parse(response);
123 return fieldValue.get(field).toString();
126 public static String getUniqueIdFromResponse(RestResponse response) {
127 return getValueFromJsonResponse(response.getResponse(), UNIQUE_ID);
130 public static String getInvariantUuid(RestResponse response) {
131 return getValueFromJsonResponse(response.getResponse(), INVARIANT_UUID);
134 public static String getUuidFromResponse(RestResponse response) {
135 return getValueFromJsonResponse(response.getResponse(), UUID);
138 public static String getNameFromResponse(RestResponse response) {
139 return getValueFromJsonResponse(response.getResponse(), NAME);
142 public static String getVersionFromResponse(RestResponse response) {
143 return ResponseParser.getValueFromJsonResponse(response.getResponse(), VERSION);
146 public static String getComponentTypeFromResponse(RestResponse response) {
147 return ResponseParser.getValueFromJsonResponse(response.getResponse(), ORIGIN_TYPE);
150 public static String getToscaResourceNameFromResponse(RestResponse response) {
151 return getValueFromJsonResponse(response.getResponse(), TOSCA_RESOURCE_NAME);
154 @SuppressWarnings("unchecked")
155 public static ResourceRespJavaObject parseJsonListReturnResourceDetailsObj(RestResponse restResponse,
156 String resourceType, String searchPattern, String expectedResult) throws Exception {
158 // Gson gson = new Gson;
160 JsonElement jElement = new JsonParser().parse(restResponse.getResponse());
161 JsonObject jObject = jElement.getAsJsonObject();
162 JsonArray arrayOfObjects = (JsonArray) jObject.get(resourceType);
163 Gson gson = new Gson();
164 Map<String, Object> map = new HashMap<>();
165 ResourceRespJavaObject jsonToJavaObject = new ResourceRespJavaObject();
167 for (int counter = 0; counter < arrayOfObjects.size(); counter++) {
168 JsonObject jHitObject = (JsonObject) arrayOfObjects.get(counter);
170 map = (Map<String, Object>) gson.fromJson(jHitObject.toString(), map.getClass());
171 if (map.get(searchPattern).toString().contains(expectedResult)) {
173 jsonToJavaObject = gson.fromJson(jObject, ResourceRespJavaObject.class);
177 return jsonToJavaObject;
181 private static ObjectMapper newObjectMapper() {
182 SimpleModule module = new SimpleModule("customDeserializationModule");
183 module.addDeserializer(PropertyConstraint.class, new PropertyConstraintJacksonDeserializer());
184 return new ObjectMapper()
185 .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
186 .registerModule(module);
189 public static Resource convertResourceResponseToJavaObject(String response) {
190 ObjectMapper mapper = newObjectMapper();
191 Resource resource = null;
193 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
194 resource = mapper.readValue(response, Resource.class);
196 logger.debug(resource.toString());
197 } catch (IOException e) {
199 List<Resource> resources = Arrays.asList(mapper.readValue(response.toString(), Resource[].class));
200 resource = resources.get(0);
201 } catch (Exception e1) {
202 e1.printStackTrace();
209 public static ComponentInstanceProperty convertPropertyResponseToJavaObject(String response) {
211 ObjectMapper mapper = newObjectMapper();
212 ComponentInstanceProperty propertyDefinition = null;
214 propertyDefinition = mapper.readValue(response, ComponentInstanceProperty.class);
215 logger.debug(propertyDefinition.toString());
216 } catch (IOException e) {
219 return propertyDefinition;
222 public static GroupDefinition convertPropertyResponseToObject(String response) {
224 ObjectMapper mapper = newObjectMapper();
225 GroupDefinition groupDefinition = null;
227 groupDefinition = mapper.readValue(response, GroupDefinition.class);
228 logger.debug(groupDefinition.toString());
229 } catch (IOException e) {
232 return groupDefinition;
235 public static String toJson(Object object) {
236 Gson gson = new Gson();
237 return gson.toJson(object);
240 public static ArtifactDefinition convertArtifactDefinitionResponseToJavaObject(String response) {
241 ObjectMapper mapper = new ObjectMapper();
242 ArtifactDefinition artifactDefinition = null;
244 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
245 artifactDefinition = mapper.readValue(response, ArtifactDefinition.class);
246 logger.debug(artifactDefinition.toString());
247 } catch (IOException e) {
251 return artifactDefinition;
255 public static ArtifactReqDetails convertArtifactReqDetailsToJavaObject(String response) {
257 ArtifactReqDetails artifactReqDetails = null;
258 Gson gson = new Gson();
259 artifactReqDetails = gson.fromJson(response, ArtifactReqDetails.class);
260 return artifactReqDetails;
263 public static <T> T parseToObject(String json, Class<T> clazz) {
264 Gson gson = new Gson();
267 object = gson.fromJson(json, clazz);
268 } catch (Exception e) {
269 object = parseToObjectUsingMapper(json, clazz);
274 public static <T> T parseToObjectUsingMapper(String json, Class<T> clazz) {
276 ObjectMapper mapper = newObjectMapper();
279 object = mapper.readValue(json, clazz);
280 } catch (IOException e) {
287 public static ArtifactReqDetails convertArtifactDefinitionToArtifactReqDetailsObject(
288 ArtifactDefinition artifactDefinition) {
290 ArtifactReqDetails artifactReqDetails = null;
291 Gson gson = new Gson();
292 String artDef = gson.toJson(artifactDefinition);
293 artifactReqDetails = gson.fromJson(artDef, ArtifactReqDetails.class);
294 return artifactReqDetails;
297 public static Service convertServiceResponseToJavaObject(String response) {
299 ObjectMapper mapper = newObjectMapper();
300 Service service = null;
302 service = mapper.readValue(response, Service.class);
303 logger.debug(service.toString());
304 } catch (IOException e) {
311 public static Product convertProductResponseToJavaObject(String response) {
313 ObjectMapper mapper = newObjectMapper();
314 Product product = null;
316 product = mapper.readValue(response, Product.class);
317 logger.debug(product.toString());
318 } catch (IOException e) {
325 public static ComponentInstance convertComponentInstanceResponseToJavaObject(String response) {
327 ObjectMapper mapper = newObjectMapper();
328 ComponentInstance componentInstance = null;
330 componentInstance = mapper.readValue(response, ComponentInstance.class);
331 logger.debug(componentInstance.toString());
332 } catch (IOException e) {
333 // TODO Auto-generated catch block
337 return componentInstance;
340 public static List<String> getValuesFromJsonArray(RestResponse message) throws Exception {
341 List<String> artifactTypesArrayFromApi = new ArrayList<>();
343 org.json.JSONObject responseObject = new org.json.JSONObject(message.getResponse());
344 JSONArray jArr = responseObject.getJSONArray("artifactTypes");
346 for (int i = 0; i < jArr.length(); i++) {
347 org.json.JSONObject jObj = jArr.getJSONObject(i);
348 String value = jObj.get("name").toString();
350 artifactTypesArrayFromApi.add(value);
352 return artifactTypesArrayFromApi;
355 public static String calculateMD5Header(ArtifactReqDetails artifactDetails) {
356 Gson gson = new Gson();
357 String jsonBody = gson.toJson(artifactDetails);
358 // calculate MD5 for json body
359 return calculateMD5(jsonBody);
363 public static String calculateMD5(String data) {
364 String calculatedMd5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(data);
365 // encode base-64 result
366 byte[] encodeBase64 = Base64.encodeBase64(calculatedMd5.getBytes());
367 String encodeBase64Str = new String(encodeBase64);
368 return encodeBase64Str;
372 public static List<Map<String, Object>> getAuditFromMessage(Map<String, Object> auditingMessage) {
373 List<Map<String, Object>> auditList = new ArrayList<>();
374 auditList.add(auditingMessage);
378 public static List<CategoryDefinition> parseCategories(RestResponse getAllCategoriesRest) {
380 List<CategoryDefinition> categories = new ArrayList<>();
382 JsonElement jElement = new JsonParser().parse(getAllCategoriesRest.getResponse());
383 JsonArray cagegories = jElement.getAsJsonArray();
384 Iterator<JsonElement> iter = cagegories.iterator();
385 while (iter.hasNext()) {
386 JsonElement next = iter.next();
387 CategoryDefinition category = ResponseParser.parseToObject(next.toString(), CategoryDefinition.class);
388 categories.add(category);
391 } catch (Exception e) {
398 public static JSONArray getListFromJson(RestResponse res, String field) throws JSONException {
399 String valueFromJsonResponse = getValueFromJsonResponse(res.getResponse(), field);
400 JSONArray jArr = new JSONArray(valueFromJsonResponse);
405 public static List<String> getDerivedListFromJson(RestResponse res) throws JSONException {
406 JSONArray listFromJson = getListFromJson(res, "derivedFrom");
407 List<String> lst = new ArrayList<>();
408 for (int i = 0; i < listFromJson.length(); i++) {
409 lst.add(listFromJson.getString(i));
415 public static Map<String, Object> convertStringToMap(String obj) {
416 Map<String, Object> object = (Map<String, Object>) JSONValue.parse(obj);
420 public static List<Map<String, Object>> getListOfMapsFromJson(RestResponse res, String field) throws Exception {
421 List<Map<String, Object>> list = new ArrayList<>();
422 JSONArray listFromJson = getListFromJson(res, field);
423 for (int i = 0; i < listFromJson.length(); i++) {
424 Map<String, Object> convertStringToMap = convertStringToMap(listFromJson.getString(i));
425 list.add(convertStringToMap);
431 public static Map<String, Object> getJsonValueAsMap(RestResponse response, String key) {
432 String valueField = getValueFromJsonResponse(response.getResponse(), key);
433 Map<String, Object> convertToMap = convertStringToMap(valueField);
437 public static String getJsonObjectValueByKey(String metadata, String key) {
438 JsonElement jelement = new JsonParser().parse(metadata);
440 JsonObject jobject = jelement.getAsJsonObject();
441 Object obj = jobject.get(key);
445 return obj.toString();
449 public static Map<String, List<Component>> convertCatalogResponseToJavaObject(String response) {
451 // Map<String, ArrayList<Component>> map = new HashMap<String,
452 // ArrayList<Component>>();
453 Map<String, List<Component>> map = new HashMap<>();
455 JsonElement jElement = new JsonParser().parse(response);
456 JsonObject jObject = jElement.getAsJsonObject();
457 JsonArray jArrReousrces = jObject.getAsJsonArray("resources");
458 JsonArray jArrServices = jObject.getAsJsonArray("services");
459 JsonArray jArrProducts = jObject.getAsJsonArray("products");
461 if (jArrReousrces != null && jArrServices != null && jArrProducts != null){
464 //////// RESOURCE/////////////////////////////
465 ArrayList<Component> restResponseArray = new ArrayList<>();
466 Component component = null;
467 for (int i = 0; i < jArrReousrces.size(); i++) {
468 String resourceString = (String) jArrReousrces.get(i).toString();
469 component = ResponseParser.convertResourceResponseToJavaObject(resourceString);
470 restResponseArray.add(component);
473 map.put("resources", restResponseArray);
475 ///////// SERVICE/////////////////////////////
477 restResponseArray = new ArrayList<>();
479 for (int i = 0; i < jArrServices.size(); i++) {
480 String resourceString = (String) jArrServices.get(i).toString();
481 component = ResponseParser.convertServiceResponseToJavaObject(resourceString);
482 restResponseArray.add(component);
485 map.put("services", restResponseArray);
487 ///////// PRODUCT/////////////////////////////
488 restResponseArray = new ArrayList<>();
490 for (int i = 0; i < jArrProducts.size(); i++) {
491 String resourceString = (String) jArrProducts.get(i).toString();
492 component = ResponseParser.convertProductResponseToJavaObject(resourceString);
493 restResponseArray.add(component);
496 map.put("products", restResponseArray);
500 map.put("resources", new ArrayList<>());
501 map.put("services", new ArrayList<>());
502 map.put("products", new ArrayList<>());
510 public static Map<Long, ServiceDistributionStatus> convertServiceDistributionStatusToObject(String response) throws ParseException {
512 Map<Long, ServiceDistributionStatus> serviceDistributionStatusMap = new HashMap<>();
513 ServiceDistributionStatus serviceDistributionStatusObject = null;
515 JsonElement jElement = new JsonParser().parse(response);
516 JsonObject jObject = jElement.getAsJsonObject();
517 JsonArray jDistrStatusArray = jObject.getAsJsonArray("distributionStatusOfServiceList");
519 for (int i = 0; i < jDistrStatusArray.size(); i++){
520 Gson gson = new Gson();
521 String servDistrStatus = gson.toJson(jDistrStatusArray.get(i));
522 serviceDistributionStatusObject = gson.fromJson(servDistrStatus, ServiceDistributionStatus.class);
523 serviceDistributionStatusMap.put(Utils.getEpochTimeFromUTC(serviceDistributionStatusObject.getTimestamp()), serviceDistributionStatusObject);
526 return serviceDistributionStatusMap;
530 public static Map<String, String> getPropertiesNameType(RestResponse restResponse)
531 throws JSONException {
532 Map<String, String> propertiesMap = new HashMap<>();
533 JSONArray propertiesList = getListFromJson(restResponse, "properties");
534 for (int i = 0; i < propertiesList.length() ; i ++){
535 JSONObject prop = (JSONObject) JSONValue.parse(propertiesList.get(i).toString());
536 String propName = prop.get("name").toString();
537 String propType = prop.get("type").toString();
538 propertiesMap.put(propName, propType);
541 return propertiesMap;
544 public static ResourceAssetStructure getDataOutOfSearchExternalAPIResponseForResourceName(String response, String resourceName) {
545 Gson gson = new Gson();
546 JsonElement jsonElement = new JsonParser().parse(response);
547 JsonArray jsonArray = jsonElement.getAsJsonArray();
548 for(JsonElement jElement: jsonArray) {
549 ResourceAssetStructure parsedResponse = gson.fromJson(jElement, ResourceAssetStructure.class);
551 if(resourceName.contains(parsedResponse.getName()) && parsedResponse.getName().contains(resourceName)) {
552 return parsedResponse;