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 java.io.IOException;
24 import java.text.ParseException;
25 import java.util.ArrayList;
26 import java.util.Arrays;
27 import java.util.HashMap;
28 import java.util.Iterator;
29 import java.util.List;
32 import org.apache.commons.codec.binary.Base64;
33 import org.apache.log4j.Logger;
34 import org.codehaus.jackson.Version;
35 import org.codehaus.jackson.map.JsonDeserializer;
36 import org.codehaus.jackson.map.ObjectMapper;
37 import org.codehaus.jackson.map.module.SimpleModule;
38 import org.json.JSONArray;
39 import org.json.JSONException;
40 import org.json.simple.JSONObject;
41 import org.json.simple.JSONValue;
42 import org.openecomp.sdc.be.model.ArtifactDefinition;
43 import org.openecomp.sdc.be.model.Component;
44 import org.openecomp.sdc.be.model.ComponentInstance;
45 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
46 import org.openecomp.sdc.be.model.Product;
47 import org.openecomp.sdc.be.model.PropertyConstraint;
48 import org.openecomp.sdc.be.model.Resource;
49 import org.openecomp.sdc.be.model.Service;
50 import org.openecomp.sdc.be.model.category.CategoryDefinition;
51 import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintJacksonDeserialiser;
52 import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
53 import org.openecomp.sdc.ci.tests.datatypes.ResourceRespJavaObject;
54 import org.openecomp.sdc.ci.tests.datatypes.ServiceDistributionStatus;
55 import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
56 import org.openecomp.sdc.ci.tests.utils.Utils;
58 import com.google.gson.Gson;
59 import com.google.gson.JsonArray;
60 import com.google.gson.JsonElement;
61 import com.google.gson.JsonObject;
62 import com.google.gson.JsonParser;
64 public class ResponseParser {
66 // comment by Andrey, for test only
67 // public static void main(String[] args) {
69 // "{\"uniqueId\":\"52eb0139-a855-47b9-a0e6-c90f0a90b1d2\",\"resourceName\":\"importResource4test\",\"resourceVersion\":\"0.1\",\"creatorUserId\":\"jh0003\",\"creatorFullName\":\"Jimmy
70 // Hendrix\",\"lastUpdaterUserId\":\"jh0003\",\"lastUpdaterFullName\":\"Jimmy
71 // Hendrix\",\"creationDate\":1446742241514,\"lastUpdateDate\":1446742241514,\"description\":\"Represents
72 // a generic software component that can be managed and run by a Compute
74 // 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
75 // port the DBMS service will listen to for data and
76 // 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
77 // optional root password for the DBMS
78 // 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
80 // operation.\",\"definition\":false},\"start\":{\"uniqueId\":\"tosca.interfaces.node.lifecycle.standard.start\",\"description\":\"Standard
82 // operation.\",\"definition\":false},\"delete\":{\"uniqueId\":\"tosca.interfaces.node.lifecycle.standard.delete\",\"description\":\"Standard
84 // operation.\",\"definition\":false},\"create\":{\"uniqueId\":\"tosca.interfaces.node.lifecycle.standard.create\",\"description\":\"Standard
86 // operation.\",\"definition\":false},\"configure\":{\"uniqueId\":\"tosca.interfaces.node.lifecycle.standard.configure\",\"description\":\"Standard
87 // lifecycle configure
88 // 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
89 // (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\"}";
90 // convertResourceResponseToJavaObject(response);
93 private static final String INVARIANT_UUID = "invariantUUID";
94 public static final String UNIQUE_ID = "uniqueId";
95 public static final String VERSION = "version";
96 public static final String UUID = "uuid";
97 public static final String NAME = "name";
98 public static final String ORIGIN_TYPE = "originType";
99 public static final String TOSCA_RESOURCE_NAME = "toscaResourceName";
101 static Logger logger = Logger.getLogger(ResponseParser.class.getName());
103 public static String getValueFromJsonResponse(String response, String fieldName) {
105 JSONObject jsonResp = (JSONObject) JSONValue.parse(response);
106 Object fieldValue = jsonResp.get(fieldName);
107 return fieldValue.toString();
109 } catch (Exception e) {
115 public static String getUniqueIdFromResponse(RestResponse response) {
116 return getValueFromJsonResponse(response.getResponse(), UNIQUE_ID);
119 public static String getInvariantUuid(RestResponse response) {
120 return getValueFromJsonResponse(response.getResponse(), INVARIANT_UUID);
123 public static String getUuidFromResponse(RestResponse response) {
124 return getValueFromJsonResponse(response.getResponse(), UUID);
127 public static String getNameFromResponse(RestResponse response) {
128 return getValueFromJsonResponse(response.getResponse(), NAME);
131 public static String getVersionFromResponse(RestResponse response) {
132 return ResponseParser.getValueFromJsonResponse(response.getResponse(), VERSION);
135 public static String getComponentTypeFromResponse(RestResponse response) {
136 return ResponseParser.getValueFromJsonResponse(response.getResponse(), ORIGIN_TYPE);
139 public static String getToscaResourceNameFromResponse(RestResponse response) {
140 return getValueFromJsonResponse(response.getResponse(), TOSCA_RESOURCE_NAME);
143 @SuppressWarnings("unchecked")
144 public static ResourceRespJavaObject parseJsonListReturnResourceDetailsObj(RestResponse restResponse,
145 String resourceType, String searchPattern, String expectedResult) throws Exception {
147 // Gson gson = new Gson;
149 JsonElement jElement = new JsonParser().parse(restResponse.getResponse());
150 JsonObject jObject = jElement.getAsJsonObject();
151 JsonArray arrayOfObjects = (JsonArray) jObject.get(resourceType);
152 Gson gson = new Gson();
153 Map<String, Object> map = new HashMap<String, Object>();
154 ResourceRespJavaObject jsonToJavaObject = new ResourceRespJavaObject();
156 for (int counter = 0; counter < arrayOfObjects.size(); counter++) {
157 JsonObject jHitObject = (JsonObject) arrayOfObjects.get(counter);
159 map = (Map<String, Object>) gson.fromJson(jHitObject.toString(), map.getClass());
160 if (map.get(searchPattern).toString().contains(expectedResult)) {
162 jsonToJavaObject = gson.fromJson(jObject, ResourceRespJavaObject.class);
166 return jsonToJavaObject;
170 public static Resource convertResourceResponseToJavaObject(String response) {
172 ObjectMapper mapper = new ObjectMapper();
173 final SimpleModule module = new SimpleModule("customerSerializationModule",
174 new Version(1, 0, 0, "static version"));
175 JsonDeserializer<PropertyConstraint> desrializer = new PropertyConstraintJacksonDeserialiser();
176 addDeserializer(module, PropertyConstraint.class, desrializer);
178 mapper.registerModule(module);
179 Resource resource = null;
181 resource = mapper.readValue(response, Resource.class);
182 logger.debug(resource.toString());
183 } catch (IOException e) {
185 List<Resource> resources = Arrays.asList(mapper.readValue(response.toString(), Resource[].class));
186 resource = resources.get(0);
187 } catch (Exception e1) {
188 // TODO Auto-generated catch block
189 e1.printStackTrace();
196 public static ComponentInstanceProperty convertPropertyResponseToJavaObject(String response) {
198 ObjectMapper mapper = new ObjectMapper();
199 final SimpleModule module = new SimpleModule("customerSerializationModule",
200 new Version(1, 0, 0, "static version"));
201 JsonDeserializer<PropertyConstraint> desrializer = new PropertyConstraintJacksonDeserialiser();
202 addDeserializer(module, PropertyConstraint.class, desrializer);
204 mapper.registerModule(module);
205 ComponentInstanceProperty propertyDefinition = null;
207 propertyDefinition = mapper.readValue(response, ComponentInstanceProperty.class);
208 logger.debug(propertyDefinition.toString());
209 } catch (IOException e) {
210 // TODO Auto-generated catch block
213 return propertyDefinition;
216 public static String toJson(Object object) {
217 Gson gson = new Gson();
218 return gson.toJson(object);
221 public static ArtifactDefinition convertArtifactDefinitionResponseToJavaObject(String response) {
222 ObjectMapper mapper = new ObjectMapper();
223 ArtifactDefinition artifactDefinition = null;
226 artifactDefinition = mapper.readValue(response, ArtifactDefinition.class);
227 logger.debug(artifactDefinition.toString());
228 } catch (IOException e) {
229 // TODO Auto-generated catch block
233 return artifactDefinition;
237 public static ArtifactReqDetails convertArtifactReqDetailsToJavaObject(String response) {
239 ArtifactReqDetails artifactReqDetails = null;
241 Gson gson = new Gson();
242 artifactReqDetails = gson.fromJson(response, ArtifactReqDetails.class);
243 return artifactReqDetails;
246 public static <T> T parseToObject(String json, Class<T> clazz) {
247 Gson gson = new Gson();
250 object = gson.fromJson(json, clazz);
251 } catch (Exception e) {
252 object = parseToObjectUsingMapper(json, clazz);
257 public static <T> T parseToObjectUsingMapper(String json, Class<T> clazz) {
259 ObjectMapper mapper = new ObjectMapper();
261 final SimpleModule module = new SimpleModule("customerSerializationModule",
262 new Version(1, 0, 0, "static version"));
263 JsonDeserializer<PropertyConstraint> desrializer = new PropertyConstraintJacksonDeserialiser();
264 addDeserializer(module, PropertyConstraint.class, desrializer);
265 mapper.registerModule(module);
267 object = mapper.readValue(json, clazz);
268 // System.out.println("Class: "+clazz.getSimpleName()+", json:
270 } catch (IOException e) {
271 // TODO Auto-generated catch block
278 public static ArtifactReqDetails convertArtifactDefinitionToArtifactReqDetailsObject(
279 ArtifactDefinition artifactDefinition) {
281 ArtifactReqDetails artifactReqDetails = null;
283 Gson gson = new Gson();
284 String artDef = gson.toJson(artifactDefinition);
285 artifactReqDetails = gson.fromJson(artDef, ArtifactReqDetails.class);
286 return artifactReqDetails;
289 public static <T> void addDeserializer(SimpleModule module, Class<T> clazz,
290 final JsonDeserializer<T> deserializer) {
291 module.addDeserializer(clazz, deserializer);
294 public static Service convertServiceResponseToJavaObject(String response) {
296 ObjectMapper mapper = new ObjectMapper();
297 final SimpleModule module = new SimpleModule("customerSerializationModule",
298 new Version(1, 0, 0, "static version"));
299 JsonDeserializer<PropertyConstraint> desrializer = new PropertyConstraintJacksonDeserialiser();
300 addDeserializer(module, PropertyConstraint.class, desrializer);
302 mapper.registerModule(module);
303 Service service = null;
305 service = mapper.readValue(response, Service.class);
306 logger.debug(service.toString());
307 } catch (IOException e) {
308 // TODO Auto-generated catch block
315 public static Product convertProductResponseToJavaObject(String response) {
317 ObjectMapper mapper = new ObjectMapper();
318 Product product = null;
320 product = mapper.readValue(response, Product.class);
321 logger.debug(product.toString());
322 } catch (IOException e) {
323 // TODO Auto-generated catch block
330 public static ComponentInstance convertComponentInstanceResponseToJavaObject(String response) {
332 ObjectMapper mapper = new ObjectMapper();
333 final SimpleModule module = new SimpleModule("customerSerializationModule",
334 new Version(1, 0, 0, "static version"));
335 JsonDeserializer<PropertyConstraint> desrializer = new PropertyConstraintJacksonDeserialiser();
336 addDeserializer(module, PropertyConstraint.class, desrializer);
338 mapper.registerModule(module);
339 ComponentInstance componentInstance = null;
341 componentInstance = mapper.readValue(response, ComponentInstance.class);
342 logger.debug(componentInstance.toString());
343 } catch (IOException e) {
344 // TODO Auto-generated catch block
348 return componentInstance;
351 public static List<String> getValuesFromJsonArray(RestResponse message) throws Exception {
352 List<String> artifactTypesArrayFromApi = new ArrayList<String>();
354 org.json.JSONObject responseObject = new org.json.JSONObject(message.getResponse());
355 JSONArray jArr = responseObject.getJSONArray("artifactTypes");
357 for (int i = 0; i < jArr.length(); i++) {
358 org.json.JSONObject jObj = jArr.getJSONObject(i);
359 String value = jObj.get("name").toString();
361 artifactTypesArrayFromApi.add(value);
363 return artifactTypesArrayFromApi;
366 public static String calculateMD5Header(ArtifactReqDetails artifactDetails) {
367 Gson gson = new Gson();
368 String jsonBody = gson.toJson(artifactDetails);
369 // calculate MD5 for json body
370 return calculateMD5(jsonBody);
374 public static String calculateMD5(String data) {
375 String calculatedMd5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(data);
376 // encode base-64 result
377 byte[] encodeBase64 = Base64.encodeBase64(calculatedMd5.getBytes());
378 String encodeBase64Str = new String(encodeBase64);
379 return encodeBase64Str;
383 public static List<Map<String, Object>> getAuditFromMessage(Map auditingMessage) {
384 List<Map<String, Object>> auditList = new ArrayList<Map<String, Object>>();
385 // JsonElement jElement = new JsonParser().parse(auditingMessage);
386 // JsonObject jObject = jElement.getAsJsonObject();
387 // JsonObject hitsObject = (JsonObject) jObject.get("hits");
388 // JsonArray hitsArray = (JsonArray) hitsObject.get("hits");
390 // Iterator<JsonElement> hitsIterator = hitsArray.iterator();
391 // while(hitsIterator.hasNext())
393 // JsonElement nextHit = hitsIterator.next();
394 // JsonObject jHitObject = nextHit.getAsJsonObject();
395 // JsonObject jSourceObject = (JsonObject) jHitObject.get("_source");
397 // Gson gson=new Gson();
398 // String auditUnparsed = jSourceObject.toString();
400 // Map<String,Object> map = new HashMap<String,Object>();
401 // map = (Map<String,Object>) gson.fromJson(auditUnparsed,
404 auditList.add(auditingMessage);
409 public static List<CategoryDefinition> parseCategories(RestResponse getAllCategoriesRest) {
411 List<CategoryDefinition> categories = new ArrayList<>();
413 JsonElement jElement = new JsonParser().parse(getAllCategoriesRest.getResponse());
414 JsonArray cagegories = jElement.getAsJsonArray();
415 Iterator<JsonElement> iter = cagegories.iterator();
416 while (iter.hasNext()) {
417 JsonElement next = iter.next();
418 CategoryDefinition category = ResponseParser.parseToObject(next.toString(), CategoryDefinition.class);
419 categories.add(category);
422 } catch (Exception e) {
429 public static JSONArray getListFromJson(RestResponse res, String field) throws JSONException {
430 String valueFromJsonResponse = getValueFromJsonResponse(res.getResponse(), field);
431 JSONArray jArr = new JSONArray(valueFromJsonResponse);
436 public static List<String> getDerivedListFromJson(RestResponse res) throws JSONException {
437 JSONArray listFromJson = getListFromJson(res, "derivedFrom");
438 List<String> lst = new ArrayList<String>();
439 for (int i = 0; i < listFromJson.length(); i++) {
440 lst.add(listFromJson.getString(i));
446 public static Map<String, Object> convertStringToMap(String obj) {
447 Map<String, Object> object = (Map<String, Object>) JSONValue.parse(obj);
451 public static List<Map<String, Object>> getListOfMapsFromJson(RestResponse res, String field) throws Exception {
452 List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
453 JSONArray listFromJson = getListFromJson(res, field);
454 for (int i = 0; i < listFromJson.length(); i++) {
455 Map<String, Object> convertStringToMap = convertStringToMap(listFromJson.getString(i));
456 list.add(convertStringToMap);
462 public static Map<String, Object> getJsonValueAsMap(RestResponse response, String key) {
463 String valueField = getValueFromJsonResponse(response.getResponse(), key);
464 Map<String, Object> convertToMap = convertStringToMap(valueField);
468 public static String getJsonObjectValueByKey(String metadata, String key) {
469 JsonElement jelement = new JsonParser().parse(metadata);
471 JsonObject jobject = jelement.getAsJsonObject();
472 Object obj = jobject.get(key);
476 return obj.toString();
480 public static Map<String, List<Component>> convertCatalogResponseToJavaObject(String response) {
482 // Map<String, ArrayList<Component>> map = new HashMap<String,
483 // ArrayList<Component>>();
484 Map<String, List<Component>> map = new HashMap<String, List<Component>>();
486 JsonElement jElement = new JsonParser().parse(response);
487 JsonObject jObject = jElement.getAsJsonObject();
488 JsonArray jArrReousrces = jObject.getAsJsonArray("resources");
489 JsonArray jArrServices = jObject.getAsJsonArray("services");
490 JsonArray jArrProducts = jObject.getAsJsonArray("products");
492 //////// RESOURCE/////////////////////////////
493 ArrayList<Component> restResponseArray = new ArrayList<>();
494 Component component = null;
495 for (int i = 0; i < jArrReousrces.size(); i++) {
496 String resourceString = (String) jArrReousrces.get(i).toString();
497 component = ResponseParser.convertResourceResponseToJavaObject(resourceString);
498 restResponseArray.add(component);
501 map.put("resources", restResponseArray);
503 ///////// SERVICE/////////////////////////////
505 restResponseArray = new ArrayList<>();
507 for (int i = 0; i < jArrServices.size(); i++) {
508 String resourceString = (String) jArrServices.get(i).toString();
509 component = ResponseParser.convertServiceResponseToJavaObject(resourceString);
510 restResponseArray.add(component);
513 map.put("services", restResponseArray);
515 ///////// PRODUCT/////////////////////////////
516 restResponseArray = new ArrayList<>();
518 for (int i = 0; i < jArrProducts.size(); i++) {
519 String resourceString = (String) jArrProducts.get(i).toString();
520 component = ResponseParser.convertProductResponseToJavaObject(resourceString);
521 restResponseArray.add(component);
524 map.put("products", restResponseArray);
531 public static Map<Long, ServiceDistributionStatus> convertServiceDistributionStatusToObject(String response) throws ParseException {
533 Map<Long, ServiceDistributionStatus> serviceDistributionStatusMap = new HashMap<Long, ServiceDistributionStatus>();
534 ServiceDistributionStatus serviceDistributionStatusObject = null;
536 JsonElement jElement = new JsonParser().parse(response);
537 JsonObject jObject = jElement.getAsJsonObject();
538 JsonArray jDistrStatusArray = jObject.getAsJsonArray("distributionStatusOfServiceList");
540 for (int i = 0; i < jDistrStatusArray.size(); i++){
541 Gson gson = new Gson();
542 String servDistrStatus = gson.toJson(jDistrStatusArray.get(i));
543 serviceDistributionStatusObject = gson.fromJson(servDistrStatus, ServiceDistributionStatus.class);
544 serviceDistributionStatusMap.put(Utils.getEpochTimeFromUTC(serviceDistributionStatusObject.getTimestamp()), serviceDistributionStatusObject);
547 return serviceDistributionStatusMap;
551 public static Map<String, String> getPropertiesNameType(RestResponse restResponse)
552 throws JSONException {
553 Map<String, String> propertiesMap = new HashMap<String, String>();
554 JSONArray propertiesList = getListFromJson(restResponse, "properties");
555 for (int i = 0; i < propertiesList.length() ; i ++){
556 JSONObject prop = (JSONObject) JSONValue.parse(propertiesList.get(i).toString());
557 String propName = prop.get("name").toString();
558 String propType = prop.get("type").toString();
559 propertiesMap.put(propName, propType);
562 return propertiesMap;