Fix for radio buttons
[sdc.git] / asdc-tests / src / main / java / org / openecomp / sdc / ci / tests / utils / rest / ResourceRestUtils.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.openecomp.sdc.ci.tests.utils.rest;
22
23 import static org.testng.AssertJUnit.assertEquals;
24
25 import java.io.FileNotFoundException;
26 import java.io.IOException;
27 import java.nio.file.Files;
28 import java.nio.file.Path;
29 import java.nio.file.Paths;
30 import java.util.ArrayList;
31 import java.util.HashMap;
32 import java.util.List;
33 import java.util.Map;
34
35 import org.apache.commons.codec.binary.Base64;
36 import org.apache.commons.lang.StringUtils;
37 import org.apache.http.client.ClientProtocolException;
38 import org.json.JSONException;
39 import org.json.simple.JSONArray;
40 import org.json.simple.JSONObject;
41 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
42 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
43 import org.openecomp.sdc.be.model.CapabilityDefinition;
44 import org.openecomp.sdc.be.model.Component;
45 import org.openecomp.sdc.be.model.ComponentInstance;
46 import org.openecomp.sdc.be.model.RequirementDefinition;
47 import org.openecomp.sdc.be.model.Resource;
48 import org.openecomp.sdc.be.model.User;
49 import org.openecomp.sdc.be.resources.data.RelationshipInstData;
50 import org.openecomp.sdc.ci.tests.api.Urls;
51 import org.openecomp.sdc.ci.tests.config.Config;
52 import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails;
53 import org.openecomp.sdc.ci.tests.datatypes.ImportReqDetails;
54 import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
55 import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
56 import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
57 import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest;
58 import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
59 import org.openecomp.sdc.ci.tests.utils.Utils;
60 import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
61 import org.openecomp.sdc.common.util.GeneralUtility;
62 import org.slf4j.Logger;
63 import org.slf4j.LoggerFactory;
64
65 import com.google.gson.Gson;
66 import com.google.gson.JsonArray;
67 import com.google.gson.JsonElement;
68 import com.google.gson.JsonParser;
69
70 public class ResourceRestUtils extends BaseRestUtils {
71         
72         private static final String CSARS_PATH = "/src/test/resources/CI/csars/";
73         private static Logger logger = LoggerFactory.getLogger(ResourceRestUtils.class.getName());
74
75         // ****** CREATE *******
76
77         public static RestResponse createResource(ResourceReqDetails resourceDetails, User sdncModifierDetails)
78                         throws Exception {
79
80                 Config config = Utils.getConfig();
81                 String url = String.format(Urls.CREATE_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort());
82
83                 String userId = sdncModifierDetails.getUserId();
84
85                 Map<String, String> headersMap = prepareHeadersMap(userId);
86
87                 Gson gson = new Gson();
88                 String userBodyJson = gson.toJson(resourceDetails);
89                 String calculateMD5 = GeneralUtility.calculateMD5Base64EncodedByString(userBodyJson);
90                 headersMap.put(HttpHeaderEnum.Content_MD5.getValue(), calculateMD5);
91                 HttpRequest http = new HttpRequest();
92                 // System.out.println(url);
93                 // System.out.println(userBodyJson);
94                 RestResponse createResourceResponse = http.httpSendPost(url, userBodyJson, headersMap);
95                 if (createResourceResponse.getErrorCode() == STATUS_CODE_CREATED) {
96                         resourceDetails.setUUID(ResponseParser.getUuidFromResponse(createResourceResponse));
97                         resourceDetails.setVersion(ResponseParser.getVersionFromResponse(createResourceResponse));
98                         resourceDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(createResourceResponse));
99                         String lastUpdaterUserId = ResponseParser.getValueFromJsonResponse(createResourceResponse.getResponse(),
100                                         "lastUpdaterUserId");
101                         resourceDetails.setLastUpdaterUserId(lastUpdaterUserId);
102                         String lastUpdaterFullName = ResponseParser.getValueFromJsonResponse(createResourceResponse.getResponse(),
103                                         "lastUpdaterFullName");
104                         resourceDetails.setLastUpdaterFullName(lastUpdaterFullName);
105                         // Creator details never change after component is created - Ella,
106                         // 12/1/2016
107                         resourceDetails.setCreatorUserId(userId);
108                         resourceDetails.setCreatorFullName(sdncModifierDetails.getFullName());
109                 }
110                 return createResourceResponse;
111
112         }
113
114         public static RestResponse createImportResource(ImportReqDetails importReqDetails, User sdncModifierDetails,
115                         Map<String, String> additionalHeaders) throws JSONException, IOException {
116
117                 Config config = Utils.getConfig();
118                 String url = String.format(Urls.CREATE_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort());
119                 String userId = sdncModifierDetails.getUserId();
120
121                 Gson gson = new Gson();
122                 String resourceImportBodyJson = gson.toJson(importReqDetails);
123                 HttpRequest http = new HttpRequest();
124                 // System.out.println(url);
125                 // System.out.println(resourceImportBodyJson);
126
127                 Map<String, String> headersMap = prepareHeadersMap(userId);
128                 if (additionalHeaders != null) {
129                         headersMap.putAll(additionalHeaders);
130                 } else {
131                         headersMap.put(HttpHeaderEnum.Content_MD5.getValue(),
132                                         ArtifactRestUtils.calculateMD5(resourceImportBodyJson));
133                 }
134
135                 RestResponse createResourceResponse = http.httpSendPost(url, resourceImportBodyJson, headersMap);
136                 if (createResourceResponse.getErrorCode() == STATUS_CODE_CREATED) {
137                         importReqDetails.setVersion(ResponseParser.getVersionFromResponse(createResourceResponse));
138                         importReqDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(createResourceResponse));
139                         // Creator details never change after component is created - Ella,
140                         // 12/1/2016
141                         importReqDetails.setCreatorUserId(userId);
142                         importReqDetails.setCreatorFullName(sdncModifierDetails.getFullName());
143                         importReqDetails
144                                         .setToscaResourceName(ResponseParser.getToscaResourceNameFromResponse(createResourceResponse));
145                         importReqDetails.setDerivedList(ResponseParser.getDerivedListFromJson(createResourceResponse));
146                 }
147                 return createResourceResponse;
148
149         }
150
151         // ***** DELETE ****
152         public static RestResponse deleteResource(ResourceReqDetails resourceDetails, User sdncModifierDetails,
153                         String version) throws IOException {
154
155                 if (resourceDetails.getUniqueId() != null) {
156                         Config config = Utils.getConfig();
157                         String url = String.format(Urls.DELETE_RESOURCE_BY_NAME_AND_VERSION, config.getCatalogBeHost(),
158                                         config.getCatalogBePort(), resourceDetails.getName(), version);
159                         return sendDelete(url, sdncModifierDetails.getUserId());
160                 } else {
161                         return null;
162                 }
163
164         }
165
166         public static RestResponse markResourceToDelete(String resourceId, String userId) throws IOException {
167
168                 Config config = Utils.getConfig();
169                 String url = String.format(Urls.DELETE_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(),
170                                 resourceId);
171                 RestResponse sendDelete = sendDelete(url, userId);
172
173                 return sendDelete;
174
175         }
176
177         public static RestResponse deleteResource(String resourceId, String userId) throws IOException {
178
179                 Config config = Utils.getConfig();
180                 String url = String.format(Urls.DELETE_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(),
181                                 resourceId);
182                 RestResponse sendDelete = sendDelete(url, userId);
183
184                 deleteMarkedResources(userId);
185
186                 return sendDelete;
187
188         }
189
190         public static void deleteMarkedResources(String userId) throws IOException {
191                 String url;
192                 Config config = Utils.getConfig();
193                 url = String.format(Urls.DELETE_MARKED_RESOURCES, config.getCatalogBeHost(), config.getCatalogBePort());
194                 sendDelete(url, userId);
195         }
196
197         public static RestResponse deleteResourceByNameAndVersion(User sdncModifierDetails, String resourceName,
198                         String resourceVersion) throws IOException {
199                 Config config = Utils.getConfig();
200                 String url = String.format(Urls.DELETE_RESOURCE_BY_NAME_AND_VERSION, config.getCatalogBeHost(),
201                                 config.getCatalogBePort(), resourceName, resourceVersion);
202                 RestResponse sendDelete = sendDelete(url, sdncModifierDetails.getUserId());
203
204                 deleteMarkedResources(sdncModifierDetails.getUserId());
205
206                 return sendDelete;
207         }
208
209         public static Boolean deleteResourceByNameAndVersion(String resourceName, String resourceVersion)
210                         throws IOException {
211                 RestResponse deleteResponse = ResourceRestUtils.deleteResourceByNameAndVersion(
212                                 ElementFactory.getDefaultUser(UserRoleEnum.ADMIN), resourceName, resourceVersion);
213                 return checkErrorCode(deleteResponse);
214         }
215
216         public static Boolean removeResource(String resourceId)
217                         throws FileNotFoundException, IOException, ClientProtocolException {
218                 RestResponse response = deleteResource(resourceId,
219                                 ElementFactory.getDefaultUser(UserRoleEnum.ADMIN).getUserId());
220                 return checkErrorCode(response);
221         }
222
223         // ************** GET *************
224         public static RestResponse getResource(User sdncModifierDetails, String uniqueId) throws IOException {
225
226                 Config config = Utils.getConfig();
227                 String url = String.format(Urls.GET_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(), uniqueId);
228                 return sendGet(url, sdncModifierDetails.getUserId());
229         }
230
231         public static RestResponse getModule(User sdncModifierDetails, String componentId, String moduleId)
232                         throws IOException {
233                 Config config = Utils.getConfig();
234                 String url = String.format(Urls.GET_MODULE_BY_ID, config.getCatalogBeHost(), config.getCatalogBePort(),
235                                 componentId, moduleId);
236                 return sendGet(url, sdncModifierDetails.getUserId());
237         }
238
239         public static RestResponse getLatestResourceFromCsarUuid(User sdncModifierDetails, String csarUuid)
240                         throws IOException {
241
242                 Config config = Utils.getConfig();
243                 String url = String.format(Urls.GET_RESOURCE_BY_CSAR_UUID, config.getCatalogBeHost(), config.getCatalogBePort(),
244                                 csarUuid);
245                 return sendGet(url, sdncModifierDetails.getUserId());
246         }
247
248         public static RestResponse getResource(ResourceReqDetails resourceDetails, User sdncModifierDetails)
249                         throws IOException {
250
251                 Config config = Utils.getConfig();
252                 String url = String.format(Urls.GET_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(),
253                                 resourceDetails.getUniqueId());
254                 return sendGet(url, sdncModifierDetails.getUserId());
255         }
256
257         public static RestResponse getResourceLatestVersionListMetadata(User sdncModifierDetails, String internalComponentType) throws IOException {
258
259                 Config config = Utils.getConfig();
260                 StringBuilder sb = new StringBuilder();
261                 String url = String.format(Urls.GET_RESOURCE_METADATA_lATEST_VERSION, config.getCatalogBeHost(),
262                                 config.getCatalogBePort());
263                 sb.append(url);
264                 if (internalComponentType != null && !internalComponentType.isEmpty()) {
265                         sb.append("?internalComponentType="+internalComponentType);
266                 }
267                 return sendGet(sb.toString(), sdncModifierDetails.getUserId());
268
269         }
270
271         public static RestResponse getResourceByNameAndVersion(String userId, String resourceName, String resourceVersion)
272                         throws IOException {
273
274                 Config config = Utils.getConfig();
275                 String url = String.format(Urls.GET_RESOURCE_BY_NAME_AND_VERSION, config.getCatalogBeHost(),
276                                 config.getCatalogBePort(), resourceName, resourceVersion);
277
278                 return sendGet(url, userId);
279         }
280
281         public static RestResponse getResourceList(User sdncModifierDetails) throws IOException {
282
283                 Config config = Utils.getConfig();
284                 String url = String.format(Urls.GET_FOLLWED_LIST, config.getCatalogBeHost(), config.getCatalogBePort());
285
286                 return sendGet(url, sdncModifierDetails.getUserId());
287
288         }
289         
290         public static RestResponse getResourceListFilterByCategory(User sdncModifierDetails, String componentType, String category) throws IOException {
291
292                 Config config = Utils.getConfig();
293                 String url = String.format(Urls.GET_FILTERED_ASSET_LIST, config.getCatalogBeHost(), config.getCatalogBePort(), componentType, "category=" + category);
294                 
295                 Map<String, String> headersMap =  prepareHeadersMap(sdncModifierDetails.getUserId());
296                 headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), authorizationHeader);
297                 headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci");
298
299                 return sendGet(url, sdncModifierDetails.getUserId(), headersMap);
300
301         }
302         
303         public static RestResponse getResourceListFilterByCriteria(User sdncModifierDetails, String componentType, String criteria, String value) throws IOException {
304
305                 Config config = Utils.getConfig();
306                 String url = String.format(Urls.GET_FILTERED_ASSET_LIST, config.getCatalogBeHost(), config.getCatalogBePort(), componentType, criteria + "=" + value);
307                 
308                 Map<String, String> headersMap =  prepareHeadersMap(sdncModifierDetails.getUserId());
309                 headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), authorizationHeader);
310                 headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci");
311
312                 return sendGet(url, sdncModifierDetails.getUserId(), headersMap);
313
314         }
315
316         public static RestResponse getResource(String resourceId) throws ClientProtocolException, IOException {
317                 return getResource(ElementFactory.getDefaultUser(UserRoleEnum.ADMIN), resourceId);
318         }
319
320         public static RestResponse getLatestResourceFromCsarUuid(String csarUuid)
321                         throws ClientProtocolException, IOException {
322                 return getLatestResourceFromCsarUuid(ElementFactory.getDefaultUser(UserRoleEnum.ADMIN), csarUuid);
323         }
324
325         public static RestResponse getResourceLatestVersionList(User sdncModifierDetails) throws IOException {
326
327                 Config config = Utils.getConfig();
328                 String url = String.format(Urls.GET_RESOURCE_lATEST_VERSION, config.getCatalogBeHost(),
329                                 config.getCatalogBePort());
330
331                 return sendGet(url, sdncModifierDetails.getUserId());
332
333         }
334
335         public static RestResponse putAllCategoriesTowardsCatalogFeWithUuidNotAllowed(String uuid) throws IOException {
336
337                 Config config = Utils.getConfig();
338                 String url = String.format(Urls.GET_ALL_CATEGORIES_FE, config.getCatalogFeHost(), config.getCatalogFePort(),
339                                 BaseRestUtils.RESOURCE_COMPONENT_TYPE);
340
341                 Map<String, String> headersMap = new HashMap<String, String>();
342                 headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
343                 headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderData);
344                 headersMap.put(HttpHeaderEnum.X_ECOMP_REQUEST_ID_HEADER.getValue(), uuid);
345                 HttpRequest http = new HttpRequest();
346
347                 logger.debug("Send PUT request to get all categories (should be 405): {}",url);
348                 return http.httpSendByMethod(url, "PUT", null, headersMap);
349         }
350
351         public static RestResponse getAllTagsTowardsCatalogBe() throws IOException {
352
353                 Config config = Utils.getConfig();
354                 HttpRequest http = new HttpRequest();
355                 String url = String.format(Urls.GET_ALL_TAGS, config.getCatalogBeHost(), config.getCatalogBePort());
356
357                 Map<String, String> headersMap = new HashMap<String, String>();
358                 headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
359                 headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderData);
360
361                 return http.httpSendGet(url, headersMap);
362
363         }
364
365         public static RestResponse getAllPropertyScopesTowardsCatalogBe() throws IOException {
366
367                 Config config = Utils.getConfig();
368                 HttpRequest http = new HttpRequest();
369                 String url = String.format(Urls.GET_PROPERTY_SCOPES_LIST, config.getCatalogBeHost(), config.getCatalogBePort());
370
371                 Map<String, String> headersMap = new HashMap<String, String>();
372                 headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json");
373                 headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json");
374                 headersMap.put(HttpHeaderEnum.USER_ID.getValue(), "cs0008");
375
376                 return http.httpSendGet(url, headersMap);
377         }
378
379         public static RestResponse getAllArtifactTypesTowardsCatalogBe() throws IOException {
380
381                 Config config = Utils.getConfig();
382                 HttpRequest http = new HttpRequest();
383                 String url = String.format(Urls.GET_ALL_ARTIFACTS, config.getCatalogBeHost(), config.getCatalogBePort());
384
385                 Map<String, String> headersMap = new HashMap<String, String>();
386
387                 headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json");
388                 headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json");
389                 headersMap.put(HttpHeaderEnum.USER_ID.getValue(), "cs0008");
390
391                 return http.httpSendGet(url, headersMap);
392
393         }
394
395         public static RestResponse getConfigurationTowardsCatalogBe() throws IOException {
396
397                 Config config = Utils.getConfig();
398                 HttpRequest http = new HttpRequest();
399                 String url = String.format(Urls.GET_CONFIGURATION, config.getCatalogBeHost(), config.getCatalogBePort());
400
401                 Map<String, String> headersMap = new HashMap<String, String>();
402                 headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json");
403                 headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json");
404                 headersMap.put(HttpHeaderEnum.USER_ID.getValue(), "cs0008");
405
406                 return http.httpSendGet(url, headersMap);
407
408         }
409         
410         public static RestResponse getResourceFilteredDataByParams(User sdncModifierDetails, String uniqueId , List<String> parameters) throws IOException {
411                 Config config = Utils.getConfig();
412                 String urlGetResourceDataByParams = Urls.GET_RESOURCE_DATA_BY_PARAMS;
413                 String joinedParameters = StringUtils.join(parameters , "&");
414                 String url = String.format(urlGetResourceDataByParams + joinedParameters , config.getCatalogBeHost(), config.getCatalogBePort(), uniqueId);
415                 return sendGet(url, sdncModifierDetails.getUserId());
416                 
417         }
418
419
420         public static RestResponse sendOptionsTowardsCatalogFeWithUuid() throws IOException {
421
422                 Config config = Utils.getConfig();
423                 String url = String.format(Urls.GET_ALL_CATEGORIES_FE, config.getCatalogFeHost(), config.getCatalogFePort(),
424                                 BaseRestUtils.RESOURCE_COMPONENT_TYPE);
425
426                 Map<String, String> headersMap = new HashMap<String, String>();
427                 headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
428                 headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderData);
429                 HttpRequest http = new HttpRequest();
430
431                 logger.debug("Send OPTIONS request for categories: {}",url);
432                 return http.httpSendByMethod(url, "OPTIONS", null, headersMap);
433         }
434
435         // ********** UPDATE *************
436         public static RestResponse updateResourceMetadata(ResourceReqDetails updatedResourceDetails,
437                         User sdncModifierDetails, String uniqueId, String encoding) throws Exception {
438                 Config config = Utils.getConfig();
439                 String url = String.format(Urls.UPDATE_RESOURCE_METADATA, config.getCatalogBeHost(), config.getCatalogBePort(),
440                                 uniqueId);
441
442                 String ContentTypeString = String.format("%s;%s", contentTypeHeaderData, encoding);
443
444                 Gson gson = new Gson();
445                 String userBodyJson = gson.toJson(updatedResourceDetails);
446                 String userId = sdncModifierDetails.getUserId();
447
448                 RestResponse updateResourceResponse = sendPut(url, userBodyJson, userId, ContentTypeString);
449
450                 updatedResourceDetails.setVersion(ResponseParser.getVersionFromResponse(updateResourceResponse));
451                 updatedResourceDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(updateResourceResponse));
452
453                 return updateResourceResponse;
454         }
455
456         public static RestResponse updateResourceTEST(Resource resource, User sdncModifierDetails, String uniqueId,
457                         String encoding) throws Exception {
458                 Config config = Utils.getConfig();
459                 String url = String.format(Urls.UPDATE_RESOURCE_METADATA, config.getCatalogBeHost(), config.getCatalogBePort(),
460                                 uniqueId);
461
462                 String ContentTypeString = String.format("%s;%s", contentTypeHeaderData, encoding);
463
464                 Gson gson = new Gson();
465                 String userBodyJson = gson.toJson(resource);
466                 String userId = sdncModifierDetails.getUserId();
467
468                 RestResponse updateResourceResponse = sendPut(url, userBodyJson, userId, ContentTypeString);
469
470                 // String resourceUniqueId =
471                 // ResponseParser.getValueFromJsonResponse(updateResourceResponse.getResponse(),
472                 // "uniqueId");
473                 // updatedResourceDetails.setUniqueId(resourceUniqueId);
474                 // String resourceVersion =
475                 // ResponseParser.getValueFromJsonResponse(updateResourceResponse.getResponse(),
476                 // "version");
477                 // updatedResourceDetails.setUniqueId(resourceVersion);
478
479                 return updateResourceResponse;
480         }
481
482         public static RestResponse updateResourceMetadata(ResourceReqDetails updatedResourceDetails,
483                         User sdncModifierDetails, String uniqueId) throws Exception {
484                 return updateResourceMetadata(updatedResourceDetails, sdncModifierDetails, uniqueId, "");
485         }
486
487         public static RestResponse updateResourceMetadata(String json, User sdncModifierDetails, String resourceId)
488                         throws IOException {
489                 Config config = Utils.getConfig();
490                 String url = String.format(Urls.UPDATE_RESOURCE_METADATA, config.getCatalogBeHost(), config.getCatalogBePort(),
491                                 resourceId);
492                 String userId = sdncModifierDetails.getUserId();
493
494                 RestResponse updateResourceResponse = sendPut(url, json, userId, contentTypeHeaderData);
495
496                 return updateResourceResponse;
497         }
498
499         public static RestResponse updateResource(ResourceReqDetails resourceDetails, User sdncModifierDetails,
500                         String resourceId) throws IOException {
501
502                 String userId = sdncModifierDetails.getUserId();
503                 Config config = Utils.getConfig();
504                 String url = String.format(Urls.UPDATE_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(),
505                                 resourceId);
506
507                 Map<String, String> headersMap = prepareHeadersMap(userId);
508
509                 Gson gson = new Gson();
510                 String userBodyJson = gson.toJson(resourceDetails);
511                 String calculateMD5 = GeneralUtility.calculateMD5Base64EncodedByString(userBodyJson);
512                 headersMap.put(HttpHeaderEnum.Content_MD5.getValue(), calculateMD5);
513                 HttpRequest http = new HttpRequest();
514                 RestResponse updateResourceResponse = http.httpSendPut(url, userBodyJson, headersMap);
515                 if (updateResourceResponse.getErrorCode() == STATUS_CODE_UPDATE_SUCCESS) {
516                         resourceDetails.setUUID(ResponseParser.getUuidFromResponse(updateResourceResponse));
517                         resourceDetails.setVersion(ResponseParser.getVersionFromResponse(updateResourceResponse));
518                         resourceDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(updateResourceResponse));
519                         String lastUpdaterUserId = ResponseParser.getValueFromJsonResponse(updateResourceResponse.getResponse(),
520                                         "lastUpdaterUserId");
521                         resourceDetails.setLastUpdaterUserId(lastUpdaterUserId);
522                         String lastUpdaterFullName = ResponseParser.getValueFromJsonResponse(updateResourceResponse.getResponse(),
523                                         "lastUpdaterFullName");
524                         resourceDetails.setLastUpdaterFullName(lastUpdaterFullName);
525                         resourceDetails.setCreatorUserId(userId);
526                         resourceDetails.setCreatorFullName(sdncModifierDetails.getFullName());
527                 }
528                 return updateResourceResponse;
529         }
530
531         public static RestResponse createResourceInstance(ResourceReqDetails resourceDetails, User modifier,
532                         String vfResourceUniqueId) throws Exception {
533                 ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory
534                                 .getComponentResourceInstance(resourceDetails);
535                 RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
536                                 resourceInstanceReqDetails, modifier, vfResourceUniqueId, ComponentTypeEnum.RESOURCE);
537                 ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
538                 return createResourceInstanceResponse;
539         }
540
541         public static RestResponse associateResourceInstances(JSONObject body, User sdncModifierDetails,
542                         Component component) throws IOException {
543
544                 Config config = Utils.getConfig();
545                 Gson gson = new Gson();
546                 String bodyJson = gson.toJson(body);
547                 component.getComponentType();
548                 String componentType = ComponentTypeEnum.findParamByType(component.getComponentType());
549                 String url = String.format(Urls.ASSOCIATE_RESOURCE_INSTANCE, config.getCatalogBeHost(),
550                                 config.getCatalogBePort(), componentType, component.getUniqueId());
551                 return sendPost(url, bodyJson, sdncModifierDetails.getUserId(), null);
552
553         }
554
555         public static RestResponse getFollowedList(User sdncModifierDetails) throws Exception {
556                 Config config = Utils.getConfig();
557                 String url = String.format(Urls.GET_FOLLWED_LIST, config.getCatalogBeHost(), config.getCatalogBePort());
558                 return sendGet(url, sdncModifierDetails.getUserId());
559         }
560
561         public static List<Resource> restResponseToResourceObjectList(String restResponse) {
562                 JsonElement jelement = new JsonParser().parse(restResponse);
563                 JsonArray jsonArray = jelement.getAsJsonArray();
564                 List<Resource> restResponseArray = new ArrayList<>();
565                 Resource resource = null;
566                 for (int i = 0; i < jsonArray.size(); i++) {
567                         String resourceString = (String) jsonArray.get(i).toString();
568                         resource = ResponseParser.convertResourceResponseToJavaObject(resourceString);
569                         restResponseArray.add(resource);
570                 }
571
572                 return restResponseArray;
573
574         }
575
576         public static Resource getResourceObjectFromResourceListByUid(List<Resource> resourceList, String uid) {
577                 if (resourceList != null && resourceList.size() > 0) {
578                         for (Resource resource : resourceList) {
579                                 if (resource.getUniqueId().equals(uid))
580                                         return resource;
581                         }
582                 } else
583                         return null;
584                 return null;
585         }
586
587         // =======================================resource
588         // associate==================================================
589         public static RestResponse associate2ResourceInstances(Component container, ComponentInstance fromNode,
590                         ComponentInstance toNode, String assocType, User sdncUserDetails) throws IOException {
591                 return associate2ResourceInstances(container, fromNode.getUniqueId(), toNode.getUniqueId(), assocType,
592                                 sdncUserDetails);
593         }
594
595         public static RestResponse associate2ResourceInstances(Component component, String fromNode, String toNode,
596                         String assocType, User sdncUserDetails) throws IOException {
597
598                 RelationshipInstData relationshipInstData = new RelationshipInstData();
599                 Map<String, List<CapabilityDefinition>> capabilitiesMap = component.getCapabilities();
600                 Map<String, List<RequirementDefinition>> requirementMap = component.getRequirements();
601                 List<CapabilityDefinition> capabilitiesList = capabilitiesMap.get(assocType);
602                 List<RequirementDefinition> requirementList = requirementMap.get(assocType);
603
604                 RequirementDefinition requirementDefinitionFrom = getRequirementDefinitionByOwnerId(requirementList, fromNode);
605                 CapabilityDefinition capabilityDefinitionTo = getCapabilityDefinitionByOwnerId(capabilitiesList, toNode);
606                 relationshipInstData.setCapabilityOwnerId(capabilityDefinitionTo.getOwnerId());
607                 relationshipInstData.setCapabiltyId(capabilityDefinitionTo.getUniqueId());
608                 relationshipInstData.setRequirementOwnerId(requirementDefinitionFrom.getOwnerId());
609                 relationshipInstData.setRequirementId(requirementDefinitionFrom.getUniqueId());
610
611                 JSONObject assocBody = assocBuilder(relationshipInstData, capabilityDefinitionTo, requirementDefinitionFrom,
612                                 toNode, fromNode);
613                 return ResourceRestUtils.associateResourceInstances(assocBody, sdncUserDetails, component);
614
615         }
616
617         private static JSONObject assocBuilder(RelationshipInstData relationshipInstData,
618                         CapabilityDefinition capabilityDefinitionTo, RequirementDefinition requirementDefinitionFrom, String toNode,
619                         String fromNode) {
620
621                 String type = capabilityDefinitionTo.getType();
622                 String requirement = requirementDefinitionFrom.getName();
623                 String capability = requirementDefinitionFrom.getName();
624
625                 JSONObject wrapper = new JSONObject();
626                 JSONArray relationshipsArray = new JSONArray();
627                 JSONObject relationship = new JSONObject();
628                 JSONObject simpleObject = new JSONObject();
629
630                 relationship.put("type", type);
631                 simpleObject.put("relationship", relationship);
632                 simpleObject.put("requirement", requirement);
633                 simpleObject.put("capability", capability);
634                 simpleObject.put("capabilityUid", relationshipInstData.getCapabiltyId());
635                 simpleObject.put("capabilityOwnerId", relationshipInstData.getCapabilityOwnerId());
636                 simpleObject.put("requirementOwnerId", relationshipInstData.getRequirementOwnerId());
637                 simpleObject.put("requirementUid", relationshipInstData.getRequirementId());
638                 relationshipsArray.add(simpleObject);
639
640                 ArrayList<Object> relationships = new ArrayList<Object>(relationshipsArray);
641                 wrapper.put("fromNode", fromNode);
642                 wrapper.put("toNode", toNode);
643                 wrapper.put("relationships", relationships);
644                 return wrapper;
645
646         }
647
648         private static CapabilityDefinition getCapabilityDefinitionByOwnerId(
649                         List<CapabilityDefinition> capabilityDefinitionList, String ownerId) {
650
651                 for (CapabilityDefinition capabilityDefinition : capabilityDefinitionList) {
652                         if (capabilityDefinition.getOwnerId().equals(ownerId)) {
653                                 return capabilityDefinition;
654                         }
655                 }
656                 return null;
657         }
658
659         private static RequirementDefinition getRequirementDefinitionByOwnerId(
660                         List<RequirementDefinition> requirementDefinitionList, String ownerId) {
661
662                 for (RequirementDefinition requirementDefinition : requirementDefinitionList) {
663                         if (requirementDefinition.getOwnerId().equals(ownerId)) {
664                                 return requirementDefinition;
665                         }
666                 }
667                 return null;
668         }
669
670         public static String getRiUniqueIdByRiName(Component component, String resourceInstanceName) {
671
672                 List<ComponentInstance> componentInstances = component.getComponentInstances();
673                 String name = null;
674                 for (ComponentInstance componentInstance : componentInstances) {
675                         if (componentInstance.getName().equals(resourceInstanceName)) {
676                                 name = componentInstance.getUniqueId();
677                                 break;
678                         }
679                 }
680                 return name;
681         }
682
683         public static Resource convertResourceGetResponseToJavaObject(ResourceReqDetails resourceDetails)
684                         throws IOException {
685                 RestResponse response = ResourceRestUtils.getResource(resourceDetails,
686                                 ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
687                 assertEquals("Check response code after get resource", 200, response.getErrorCode().intValue());
688                 return ResponseParser.convertResourceResponseToJavaObject(response.getResponse());
689         }
690
691         public static RestResponse changeResourceInstanceVersion(String containerUniqueId, String instanceToReplaceUniqueId,
692                         String newResourceUniqueId, User sdncModifierDetails, ComponentTypeEnum componentType) throws IOException {
693                 return ProductRestUtils.changeServiceInstanceVersion(containerUniqueId, instanceToReplaceUniqueId,
694                                 newResourceUniqueId, sdncModifierDetails, componentType);
695         }
696         
697         public static Resource importResourceFromCsar(String csarName) throws Exception{
698                 User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
699                 String payloadName = csarName;
700                 ImportReqDetails resourceDetails = ElementFactory.getDefaultImportResource();
701                 String rootPath = System.getProperty("user.dir");
702                 Path path = null;
703                 byte[] data = null;
704                 
705                 String payloadData = null;
706
707                 path = Paths.get(rootPath + CSARS_PATH + csarName);
708                 data = Files.readAllBytes(path);
709                 payloadData = Base64.encodeBase64String(data);
710                 resourceDetails.setPayloadData(payloadData);
711
712                 // create new resource from Csar
713                 resourceDetails.setCsarUUID(payloadName);
714                 resourceDetails.setPayloadName(payloadName);
715                 resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
716                 RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
717                 BaseRestUtils.checkCreateResponse(createResource);
718                 Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
719                 return resource;
720                 
721                 // add to restResourceUtil
722         }
723
724
725 }