diff options
Diffstat (limited to 'asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest')
19 files changed, 5664 insertions, 0 deletions
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ArtifactRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ArtifactRestUtils.java new file mode 100644 index 0000000000..4360621364 --- /dev/null +++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ArtifactRestUtils.java @@ -0,0 +1,689 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.utils.rest; + +import static org.testng.AssertJUnit.assertNotNull; +import static org.testng.AssertJUnit.assertTrue; + +import java.io.IOException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.codec.binary.Base64; +import org.json.simple.JSONObject; +import org.json.simple.JSONValue; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.api.Urls; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum; +import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.utils.Utils; +import org.openecomp.sdc.ci.tests.utils.general.ElementFactory; +import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; +import org.openecomp.sdc.common.util.ValidationUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.AssertJUnit; + +import com.google.gson.Gson; + +public class ArtifactRestUtils extends BaseRestUtils { + private static Logger logger = LoggerFactory.getLogger(ArtifactRestUtils.class.getName()); + + // External API + // Upload Artifact of the asset + public static RestResponse externalAPIUploadArtifactOfTheAsset(Component component, User user, ArtifactReqDetails artifactReqDetails) throws IOException { + Config config = Utils.getConfig(); + String resourceType = null; + String resourceUUID = component.getUUID(); + + System.out.println(component.getComponentType()); + + if (component.getComponentType().toString().toLowerCase().equals("resource")) { + resourceType = "resources"; + } else { + resourceType = "services"; + } + + String url = String.format(Urls.POST_EXTERNAL_API_UPLOAD_ARTIFACT_OF_ASSET, config.getCatalogBeHost(), config.getCatalogBePort(), resourceType, resourceUUID); + + return uploadInformationalArtifact(artifactReqDetails, user, calculateChecksum(artifactReqDetails), url); + } + + // + // Testing + // + public static RestResponse getResourceDeploymentArtifactExternalAPI(String resourceUUID, String artifactUUID, User sdncModifierDetails, String resourceType) throws IOException { + Config config = Utils.getConfig(); + String url = null; + + if (resourceType.equals("Service")) { + url = String.format(Urls.GET_DOWNLOAD_SERVICE_ARTIFACT_OF_ASSET, config.getCatalogBeHost(), config.getCatalogBePort(), resourceUUID, artifactUUID); + + } else { + url = String.format(Urls.GET_DOWNLOAD_RESOURCE_ARTIFACT_OF_ASSET, config.getCatalogBeHost(), config.getCatalogBePort(), resourceUUID, artifactUUID); + } + + Map<String, String> headersMap = new HashMap<String, String>(); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId()); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), authorizationHeader); + headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci"); + + HttpRequest http = new HttpRequest(); + + logger.debug("Send GET request to get Resource Assets: {}", url); + System.out.println("Send GET request to get Resource Assets: " + url); + + logger.debug("Request headers: {}", headersMap); + System.out.println("Request headers: " + headersMap); + + RestResponse sendGetResourceAssets = http.httpSendGet(url, headersMap); + + return sendGetResourceAssets; + + } + + public static RestResponse getComponentInstanceDeploymentArtifactExternalAPI(String resourceUUID, String componentInstanceUID, String artifactUUID, User sdncModifierDetails, String resourceType) throws IOException { + Config config = Utils.getConfig(); + String url = null; + + if (resourceType.equals("Service")) { + url = String.format(Urls.GET_DOWNLOAD_SERVICE_ARTIFACT_OF_COMPONENT_INSTANCE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceUUID, componentInstanceUID, artifactUUID); + + } else { + url = String.format(Urls.GET_DOWNLOAD_RESOURCE_ARTIFACT_OF_COMPONENT_INSTANCE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceUUID, componentInstanceUID, artifactUUID); + } + + Map<String, String> headersMap = new HashMap<String, String>(); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId()); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), authorizationHeader); + headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci"); + + HttpRequest http = new HttpRequest(); + + logger.debug("Send GET request to get Resource Assets: {}", url); + System.out.println("Send GET request to get Resource Assets: " + url); + + logger.debug("Request headers: {}", headersMap); + System.out.println("Request headers: " + headersMap); + + RestResponse sendGetResourceAssets = http.httpSendGet(url, headersMap); + + return sendGetResourceAssets; + + } + + // *********** SERVICE **************** + public static RestResponse getArtifactTypesList() throws IOException { + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_ALL_ARTIFACTS, config.getCatalogBeHost(), config.getCatalogBePort()); + + return sendGet(url, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER).getUserId()); + } + + public static RestResponse addInformationalArtifactToService(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String serviceUid) throws IOException { + return addInformationalArtifactToService(artifactDetails, sdncModifierDetails, serviceUid, calculateChecksum(artifactDetails)); + } + + public static RestResponse addInformationalArtifactToService(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String serviceUid, String checksum) throws IOException { + Config config = Utils.getConfig(); + String url = String.format(Urls.ADD_ARTIFACT_TO_SERVICE, config.getCatalogBeHost(), config.getCatalogBePort(), serviceUid); + + return uploadInformationalArtifact(artifactDetails, sdncModifierDetails, checksum, url); + } + + public static RestResponse downloadServiceArtifact(ServiceReqDetails service, ArtifactReqDetails artifact, User user, Map<String, String> addionalHeaders) throws Exception { + + return downloadServiceArtifact(service, artifact, user, addionalHeaders, true); + } + + public static RestResponse downloadServiceArtifact(ServiceReqDetails service, ArtifactReqDetails artifact, User user, Map<String, String> addionalHeaders, boolean addEcompHeader) throws Exception { + Config config = Utils.getConfig(); + String relativeUrl = encodeUrlForDownload( + String.format(Urls.DISTRIB_DOWNLOAD_SERVICE_ARTIFACT_RELATIVE_URL, ValidationUtils.convertToSystemName(service.getName()), service.getVersion(), ValidationUtils.normalizeFileName(artifact.getArtifactName()))); + String fullUrl = String.format(Urls.DOWNLOAD_SERVICE_ARTIFACT_FULL_URL, config.getCatalogBeHost(), config.getCatalogBePort(), relativeUrl); + + return downloadArtifact(fullUrl, user, addionalHeaders, addEcompHeader); + } + + public static RestResponse downloadResourceArtifact(ServiceReqDetails service, ResourceReqDetails resource, ArtifactReqDetails artifact, User user, Map<String, String> addionalHeaders) throws Exception { + return downloadResourceArtifact(service, resource, artifact, user, addionalHeaders, true); + } + + public static RestResponse downloadResourceArtifact(ServiceReqDetails service, ResourceReqDetails resource, ArtifactReqDetails artifact, User user, Map<String, String> addionalHeaders, boolean addEcompHeader) throws Exception { + Config config = Utils.getConfig(); + String relativeUrl = encodeUrlForDownload(String.format(Urls.DISTRIB_DOWNLOAD_RESOURCE_ARTIFACT_RELATIVE_URL, ValidationUtils.convertToSystemName(service.getName()), service.getVersion(), + ValidationUtils.convertToSystemName(resource.getName()), resource.getVersion(), ValidationUtils.normalizeFileName(artifact.getArtifactName()))); + String fullUrl = String.format(Urls.DOWNLOAD_RESOURCE_ARTIFACT_FULL_URL, config.getCatalogBeHost(), config.getCatalogBePort(), relativeUrl); + + return downloadArtifact(fullUrl, user, addionalHeaders, addEcompHeader); + } + + public static RestResponse downloadResourceInstanceArtifact(String serviceUniqueId, String resourceInstanceId, User user, String artifactUniqeId) throws Exception { + Config config = Utils.getConfig(); + String url = String.format(Urls.DOWNLOAD_COMPONENT_INSTANCE_ARTIFACT, config.getCatalogBeHost(), config.getCatalogBePort(), serviceUniqueId, resourceInstanceId, artifactUniqeId); + RestResponse res = sendGet(url, user.getUserId(), null); + return res; + } + + //// + + // update + + public static RestResponse updateInformationalArtifactOfServiceByMethod(ArtifactReqDetails artifactReqDetails, String serviceUid, String artifactUid, User sdncModifierDetails, String httpMethod) throws IOException { + // TODO Auto-generated method stub + return updateInformationalArtifactOfServiceByMethod(artifactReqDetails, serviceUid, artifactUid, sdncModifierDetails, httpMethod, calculateChecksum(artifactReqDetails)); + } + + public static RestResponse updateInformationalArtifactOfServiceByMethod(ArtifactReqDetails artifactReqDetails, String serviceUid, User sdncModifierDetails, String httpMethod) throws IOException { + // TODO Auto-generated method stub + return updateInformationalArtifactOfServiceByMethod(artifactReqDetails, serviceUid, artifactReqDetails.getUniqueId(), sdncModifierDetails, httpMethod, calculateChecksum(artifactReqDetails)); + } + + public static RestResponse downloadResourceArtifactInternalApi(String resourceId, User user, String artifactUniqeId) throws Exception { + return downloadComponentArtifactInternalApi(resourceId, user, artifactUniqeId, Urls.UI_DOWNLOAD_RESOURCE_ARTIFACT); + } + + public static RestResponse downloadServiceArtifactInternalApi(String componentId, User user, String artifactUniqeId) throws Exception { + return downloadComponentArtifactInternalApi(componentId, user, artifactUniqeId, Urls.UI_DOWNLOAD_SERVICE_ARTIFACT); + } + + public static RestResponse downloadComponentArtifactInternalApi(String componentId, User user, String artifactUniqeId, String urlTemplate) throws Exception { + Config config = Utils.getConfig(); + String url = String.format(urlTemplate, config.getCatalogBeHost(), config.getCatalogBePort(), componentId, artifactUniqeId); + RestResponse res = sendGet(url, user.getUserId(), null); + return res; + } + + /* + * public static RestResponse updateInformationalArtifactPayloadOfService(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String serviceUid, String artifactUid, String checksum) throws IOException { return + * updateInformationalArtifactOfService(artifactDetails, sdncModifierDetails, serviceUid, artifactUid, checksum, true); } + * + * public static RestResponse updateInformationalArtifactMetadataOfService(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String serviceUid, String artifactUid) throws IOException { return + * updateInformationalArtifactOfService(artifactDetails, sdncModifierDetails, serviceUid, artifactUid, calculateChecksum(artifactDetails), false); } + * + * public static RestResponse updateInformationalArtifactOfService(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String serviceUid, String artifactUid, String checksum, boolean isPayloadUpdate) throws IOException { Config config = + * Utils.getConfig(); Map<String, String> headersMap = getHeadersMap(sdncModifierDetails); + * + * if (isPayloadUpdate){ headersMap.put(HttpHeaderEnum.Content_MD5.getValue(), checksum); } + * + * Gson gson = new Gson(); String jsonBody = gson.toJson(artifactDetails); + * + * HttpRequest http = new HttpRequest(); + * + * String url = String.format(Urls.UPDATE_OR_DELETE_ARTIFACT_OF_SERVICE, config.getCatalogBeHost(),config.getCatalogBePort(), serviceUid, artifactUid); RestResponse res = http.httpSendPost(url, jsonBody, headersMap); + * System.out.println("update artifact was finished with response: "+ res.getErrorCode()); return res; } + */ + + public static RestResponse updateInformationalArtifactOfServiceByMethod(ArtifactReqDetails artifactReqDetails, String serviceUid, String artifactUid, User sdncModifierDetails, String httpMethod, String checksum) throws IOException { + Config config = Utils.getConfig(); + + Map<String, String> headersMap = getHeadersMap(sdncModifierDetails); + headersMap.put(HttpHeaderEnum.Content_MD5.getValue(), checksum); + + Gson gson = new Gson(); + String userBodyJson = gson.toJson(artifactReqDetails); + + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.UPDATE_OR_DELETE_ARTIFACT_OF_SERVICE, config.getCatalogBeHost(), config.getCatalogBePort(), serviceUid, artifactUid); + RestResponse updateResourceResponse = http.httpSendByMethod(url, httpMethod, userBodyJson, headersMap); + // System.out.println("update artifact was finished with response: "+ + // updateResourceResponse.getErrorCode()); + + return updateResourceResponse; + } + + public static Map<String, String> getHeadersMap(User sdncModifierDetails) { + Map<String, String> headersMap = new HashMap<String, String>(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptJsonHeader); + + try { + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId()); + } catch (Exception e) { + + } + + return headersMap; + } + + // *********** RESOURCE **************** + // add + public static RestResponse addInformationalArtifactToResource(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String resourceUid) throws IOException { + return addInformationalArtifactToResource(artifactDetails, sdncModifierDetails, resourceUid, calculateChecksum(artifactDetails)); + } + + public static RestResponse explicitAddInformationalArtifactToResource(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String resourceUid) throws IOException { + Config config = Utils.getConfig(); + + String url = String.format(Urls.ADD_ARTIFACT_TO_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceUid); + + return uploadInformationalArtifact(artifactDetails, sdncModifierDetails, calculateChecksum(artifactDetails), url); + } + + public static RestResponse addInformationalArtifactToResource(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String resourceUid, String checksum) throws IOException { + Config config = Utils.getConfig(); + + if (artifactDetails.getArtifactGroupType() != null && artifactDetails.getArtifactGroupType().equals(ArtifactGroupTypeEnum.DEPLOYMENT.getType())) { + // YANG_XML and OTHER deployment artifact should be added through + // this API, not updated + String artifactType = artifactDetails.getArtifactType(); + if (!(ArtifactTypeEnum.YANG_XML.getType().equals(artifactType) || ArtifactTypeEnum.OTHER.getType().equals(artifactType) || ArtifactTypeEnum.VNF_CATALOG.getType().equals(artifactType) + || ArtifactTypeEnum.VF_LICENSE.getType().equals(artifactType) || ArtifactTypeEnum.VENDOR_LICENSE.getType().equals(artifactType) || ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType().equals(artifactType) + || ArtifactTypeEnum.MODEL_QUERY_SPEC.getType().equals(artifactType) || ArtifactTypeEnum.APPC_CONFIG.getType().equals(artifactType))) { + // return updateInformationalArtifactToResource(artifactDetails, + // sdncModifierDetails, resourceUid); + } + } + String url = String.format(Urls.ADD_ARTIFACT_TO_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceUid); + + return uploadInformationalArtifact(artifactDetails, sdncModifierDetails, checksum, url); + } + + // update + public static RestResponse updateInformationalArtifactToResource(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String resourceUid) throws IOException { + return updateInformationalArtifactToResource(artifactDetails, sdncModifierDetails, resourceUid, calculateChecksum(artifactDetails)); + } + + public static RestResponse updateInformationalArtifactToResource(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String resourceUid, String checksum) throws IOException { + Config config = Utils.getConfig(); + if (artifactDetails.getArtifactGroupType() != null && artifactDetails.getArtifactGroupType().equals("DEPLOYMENT")) { + RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceUid); + Resource resourceRespJavaObject = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse()); + Map<String, ArtifactDefinition> deploymentArtifacts = resourceRespJavaObject.getDeploymentArtifacts(); + ArtifactDefinition artifactDefinition = deploymentArtifacts.get(artifactDetails.getArtifactLabel()); + artifactDetails.setUniqueId(artifactDefinition.getUniqueId()); + artifactDetails.setArtifactLabel(artifactDefinition.getArtifactLabel()); + + } + + String url = String.format(Urls.UPDATE_OR_DELETE_ARTIFACT_OF_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceUid, artifactDetails.getUniqueId()); + + return uploadInformationalArtifact(artifactDetails, sdncModifierDetails, calculateChecksum(artifactDetails), url); + } + + public static RestResponse uploadArtifactToPlaceholderOnResource(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String resourceUid, String placeHolderLabel) throws IOException { + Config config = Utils.getConfig(); + if (artifactDetails.getArtifactLabel() != null && !artifactDetails.getArtifactLabel().isEmpty()) { + RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceUid); + Resource resourceRespJavaObject = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse()); + Map<String, ArtifactDefinition> deploymentArtifacts = resourceRespJavaObject.getDeploymentArtifacts(); + ArtifactDefinition artifactDefinition = deploymentArtifacts.get(artifactDetails.getArtifactLabel()); + AssertJUnit.assertNotNull(artifactDefinition); + artifactDetails.setUniqueId(artifactDefinition.getUniqueId()); + artifactDetails.setArtifactLabel(artifactDefinition.getArtifactLabel()); + + } + + String url = String.format(Urls.UPDATE_OR_DELETE_ARTIFACT_OF_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceUid, artifactDetails.getUniqueId()); + + return uploadInformationalArtifact(artifactDetails, sdncModifierDetails, calculateChecksum(artifactDetails), url); + } + + public static RestResponse updateDeploymentArtifactToResource(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String resourceUid) throws IOException { + Config config = Utils.getConfig(); + String url = String.format(Urls.UPDATE_OR_DELETE_ARTIFACT_OF_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceUid, artifactDetails.getUniqueId()); + + return updateDeploymentArtifact(artifactDetails, sdncModifierDetails, url); + } + + public static RestResponse updateArtifactToResourceInstance(ArtifactDefinition artifactDefinition, User sdncModifierDetails, String resourceInstanceId, String serviceId) throws IOException { + Config config = Utils.getConfig(); + String url = String.format(Urls.UPDATE_RESOURCE_INSTANCE_ARTIFACT, config.getCatalogBeHost(), config.getCatalogBePort(), serviceId, resourceInstanceId, artifactDefinition.getUniqueId()); + return updateDeploymentArtifact(artifactDefinition, sdncModifierDetails, url); + } + + public static RestResponse updateDeploymentArtifactToRI(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String resourceInstanceId, String serviceId) throws IOException { + Config config = Utils.getConfig(); + String url = String.format(Urls.UPDATE_RESOURCE_INSTANCE_HEAT_ENV_PARAMS, config.getCatalogBeHost(), config.getCatalogBePort(), serviceId, resourceInstanceId, artifactDetails.getUniqueId()); + return updateDeploymentArtifact(artifactDetails, sdncModifierDetails, url); + } + + // delete + public static RestResponse deleteArtifactFromResourceInstance(ArtifactDefinition artifactDefinition, User sdncModifierDetails, String resourceUid, String serviceId) throws IOException { + Config config = Utils.getConfig(); + String url = String.format(Urls.DELETE_RESOURCE_INSTANCE_ARTIFACT, config.getCatalogBeHost(), config.getCatalogBePort(), serviceId, resourceUid, artifactDefinition.getUniqueId()); + return sendDelete(url, sdncModifierDetails.getUserId()); + } + + public static RestResponse deleteInformationalArtifactFromResource(String resourceUid, ArtifactReqDetails artifactDetails, User sdncModifierDetails) throws IOException { + return deleteInformationalArtifactFromResource(resourceUid, artifactDetails.getUniqueId(), sdncModifierDetails); + } + + public static RestResponse deleteInformationalArtifactFromResource(String resourceUid, String artifactId, User sdncModifierDetails) throws IOException { + Config config = Utils.getConfig(); + String url = String.format(Urls.UPDATE_OR_DELETE_ARTIFACT_OF_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceUid, artifactId); + return sendDelete(url, sdncModifierDetails.getUserId()); + } + + public static RestResponse deleteServiceApiArtifact(ArtifactReqDetails artifactDetails, String serviceUniqueId, User user) throws Exception { + Config config = Utils.getConfig(); + String url = String.format(Urls.UPDATE_DELETE_SERVICE_API_ARTIFACT, config.getCatalogBeHost(), config.getCatalogBePort(), serviceUniqueId, artifactDetails.getUniqueId()); + RestResponse res = sendDelete(url, user.getUserId()); + logger.debug("Deleting api artifact was finished with response: {}", res.getErrorCode()); + logger.debug("Response body: {}", res.getResponseMessage()); + return res; + } + + // *************** RESOURCE INSTANCE ************** + /** + * Add DCAE artifacts to resource instance. + * + * @param artifactDetails + * @param sdncModifierDetails + * @param resourceInstanceId + * @param serviceId + * @return + * @throws IOException + */ + public static RestResponse addArtifactToResourceInstance(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String resourceInstanceId, String serviceId) throws IOException { + Config config = Utils.getConfig(); + String url = String.format(Urls.ADD_RESOURCE_INSTANCE_ARTIFACT, config.getCatalogBeHost(), config.getCatalogBePort(), serviceId, resourceInstanceId, artifactDetails.getUniqueId()); + return addArtifactToInstance(artifactDetails, sdncModifierDetails, calculateChecksum(artifactDetails), url); + } + + // *************** COMPONENT ************** + + public static RestResponse uploadDeploymentArtifact(ArtifactReqDetails artifactDetails, Component component, User sdncModifierDetails) throws IOException { + Config config = Utils.getConfig(); + Map<String, String> additionalHeaders = null; + String checksum = ResponseParser.calculateMD5Header(artifactDetails); + additionalHeaders = new HashMap<String, String>(); + additionalHeaders.put(HttpHeaderEnum.Content_MD5.getValue(), checksum); + + ComponentTypeEnum componentType = component.getComponentType(); + + String url = null; + + switch (componentType) { + + case RESOURCE: { + url = String.format(Urls.UPDATE_OR_DELETE_ARTIFACT_OF_SERVICE, config.getCatalogBeHost(), config.getCatalogBePort(), component.getUniqueId(), artifactDetails.getUniqueId()); + + break; + } + case SERVICE: { + + break; + } + + case PRODUCT: { + + break; + } + + default: {// dummy + assertTrue("failed on enum selection", false); + + break; + } + } + + Gson gson = new Gson(); + String jsonBody = gson.toJson(artifactDetails); + // System.out.println("ArtifactDetails: "+ jsonBody); + + RestResponse res = sendPost(url, jsonBody, sdncModifierDetails.getUserId(), acceptHeaderData, additionalHeaders); + if (res.getErrorCode() == STATUS_CODE_SUCCESS) { + artifactDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(res)); + } + // System.out.println("Add artifact was finished with response: "+ + // res.getErrorCode()); + return res; + } + + public static RestResponse uploadArtifact(ArtifactReqDetails artifactDetails, Component component, User sdncModifierDetails) throws IOException { + Config config = Utils.getConfig(); + List<String> placeHolderlst = Utils.getListOfResPlaceHoldersDepArtTypes(); + Map<String, String> additionalHeaders = null; + String checksum = null; + String url = null; + // + // + // if (artifactDetails.getArtifactGroupType() != null + // && artifactDetails.getArtifactGroupType().equals("DEPLOYMENT") + // && placeHolderlst.contains(artifactDetails.getArtifactType())) { + // Map<String, ArtifactDefinition> deploymentArtifacts = + // component.getDeploymentArtifacts(); + // ArtifactDefinition artifactDefinition = + // deploymentArtifacts.get(artifactDetails.getArtifactLabel()); + // artifactDetails.setUniqueId(artifactDefinition.getUniqueId()); + // artifactDetails.setArtifactLabel(artifactDefinition.getArtifactLabel()); + // checksum = ResponseParser.calculateMD5Header(artifactDetails); + // additionalHeaders = new HashMap<String, String>(); + // additionalHeaders.put(HttpHeaderEnum.Content_MD5.getValue(), + // checksum); + // url = String.format(Urls.UPDATE_ARTIFACT_OF_COMPONENT, + // config.getCatalogBeHost(), + // config.getCatalogBePort(), + // ComponentTypeEnum.findParamByType(component.getComponentType()), + // component.getUniqueId(), artifactDetails.getUniqueId()); + // } + // + // else { + checksum = ResponseParser.calculateMD5Header(artifactDetails); + additionalHeaders = new HashMap<String, String>(); + additionalHeaders.put(HttpHeaderEnum.Content_MD5.getValue(), checksum); + url = String.format(Urls.UPLOAD_DELETE_ARTIFACT_OF_COMPONENT, config.getCatalogBeHost(), config.getCatalogBePort(), ComponentTypeEnum.findParamByType(component.getComponentType()), component.getUniqueId(), artifactDetails.getUniqueId()); + // } + + Gson gson = new Gson(); + String jsonBody = gson.toJson(artifactDetails); + // System.out.println("ArtifactDetails: "+ jsonBody); + + RestResponse res = sendPost(url, jsonBody, sdncModifierDetails.getUserId(), acceptHeaderData, additionalHeaders); + if (res.getErrorCode() == STATUS_CODE_SUCCESS) { + artifactDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(res)); + } + // System.out.println("Add artifact was finished with response: "+ + // res.getErrorCode()); + return res; + } + + // *************** PRIVATE ************** + private static RestResponse uploadInformationalArtifact(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String checksum, String url) throws IOException { + Map<String, String> additionalHeaders = null; + if (checksum != null && !checksum.isEmpty()) { + additionalHeaders = new HashMap<String, String>(); + additionalHeaders.put(HttpHeaderEnum.Content_MD5.getValue(), checksum); + } + + additionalHeaders.put(HttpHeaderEnum.AUTHORIZATION.getValue(), authorizationHeader); + additionalHeaders.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci"); + + Gson gson = new Gson(); + // System.out.println("ArtifactDetails: "+ jsonBody); + String jsonBody = gson.toJson(artifactDetails); + + RestResponse res = sendPost(url, jsonBody, sdncModifierDetails.getUserId(), acceptHeaderData, additionalHeaders); + if ((res.getErrorCode() == STATUS_CODE_SUCCESS) || (res.getErrorCode() == STATUS_CODE_CREATED)) { + artifactDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(res)); + } + // System.out.println("Add artifact was finished with response: "+ + // res.getErrorCode()); + return res; + } + + private static RestResponse addArtifactToInstance(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String checksum, String url) throws IOException { + Map<String, String> additionalHeaders = null; + additionalHeaders = new HashMap<String, String>(); + if (checksum != null && !checksum.isEmpty()) { + additionalHeaders = new HashMap<String, String>(); + additionalHeaders.put(HttpHeaderEnum.Content_MD5.getValue(), checksum); + } + additionalHeaders.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json, text/plain, */*"); + additionalHeaders.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json;charset=UTF-8"); + + Gson gson = new Gson(); + String jsonBody = gson.toJson(artifactDetails); + + RestResponse res = sendPost(url, jsonBody, sdncModifierDetails.getUserId(), "application/json, text/plain, */*", additionalHeaders); + if (res.getErrorCode() == STATUS_CODE_SUCCESS) { + artifactDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(res)); + } + return res; + } + + private static RestResponse updateDeploymentArtifact(ArtifactDefinition artifactDefinition, User sdncModifierDetails, String url) throws IOException { + Map<String, String> additionalHeaders = null; + additionalHeaders = new HashMap<String, String>(); + additionalHeaders.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json, text/plain, */*"); + additionalHeaders.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json;charset=UTF-8"); + + Gson gson = new Gson(); + String jsonBody = gson.toJson(artifactDefinition); + + RestResponse res = sendPost(url, jsonBody, sdncModifierDetails.getUserId(), "application/json, text/plain, */*", additionalHeaders); + return res; + } + + private static RestResponse updateDeploymentArtifact(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String url) throws IOException { + Map<String, String> additionalHeaders = null; + + additionalHeaders = new HashMap<String, String>(); + additionalHeaders.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json, text/plain, */*"); + additionalHeaders.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json;charset=UTF-8"); + // additionalHeaders.put(HttpHeaderEnum..getValue(), + // "application/json;charset=UTF-8"); + + Gson gson = new Gson(); + String jsonBody = gson.toJson(artifactDetails); + // System.out.println("ArtifactDetails: "+ jsonBody); + + RestResponse res = sendPost(url, jsonBody, sdncModifierDetails.getUserId(), "application/json, text/plain, */*", additionalHeaders); + if (res.getErrorCode() == STATUS_CODE_SUCCESS) { + artifactDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(res)); + } + // System.out.println("Add artifact was finished with response: "+ + // res.getErrorCode()); + return res; + } + + private static RestResponse downloadArtifact(String url, User user, Map<String, String> addionalHeaders, boolean addEcompHeader) throws IOException { + if (addEcompHeader) { + addionalHeaders.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), ecomp); + } + return downloadArtifact(url, user, addionalHeaders, acceptOctetStream); + } + + private static RestResponse downloadArtifact(String url, User user, Map<String, String> addionalHeaders, String accept) throws IOException { + addionalHeaders.put(HttpHeaderEnum.ACCEPT.getValue(), accept); + + RestResponse res = sendGet(url, user.getUserId(), addionalHeaders); + // System.out.println("download artifact was finished with response: "+ + // res.getErrorCode()); + // System.out.println("response is: " + res.getResponse()); + return res; + } + + private static Map<String, Map<String, Object>> getArtifactsListFromResponse(String jsonResponse, String fieldOfArtifactList) { + JSONObject object = (JSONObject) JSONValue.parse(jsonResponse); + Map<String, Map<String, Object>> map = (Map<String, Map<String, Object>>) object.get(fieldOfArtifactList); + return map; + } + + public static String calculateChecksum(ArtifactReqDetails artifactDetails) { + String checksum = null; + if (artifactDetails.getPayload() != null) { + checksum = ResponseParser.calculateMD5Header(artifactDetails); + } + return checksum; + } + + public static String encodeUrlForDownload(String url) { + + return url.replaceAll(" ", "%20"); + } + + public static String getPartialUrlByArtifactName(ServiceReqDetails serviceDetails, String serviceVersion, String artifactName) { + return encodeUrlForDownload(String.format(Urls.DISTRIB_DOWNLOAD_SERVICE_ARTIFACT_RELATIVE_URL, ValidationUtils.convertToSystemName(serviceDetails.getName()), serviceVersion, artifactName)); + } + + public static String getUniqueIdOfArtifact(RestResponse createResponse, String artifactField, String requieredArtifactLabel) throws Exception { + Map<String, Object> artifact = getArtifactFromRestResponse(createResponse, artifactField, requieredArtifactLabel); + assertNotNull(artifact); + return artifact.get("uniqueId").toString(); + } + + public static Map<String, Object> getArtifactFromRestResponse(RestResponse response, String artifactField, String requieredArtifactLabel) { + Map<String, Map<String, Object>> map = getArtifactsListFromResponse(response.getResponse(), artifactField); + return map.get(requieredArtifactLabel); + } + + public static RestResponse updateInformationalArtifactPayloadOfService(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String serviceUid, String artifactUid) throws IOException { + return updateInformationalArtifactPayloadOfService(artifactDetails, sdncModifierDetails, serviceUid, artifactUid, calculateMD5Header(artifactDetails)); + } + + private static RestResponse updateInformationalArtifactPayloadOfService(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String serviceUid, String artifactUid, String checksum) throws IOException { + return updateInformationalArtifactOfService(artifactDetails, sdncModifierDetails, serviceUid, artifactUid, checksum, true); + } + + private static RestResponse updateInformationalArtifactOfService(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String serviceUid, String artifactUid, String checksum, boolean isPayloadUpdate) throws IOException { + Config config = Utils.getConfig(); + Map<String, String> headersMap = prepareHeadersMap(sdncModifierDetails.getUserId()); + + if (isPayloadUpdate) { + headersMap.put(HttpHeaderEnum.Content_MD5.getValue(), checksum); + } + + Gson gson = new Gson(); + String jsonBody = gson.toJson(artifactDetails); + + HttpRequest http = new HttpRequest(); + + String url = String.format(Urls.UPDATE_OR_DELETE_ARTIFACT_OF_SERVICE, config.getCatalogBeHost(), config.getCatalogBePort(), serviceUid, artifactUid); + RestResponse res = http.httpSendPost(url, jsonBody, headersMap); + // System.out.println("update artifact was finished with response: "+ + // res.getErrorCode()); + return res; + } + + public static String calculateMD5Header(ArtifactReqDetails artifactDetails) { + Gson gson = new Gson(); + String jsonBody = gson.toJson(artifactDetails); + // calculate MD5 for json body + return calculateMD5(jsonBody); + + } + + public static String calculateMD5(String data) { + String calculatedMd5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(data); + // encode base-64 result + byte[] encodeBase64 = Base64.encodeBase64(calculatedMd5.getBytes()); + String encodeBase64Str = new String(encodeBase64); + return encodeBase64Str; + + } + +} diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/AssetRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/AssetRestUtils.java new file mode 100644 index 0000000000..51bd2162c0 --- /dev/null +++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/AssetRestUtils.java @@ -0,0 +1,510 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.utils.rest; + +import static org.testng.AssertJUnit.assertNotNull; +import static org.testng.AssertJUnit.assertTrue; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import org.apache.http.HttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.codehaus.jackson.map.ObjectMapper; +import org.openecomp.sdc.be.datatypes.enums.AssetTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.ci.tests.api.Urls; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.ArtifactAssetStructure; +import org.openecomp.sdc.ci.tests.datatypes.AssetStructure; +import org.openecomp.sdc.ci.tests.datatypes.ResourceAssetStructure; +import org.openecomp.sdc.ci.tests.datatypes.ResourceDetailedAssetStructure; +import org.openecomp.sdc.ci.tests.datatypes.ResourceInstanceAssetStructure; +import org.openecomp.sdc.ci.tests.datatypes.ServiceAssetStructure; +import org.openecomp.sdc.ci.tests.datatypes.ServiceDetailedAssetStructure; +import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum; +import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.utils.Utils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; + +public class AssetRestUtils extends BaseRestUtils { + static Gson gson = new Gson(); + static ObjectMapper objectMapper = new ObjectMapper(); + + static Logger logger = LoggerFactory.getLogger(UserRestUtils.class.getName()); + static final String contentTypeHeaderData = "application/json"; + static final String acceptHeaderDate = "application/json"; + static final String basicAuthentication = "Basic Y2k6MTIzNDU2"; + // /asdc/v1/catalog/{services/resources}/{componentUUID}/artifacts/{artifactUUID} + static final String COMPONENT_ARTIFACT_URL = "/asdc/v1/catalog/%s/%s/artifacts/%s"; + // /asdc/v1/catalog/{services/resources}/{componentUUID}/resourceInstances/{resourceInstanceName}/artifacts/{artifactUUID} + static final String RESOURCE_INSTANCE_ARTIFACT_URL = "/asdc/v1/catalog/%s/%s/resourceInstances/%s/artifacts/%s"; + + public static HttpResponse getComponentToscaModel(AssetTypeEnum assetType, String uuid) throws IOException { + Config config = Utils.getConfig(); + CloseableHttpClient httpclient = HttpClients.createDefault(); + String url = String.format(Urls.GET_TOSCA_MODEL, config.getCatalogBeHost(), config.getCatalogBePort(), + assetType.getValue(), uuid); + HttpGet httpGet = new HttpGet(url); + + httpGet.addHeader(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci"); + httpGet.addHeader(HttpHeaderEnum.AUTHORIZATION.getValue(), basicAuthentication); + + logger.debug("Send GET request to get Tosca model: {}", url); + + return httpclient.execute(httpGet); + } + + public static RestResponse getComponentListByAssetType(boolean isBasicAuthentication, AssetTypeEnum assetType, + String... filterArrayString) throws IOException { + Config config = Utils.getConfig(); + Map<String, String> headersMap = new HashMap<String, String>(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + if (isBasicAuthentication) { + headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), basicAuthentication); + } + headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci"); + + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.GET_ASSET_LIST, config.getCatalogBeHost(), config.getCatalogBePort(), + assetType.getValue()); + if (filterArrayString != null && filterArrayString.length > 0) { + url = buildUrlWithFilter(url, filterArrayString); + } + + RestResponse sendGetResourceAssets = http.httpSendGet(url, headersMap); + + return sendGetResourceAssets; + } + + public static RestResponse getFilteredComponentList(AssetTypeEnum assetType, String query) throws IOException { + Config config = Utils.getConfig(); + Map<String, String> headersMap = new HashMap<String, String>(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), basicAuthentication); + headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci"); + + HttpRequest http = new HttpRequest(); + + String url = String.format(Urls.GET_FILTERED_ASSET_LIST, config.getCatalogBeHost(), config.getCatalogBePort(), + assetType.getValue(), query); + + logger.debug("Send GET request to get Resource Assets: {}", url); + logger.debug("Request headers: {}", headersMap); + + RestResponse sendGetResourceAssets = http.httpSendGet(url, headersMap); + + return sendGetResourceAssets; + } + + public static String buildUrlWithFilter(String url, String[] filterArrayString) { + StringBuilder sb = new StringBuilder(); + int length = filterArrayString.length; + int count = 0; + for (String filterString : filterArrayString) { + sb.append(filterString); + count++; + if (length != count) { + sb.append("&"); + } + } + return url + "?" + sb; + } + + public static RestResponse getAssetMetadataByAssetTypeAndUuid(boolean isBasicAuthentication, + AssetTypeEnum assetType, String uuid) throws IOException { + + Config config = Utils.getConfig(); + Map<String, String> headersMap = new HashMap<String, String>(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + if (isBasicAuthentication) { + headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), basicAuthentication); + } + headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci"); + + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.GET_ASSET_METADATA, config.getCatalogBeHost(), config.getCatalogBePort(), + assetType.getValue(), uuid); + + logger.debug("Send GET request to get Resource Assets: {}", url); + logger.debug("Request headers: {} ", headersMap); + + RestResponse sendGetResourceAssets = http.httpSendGet(url, headersMap); + + return sendGetResourceAssets; + } + + public static List<ResourceAssetStructure> getResourceAssetList(RestResponse assetResponse) { + List<ResourceAssetStructure> resourceAssetList = new ArrayList<>(); + + JsonElement jelement = new JsonParser().parse(assetResponse.getResponse()); + JsonArray componenetArray = (JsonArray) jelement; + for (JsonElement jElement : componenetArray) { + ResourceAssetStructure resource = gson.fromJson(jElement, ResourceAssetStructure.class); + resourceAssetList.add(resource); + } + return resourceAssetList; + } + + public static ResourceDetailedAssetStructure getResourceAssetMetadata(RestResponse assetResponse) { + + List<ResourceInstanceAssetStructure> resourcesList = new ArrayList<>(); + List<ArtifactAssetStructure> artifactsList = new ArrayList<>(); + ResourceDetailedAssetStructure resourceAssetMetadata = new ResourceDetailedAssetStructure(); + String response = assetResponse.getResponse(); + + JsonObject jObject = (JsonObject) new JsonParser().parse(response); + resourceAssetMetadata = gson.fromJson(jObject, ResourceDetailedAssetStructure.class); + + setResourceInstanceAssetList(resourcesList, jObject); + resourceAssetMetadata.setResources(resourcesList); + + setArtifactAssetList(artifactsList, jObject); + resourceAssetMetadata.setArtifacts(artifactsList); + + return resourceAssetMetadata; + } + + public static void generalMetadataFieldsValidatior(AssetStructure assetMetadata, Component component) { + + assertTrue("Expected resourceUuid is " + component.getUUID() + " actual: " + assetMetadata.getUuid(), + assetMetadata.getUuid().equals(component.getUUID())); + assertTrue( + "Expected resourceInvariantUuid is " + component.getInvariantUUID() + " actual: " + + assetMetadata.getInvariantUUID(), + assetMetadata.getInvariantUUID().equals(component.getInvariantUUID())); + assertTrue("Expected asset name is " + component.getName() + " actual: " + assetMetadata.getName(), + assetMetadata.getName().equals(component.getName())); + assertTrue("Expected asset version is " + component.getVersion() + " actual: " + assetMetadata.getVersion(), + assetMetadata.getVersion().equals(component.getVersion())); + assertTrue( + "Expected asset lastUpdaterUserId is " + component.getLastUpdaterUserId() + " actual: " + + assetMetadata.getLastUpdaterUserId(), + assetMetadata.getLastUpdaterUserId().equals(component.getLastUpdaterUserId())); + assertNotNull("Expected asset toscaModel is null", assetMetadata.getToscaModelURL()); + assertTrue( + "Expected asset category is " + component.getCategories().get(0).getName() + " actual: " + + assetMetadata.getCategory(), + assetMetadata.getCategory().equals(component.getCategories().get(0).getName())); + assertTrue( + "Expected asset lifeCycleState is " + component.getLifecycleState() + " actual: " + + assetMetadata.getLifecycleState(), + assetMetadata.getLifecycleState().equals(component.getLifecycleState().toString())); + + } + + public static void resourceMetadataValidatior(ResourceDetailedAssetStructure resourceAssetMetadata, + Resource resource, AssetTypeEnum assetType) { + + generalMetadataFieldsValidatior(resourceAssetMetadata, resource); + assertTrue( + "Expected asset lastUpdaterFullName is " + resource.getLastUpdaterFullName() + " actual: " + + resourceAssetMetadata.getLastUpdaterFullName(), + resourceAssetMetadata.getLastUpdaterFullName().equals(resource.getLastUpdaterFullName())); + assertTrue( + "Expected asset subCategory is " + resource.getCategories().get(0).getSubcategories().get(0).getName() + + " actual: " + resourceAssetMetadata.getSubCategory(), + resourceAssetMetadata.getSubCategory() + .equals(resource.getCategories().get(0).getSubcategories().get(0).getName())); + assertTrue( + "Expected asset toscaResourceName is " + resource.getToscaResourceName() + " actual: " + + resourceAssetMetadata.getToscaResourceName(), + resourceAssetMetadata.getToscaResourceName().equals(resource.getToscaResourceName())); + assertTrue( + "Expected asset resourceType is " + resource.getResourceType() + " actual: " + + resourceAssetMetadata.getResourceType(), + resourceAssetMetadata.getResourceType().equals(resource.getResourceType().toString())); + resourceInstanceAssetValidator(resourceAssetMetadata.getResources(), resource, assetType); + // resourceInstanceAssetValidator(resourceAssetMetadata.getResources(), + // resource); + artifactAssetValidator(resourceAssetMetadata.getArtifacts(), resource, assetType); + + } + + public static void serviceMetadataValidatior(ServiceDetailedAssetStructure serviceAssetMetadata, Service service, + AssetTypeEnum assetType) { + + generalMetadataFieldsValidatior(serviceAssetMetadata, service); + assertTrue( + "Expected asset lastUpdaterFullName is " + service.getLastUpdaterFullName() + " actual: " + + serviceAssetMetadata.getLastUpdaterFullName(), + serviceAssetMetadata.getLastUpdaterFullName().equals(service.getLastUpdaterFullName())); + assertTrue( + "Expected asset distributionStatus is " + service.getDistributionStatus() + " actual: " + + serviceAssetMetadata.getDistributionStatus(), + serviceAssetMetadata.getDistributionStatus().equals(service.getDistributionStatus().toString())); + resourceInstanceAssetValidator(serviceAssetMetadata.getResources(), service, assetType); + // resourceInstanceAssetValidator(serviceAssetMetadata.getResources(), + // service); + artifactAssetValidator(serviceAssetMetadata.getArtifacts(), service, assetType); + + } + + private static void artifactAssetValidator(List<ArtifactAssetStructure> artifactAssetStructureList, + Component component, AssetTypeEnum assetType) { + Map<String, ArtifactDefinition> componentDeploymentArtifacts = component.getDeploymentArtifacts(); + validateArtifactMetadata(componentDeploymentArtifacts, artifactAssetStructureList, component.getUUID(), + assetType, null); + } + + private static void validateArtifactMetadata(Map<String, ArtifactDefinition> componentDeploymentArtifacts, + List<ArtifactAssetStructure> artifactAssetStructureList, String componentUuid, AssetTypeEnum assetType, + String resourceInstanceName) { + + for (Entry<String, ArtifactDefinition> componentDeploymentArtifact : componentDeploymentArtifacts.entrySet()) { + ArtifactAssetStructure artifactAssetStructure = getArtifactMetadata(artifactAssetStructureList, + componentDeploymentArtifact.getValue().getArtifactUUID()); + ArtifactDefinition componentDeploymentArtifactValue = componentDeploymentArtifact.getValue(); + if (artifactAssetStructure != null) { + assertTrue( + "Expected artifact asset artifactName is " + componentDeploymentArtifactValue.getArtifactName() + + " actual: " + artifactAssetStructure.getArtifactName(), + componentDeploymentArtifactValue.getArtifactName() + .equals(artifactAssetStructure.getArtifactName())); + assertTrue( + "Expected artifact asset Type is " + componentDeploymentArtifactValue.getArtifactType() + + " actual: " + artifactAssetStructure.getArtifactType(), + componentDeploymentArtifactValue.getArtifactType() + .equals(artifactAssetStructure.getArtifactType())); + // assertNotNull("Expected artifact asset resourceInvariantUUID + // is null", + // resourceInstanceAssetStructure.getResourceInvariantUUID()); + // String expectedArtifactUrl = "/asdc/v1/catalog/" + + // assetType.getValue() + "/" + componentUuid + "/artifacts/" + + // componentDeploymentArtifactValue.getArtifactUUID(); + String expectedArtifactUrl = ""; + if (resourceInstanceName == null) { + expectedArtifactUrl = String.format(COMPONENT_ARTIFACT_URL, assetType.getValue(), componentUuid, + componentDeploymentArtifactValue.getArtifactUUID()); + } else { + expectedArtifactUrl = String.format(RESOURCE_INSTANCE_ARTIFACT_URL, assetType.getValue(), + componentUuid, resourceInstanceName, componentDeploymentArtifactValue.getArtifactUUID()); + } + + assertTrue( + "Expected artifact asset URL is " + expectedArtifactUrl + " actual: " + + artifactAssetStructure.getArtifactURL(), + artifactAssetStructure.getArtifactURL().equals(expectedArtifactUrl)); + assertTrue( + "Expected artifact asset description is " + componentDeploymentArtifactValue.getDescription() + + " actual: " + artifactAssetStructure.getArtifactDescription(), + componentDeploymentArtifactValue.getDescription().toString() + .equals(artifactAssetStructure.getArtifactDescription())); + assertTrue( + "Expected artifact asset checkSum is " + componentDeploymentArtifactValue.getArtifactChecksum() + + " actual: " + artifactAssetStructure.getArtifactChecksum(), + componentDeploymentArtifactValue.getArtifactChecksum() + .equals(artifactAssetStructure.getArtifactChecksum())); + assertTrue( + "Expected artifact asset version is " + componentDeploymentArtifactValue.getArtifactVersion() + + " actual: " + artifactAssetStructure.getArtifactVersion(), + componentDeploymentArtifactValue.getArtifactVersion() + .equals(artifactAssetStructure.getArtifactVersion())); + if (componentDeploymentArtifactValue.getTimeout() > 0) { + assertTrue( + "Expected artifact asset timeout is " + componentDeploymentArtifactValue.getTimeout() + + " actual: " + artifactAssetStructure.getArtifactTimeout(), + componentDeploymentArtifactValue.getTimeout() + .equals(artifactAssetStructure.getArtifactTimeout())); + } + + } else { + assertTrue("artifact asset with UUID" + componentDeploymentArtifact.getValue().getArtifactUUID() + + " not found in get Metadata response", false); + } + } + + } + + private static ArtifactAssetStructure getArtifactMetadata(List<ArtifactAssetStructure> artifactAssetStructureList, + String artifactUUID) { + for (ArtifactAssetStructure artifactAssetStructure : artifactAssetStructureList) { + if (artifactAssetStructure.getArtifactUUID().equals(artifactUUID)) { + return artifactAssetStructure; + } + } + return null; + } + + private static void resourceInstanceAssetValidator( + List<ResourceInstanceAssetStructure> resourceInstanceAssetStructures, Component component, + AssetTypeEnum assetType) { + + List<ComponentInstance> componentInstances = component.getComponentInstances(); + if (componentInstances != null) { + for (ComponentInstance componentInstance : componentInstances) { + ResourceInstanceAssetStructure resourceInstanceAssetStructure = getResourceInstanceMetadata( + resourceInstanceAssetStructures, componentInstance.getName()); + if (resourceInstanceAssetStructure != null) { + assertTrue( + "Expected RI asset resourceName is " + componentInstance.getComponentName() + " actual: " + + resourceInstanceAssetStructure.getResourceName(), + componentInstance.getComponentName() + .equals(resourceInstanceAssetStructure.getResourceName())); + assertTrue( + "Expected RI asset Name is " + componentInstance.getName() + " actual: " + + resourceInstanceAssetStructure.getResourceInstanceName(), + componentInstance.getName() + .equals(resourceInstanceAssetStructure.getResourceInstanceName())); + assertNotNull("Expected RI asset resourceInvariantUUID is null", + resourceInstanceAssetStructure.getResourceInvariantUUID()); + assertTrue( + "Expected RI asset resourceVersion is " + componentInstance.getComponentVersion() + + " actual: " + resourceInstanceAssetStructure.getResourceVersion(), + componentInstance.getComponentVersion() + .equals(resourceInstanceAssetStructure.getResourceVersion())); + assertTrue( + "Expected RI asset resourceType is " + componentInstance.getOriginType() + " actual: " + + resourceInstanceAssetStructure.getResoucreType(), + componentInstance.getOriginType().toString() + .equals(resourceInstanceAssetStructure.getResoucreType())); + assertTrue( + "Expected RI asset resourceUUID is " + componentInstance.getComponentUid() + " actual: " + + resourceInstanceAssetStructure.getResourceUUID(), + componentInstance.getComponentUid() + .equals(resourceInstanceAssetStructure.getResourceUUID())); + validateArtifactMetadata(componentInstance.getDeploymentArtifacts(), + resourceInstanceAssetStructure.getArtifacts(), component.getUUID(), assetType, + componentInstance.getNormalizedName()); + // validateArtifactMetadata(componentInstance.getDeploymentArtifacts(), + // resourceInstanceAssetStructure.getArtifacts(), + // component.getUUID(), AssetTypeEnum.RESOURCES); + } else { + assertTrue("resourceInstance asset with UUID" + componentInstance.getComponentUid() + + " not found in get Metadata response", false); + } + } + } + + } + + // private static ResourceInstanceAssetStructure + // getResourceInstanceMetadata(List<ResourceInstanceAssetStructure> + // resourceInstanceAssetStructures, String componentUid) { + private static ResourceInstanceAssetStructure getResourceInstanceMetadata( + List<ResourceInstanceAssetStructure> resourceInstanceAssetStructures, String name) { + for (ResourceInstanceAssetStructure resourceInstanceAssetStructure : resourceInstanceAssetStructures) { + if (resourceInstanceAssetStructure.getResourceInstanceName().equals(name)) { + return resourceInstanceAssetStructure; + } + } + return null; + } + + public static ServiceDetailedAssetStructure getServiceAssetMetadata(RestResponse assetResponse) { + + List<ResourceInstanceAssetStructure> resourcesList = new ArrayList<>(); + List<ArtifactAssetStructure> artifactsList = new ArrayList<>(); + ServiceDetailedAssetStructure serviceAssetMetadata; + + JsonObject jObject = (JsonObject) new JsonParser().parse(assetResponse.getResponse()); + serviceAssetMetadata = gson.fromJson(jObject, ServiceDetailedAssetStructure.class); + + setResourceInstanceAssetList(resourcesList, jObject); + serviceAssetMetadata.setResources(resourcesList); + + setArtifactAssetList(artifactsList, jObject); + serviceAssetMetadata.setArtifacts(artifactsList); + + return serviceAssetMetadata; + } + + public static void setArtifactAssetList(List<ArtifactAssetStructure> artifactsList, JsonObject jObject) { + JsonArray artifactsArray = jObject.getAsJsonArray("artifacts"); + if (artifactsArray != null) { + for (JsonElement jElement : artifactsArray) { + ArtifactAssetStructure artifact = gson.fromJson(jElement, ArtifactAssetStructure.class); + artifactsList.add(artifact); + } + } + } + + public static void setResourceInstanceAssetList(List<ResourceInstanceAssetStructure> resourcesList, + JsonObject jObject) { + JsonArray resourcesArray = jObject.getAsJsonArray("resources"); + if (resourcesArray != null) { + for (JsonElement jElement : resourcesArray) { + ResourceInstanceAssetStructure resource = gson.fromJson(jElement, ResourceInstanceAssetStructure.class); + resourcesList.add(resource); + } + } + } + + public static List<ServiceAssetStructure> getServiceAssetList(RestResponse assetResponse) { + List<ServiceAssetStructure> serviceAssetList = new ArrayList<>(); + + JsonElement jelement = new JsonParser().parse(assetResponse.getResponse()); + JsonArray componenetArray = (JsonArray) jelement; + for (JsonElement jElement : componenetArray) { + ServiceAssetStructure service = gson.fromJson(jElement, ServiceAssetStructure.class); + serviceAssetList.add(service); + } + return serviceAssetList; + } + + public static List<String> getResourceNamesList(List<ResourceAssetStructure> resourceAssetList) { + List<String> assetNamesList = new ArrayList<>(); + for (ResourceAssetStructure resourceAsset : resourceAssetList) { + assetNamesList.add(resourceAsset.getName()); + } + return assetNamesList; + } + + public static List<String> getServiceNamesList(List<ServiceAssetStructure> serviceAssetList) { + List<String> assetNamesList = new ArrayList<>(); + for (ServiceAssetStructure serviceAsset : serviceAssetList) { + assetNamesList.add(serviceAsset.getName()); + } + return assetNamesList; + } + + public static void checkResourceTypeInObjectList(List<ResourceAssetStructure> resourceAssetList, + ResourceTypeEnum resourceType) { + for (ResourceAssetStructure resourceAsset : resourceAssetList) { + assertTrue( + "Expected resourceType is " + resourceType.toString() + " actual: " + + resourceAsset.getResourceType(), + resourceAsset.getResourceType().equals(resourceType.toString())); + } + } +} diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/BaseRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/BaseRestUtils.java new file mode 100644 index 0000000000..9ffe5782e7 --- /dev/null +++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/BaseRestUtils.java @@ -0,0 +1,256 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.utils.rest; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.codec.binary.Base64; +import org.apache.http.HttpEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum; +import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.utils.validation.BaseValidationUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class BaseRestUtils extends BaseValidationUtils { + public static final String contentTypeHeaderData = "application/json"; + public static final String acceptHeaderData = "application/json"; + public static final String acceptJsonHeader = "application/json"; + public static final String acceptOctetHeader = "application/octet-stream"; + public static final String authorizationHeader = "Basic " + Base64.encodeBase64String("ci:123456".getBytes()); + public static final String acceptOctetStream = "application/octet-stream"; + public static final String ecomp = "ecomp"; + public static final String authorizationPrefixString = "Basic "; + + public static final String RESOURCE_COMPONENT_TYPE = "resources"; + public static final String PRODUCT_COMPONENT_TYPE = "products"; + public static final String SERVICE_COMPONENT_TYPE = "services"; + + public static final int STATUS_CODE_SUCCESS = 200; + public static final int STATUS_CODE_CREATED = 201; + public static final int STATUS_CODE_DELETE = 204; + public static final int STATUS_CODE_NOT_FOUND = 404; + public static final int STATUS_CODE_SUCCESS_NO_CONTENT = 204; + public static final int STATUS_CODE_SUCCESS_DELETE = 204; + public static final int STATUS_CODE_INVALID_CONTENT = 400; + public static final int STATUS_CODE_MISSING_DATA = 400; + public static final int STATUS_CODE_MISSING_INFORMATION = 403; + public static final int STATUS_CODE_RESTRICTED_ACCESS = 403; + public static final int STATUS_CODE_ALREADY_EXISTS = 409; + public static final int STATUS_CODE_RESTRICTED_OPERATION = 409; + public static final int STATUS_CODE_COMPONENT_NAME_EXCEEDS_LIMIT = 400; + public static final int STATUS_CODE_MISSING_COMPONENT_NAME = 400; + public static final int STATUS_CODE_UNSUPPORTED_ERROR = 400; + public static final int STATUS_CODE_IMPORT_SUCCESS = 201; + public static final int STATUS_CODE_UPDATE_SUCCESS = 200; + public static final int RESTRICTED_OPERATION = 409; + public static final int STATUS_CODE_GET_SUCCESS = 200; + + public static final String SUCCESS_MESSAGE = "OK"; + private static Logger logger = LoggerFactory.getLogger(BaseRestUtils.class.getName()); + + private static byte[] encodeBase64; + + // ************* PRIVATE METHODS ************************ + + protected static Map<String, String> prepareHeadersMap(String userId) { + return prepareHeadersMap(userId, acceptHeaderData); + } + + protected static Map<String, String> prepareHeadersMap(String userId, String accept) { + Map<String, String> headersMap = new HashMap<String, String>(); + if (contentTypeHeaderData != null) { + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + } + if (accept != null) { + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), accept); + } + if (userId != null) { + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), userId); + } + + return headersMap; + } + + // send request + // GET + protected static RestResponse sendGet(String url, String userId) throws IOException { + return sendGet(url, userId, null); + } + + protected static RestResponse sendGet(String url, String userId, Map<String, String> additionalHeaders) + throws IOException { + Map<String, String> headersMap = prepareHeadersMap(userId); + if (additionalHeaders != null) { + headersMap.putAll(additionalHeaders); + } + + HttpRequest http = new HttpRequest(); + RestResponse getResourceResponse = http.httpSendGet(url, headersMap); + return getResourceResponse; + } + + public static RestResponse sendGetAndRemoveHeaders(String url, String userId, List<String> headersToRemove) + throws IOException { + Map<String, String> headersMap = prepareHeadersMap(userId); + if (headersToRemove != null) { + for (String header : headersToRemove) { + headersMap.remove(header); + } + } + + HttpRequest http = new HttpRequest(); + RestResponse getResourceResponse = http.httpSendGet(url, headersMap); + return getResourceResponse; + } + + // PUT + protected static RestResponse sendPut(String url, String userBodyJson, String userId, String cont) + throws IOException { + Map<String, String> headersMap = prepareHeadersMap(userId, cont); + + HttpRequest http = new HttpRequest(); + RestResponse updateResourceResponse = http.httpSendByMethod(url, "PUT", userBodyJson, headersMap); + return updateResourceResponse; + } + + // POST + public static RestResponse sendPost(String url, String userBodyJson, String userId, String accept) + throws IOException { + return sendPost(url, userBodyJson, userId, accept, null); + } + + protected static RestResponse sendPost(String url, String userBodyJson, String userId, String accept, + Map<String, String> additionalHeaders) throws IOException { + Map<String, String> headersMap = prepareHeadersMap(userId, accept); + if (additionalHeaders != null) { + headersMap.putAll(additionalHeaders); + } + HttpRequest http = new HttpRequest(); + RestResponse postResourceResponse = http.httpSendPost(url, userBodyJson, headersMap); + return postResourceResponse; + } + + // used form complex requests like import categories.. + protected static RestResponse sendPost(String url, HttpEntity entity, String userId, String accept) + throws IOException { + RestResponse postResponse = new RestResponse(); + CloseableHttpResponse response = null; + CloseableHttpClient client = null; + try { + client = HttpClients.createDefault(); + HttpPost httpPost = new HttpPost(url); + + httpPost.addHeader("USER_ID", userId); + httpPost.setEntity(entity); + response = client.execute(httpPost); + HttpEntity responseEntity = response.getEntity(); + int statusCode = response.getStatusLine().getStatusCode(); + + postResponse.setErrorCode(statusCode); + StringBuffer sb = new StringBuffer(); + try { + BufferedReader in = new BufferedReader(new InputStreamReader(responseEntity.getContent())); + String inputLine; + while ((inputLine = in.readLine()) != null) { + sb.append(inputLine); + } + in.close(); + } catch (Exception e) { + logger.debug("response body is null"); + } + postResponse.setResponse(sb.toString()); + } finally { + try { + if (response != null) { + response.close(); + } + + } catch (IOException e) { + logger.debug("failed to close client or response: ", e); + } + try { + if (client != null) { + client.close(); + } + } catch (IOException e) { + logger.debug("failed to close client or response: ", e); + } + } + return postResponse; + } + + // DELETE + protected static RestResponse sendDelete(String url, String userId) throws IOException { + Map<String, String> headersMap = prepareHeadersMap(userId); + + HttpRequest http = new HttpRequest(); + RestResponse deleteResourceResponse = http.httpSendDelete(url, headersMap); + return deleteResourceResponse; + } + + /* + * // ------ protected static Boolean checkErrorCode(RestResponse + * deleteResponse) { if (deleteResponse.getErrorCode() == + * STATUS_CODE_SUCCESS || deleteResponse.getErrorCode() == + * STATUS_CODE_DELETE) { return true; } return false; } + * + * // *** STATUS CODE VALIDATION UTIITIES **** public static void + * checkStatusCode(RestResponse response, String assertMessage, boolean AND, + * int... statuses) { int statusCode = response.getErrorCode(); for (int + * status : statuses) { if (AND && statusCode != status) { + * Assert.fail(assertMessage + " status: " + statusCode); } else if + * (statusCode == status) { return; } } if (!AND) { + * Assert.fail(assertMessage + " status: " + statusCode); } } + * + * public static void checkDeleteResponse(RestResponse response) { + * checkStatusCode(response,"delete request failed",false,STATUS_CODE_DELETE + * ,STATUS_CODE_NOT_FOUND, STATUS_CODE_SUCCESS); // STATUS_CODE_SUCCESS for + * deActivate user } + * + * public static void checkCreateResponse(RestResponse response) { + * checkStatusCode(response, "create request failed", false, + * STATUS_CODE_CREATED); } + */ + public static String encodeUrlForDownload(String url) { + return url.replaceAll(" ", "%20"); + } + + public static Map<String, String> addAuthorizeHeader(String userName, String password) { + String userCredentials = userName + ":" + password; + encodeBase64 = Base64.encodeBase64(userCredentials.getBytes()); + String encodedUserCredentials = authorizationPrefixString + new String(encodeBase64); + Map<String, String> authorizationHeader = new HashMap<String, String>(); + authorizationHeader.put(HttpHeaderEnum.AUTHORIZATION.getValue(), encodedUserCredentials); + return authorizationHeader; + } + +} diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CatalogRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CatalogRestUtils.java new file mode 100644 index 0000000000..a265639804 --- /dev/null +++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CatalogRestUtils.java @@ -0,0 +1,75 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.utils.rest; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import org.openecomp.sdc.ci.tests.api.Urls; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.utils.Utils; + +public class CatalogRestUtils extends BaseRestUtils { + + public static RestResponse getAbstractResources() throws IOException { + + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_ALL_ABSTRACT_RESOURCES, config.getCatalogBeHost(), + config.getCatalogBePort()); + + return sendGet(url, UserRoleEnum.DESIGNER.getUserId()); + } + + public static RestResponse getCatalog() throws IOException { + return getCatalog(UserRoleEnum.DESIGNER.getUserId()); + } + + public static RestResponse getCatalog(String userId) throws IOException { + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_CATALOG_DATA, config.getCatalogBeHost(), config.getCatalogBePort()); + return sendGet(url, userId); + } + + public static RestResponse getAllCategoriesTowardsCatalogBe() throws IOException { + + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_ALL_CATEGORIES, config.getCatalogBeHost(), config.getCatalogBePort(), + BaseRestUtils.RESOURCE_COMPONENT_TYPE); + + return sendGet(url, UserRoleEnum.DESIGNER.getUserId()); + } + + public static RestResponse getAllCategoriesTowardsCatalogFeWithUuid(String uuid) throws IOException { + + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_ALL_CATEGORIES_FE, config.getCatalogFeHost(), config.getCatalogFePort(), + BaseRestUtils.RESOURCE_COMPONENT_TYPE); + + Map<String, String> additionalHeaders = new HashMap<String, String>(); + additionalHeaders.put(HttpHeaderEnum.X_ECOMP_REQUEST_ID_HEADER.getValue(), uuid); + + return sendGet(url, UserRoleEnum.DESIGNER.getUserId(), additionalHeaders); + } +} diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CategoryRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CategoryRestUtils.java new file mode 100644 index 0000000000..d9ae91b955 --- /dev/null +++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CategoryRestUtils.java @@ -0,0 +1,298 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.utils.rest; + +import java.io.IOException; +import java.util.List; +import java.util.Map; + +import org.apache.http.entity.mime.MultipartEntityBuilder; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.openecomp.sdc.be.model.category.GroupingDefinition; +import org.openecomp.sdc.be.model.category.SubCategoryDefinition; +import org.openecomp.sdc.ci.tests.api.Urls; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.utils.Utils; + +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; + +public class CategoryRestUtils extends BaseRestUtils { + + private static final int STATUS_CODE_CREATED = 201; + + private static Gson gson = new Gson(); + + public static RestResponse createCategory(CategoryDefinition categoryDefinition, User sdncModifierDetails, + String categoryType) throws Exception { + Config config = Utils.getConfig(); + String url = String.format(Urls.CREATE_CATEGORY, config.getCatalogBeHost(), config.getCatalogBePort(), + categoryType); + String bodyJson = gson.toJson(categoryDefinition); + RestResponse addCategoryResponse = BaseRestUtils.sendPost(url, bodyJson, sdncModifierDetails.getUserId(), + acceptHeaderData); + if (addCategoryResponse.getErrorCode().intValue() == STATUS_CODE_CREATED) + categoryDefinition.setUniqueId( + ResponseParser.getValueFromJsonResponse(addCategoryResponse.getResponse(), "uniqueId")); + return addCategoryResponse; + } + + // GET categories + public static RestResponse getAllCategories(User sdncModifierDetails, String categoryType) throws Exception { + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_ALL_CATEGORIES, config.getCatalogBeHost(), config.getCatalogBePort(), categoryType); + String userId = sdncModifierDetails.getUserId(); + Map<String, String> headersMap = prepareHeadersMap(userId); + HttpRequest http = new HttpRequest(); + // System.out.println(url); + RestResponse getCategotyResponse = http.httpSendGet(url, headersMap); + return getCategotyResponse; + } + + public static RestResponse getAllCategoriesTowardsFe(User sdncModifierDetails, String categoryType) throws Exception { + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_ALL_CATEGORIES_FE, config.getCatalogFeHost(), config.getCatalogFePort(), categoryType); + String userId = sdncModifierDetails.getUserId(); + Map<String, String> headersMap = prepareHeadersMap(userId); + HttpRequest http = new HttpRequest(); + // System.out.println(url); + RestResponse getCategotyResponse = http.httpSendGet(url, headersMap); + return getCategotyResponse; + } + + // Delete Category + public static RestResponse deleteCategory(String categoryId, String psUserId, String categoryType) throws Exception { + Config config = Utils.getConfig(); + String url = String.format(Urls.DELETE_CATEGORY, config.getCatalogBeHost(), config.getCatalogBePort(), categoryType, categoryId); + url = url.replace("#", "%23"); // HEX + url = url.replace(" ", "%20"); // HEX + RestResponse deleteCategoryResponse = sendDelete(url, psUserId); + return deleteCategoryResponse; + } + + public static RestResponse createSubCategory(SubCategoryDefinition subCategory, CategoryDefinition parentCategory, + User sdncModifierDetails, String categoryType) throws Exception { + // categoryType = service/resource/product + Config config = Utils.getConfig(); + String url = String.format(Urls.CREATE_SUB_CATEGORY, config.getCatalogBeHost(), config.getCatalogBePort(), + categoryType, parentCategory.getUniqueId()); + String bodyJson = gson.toJson(subCategory); + RestResponse createSubCategoryPost = BaseRestUtils.sendPost(url, bodyJson, sdncModifierDetails.getUserId(), + acceptHeaderData); + if (createSubCategoryPost.getErrorCode().intValue() == STATUS_CODE_CREATED) + subCategory.setUniqueId( + ResponseParser.getValueFromJsonResponse(createSubCategoryPost.getResponse(), "uniqueId")); + + return createSubCategoryPost; + } + + public static RestResponse deleteSubCategory(String subCategoryId, String categoryId, String psUserId, + String categoryType) throws Exception { + Config config = Utils.getConfig(); + String url = String.format(Urls.DELETE_SUB_CATEGORY, config.getCatalogBeHost(), config.getCatalogBePort(), + categoryType, categoryId, subCategoryId); + url = url.replace("#", "%23"); // HEX + url = url.replace(" ", "%20"); // HEX + RestResponse deleteSubCategoryResponse = sendDelete(url, psUserId); + return deleteSubCategoryResponse; + } + + public static RestResponse deleteGrouping(String groupId, String subCategoryId, String categoryId, String psUserId, + String categoryType) throws Exception { + + Config config = Utils.getConfig(); + String url = String.format(Urls.DELETE_GROUPING, config.getCatalogBeHost(), config.getCatalogBePort(), + categoryType, categoryId, subCategoryId, groupId); + url = url.replace("#", "%23"); // HEX + url = url.replace(" ", "%20"); // HEX + RestResponse deleteGroupResponse = sendDelete(url, psUserId); + return deleteGroupResponse; + } + + public static RestResponse createServiceCategoryHttpCspAtuUidIsMissing(CategoryDefinition categoryDataDefinition, + User sdncModifierDetails) throws Exception { + + Config config = Utils.getConfig(); + String url = String.format(Urls.CREATE_CATEGORY, config.getCatalogBeHost(), config.getCatalogBePort(), + SERVICE_COMPONENT_TYPE); + + Map<String, String> headersMap = prepareHeadersMap(sdncModifierDetails.getUserId()); + headersMap.remove("USER_ID"); + Gson gson = new Gson(); + String userBodyJson = gson.toJson(categoryDataDefinition); + HttpRequest http = new HttpRequest(); + // System.out.println(url); + // System.out.println(userBodyJson); + RestResponse createCatergoryResponse = http.httpSendPost(url, userBodyJson, headersMap); + return createCatergoryResponse; + } + + public static RestResponse createSubCategoryHttpCspAtuUidIsMissing(SubCategoryDefinition subCategory, + CategoryDefinition parentCategory, User sdncModifierDetails, String categoryType) throws Exception { + // categoryType = service/resource/product + Config config = Utils.getConfig(); + String url = String.format(Urls.CREATE_SUB_CATEGORY, config.getCatalogBeHost(), config.getCatalogBePort(), + categoryType, parentCategory.getUniqueId()); + String userId = sdncModifierDetails.getUserId(); + Map<String, String> headersMap = prepareHeadersMap(userId); + headersMap.remove("USER_ID"); + Gson gson = new Gson(); + String subCatJson = gson.toJson(subCategory); + HttpRequest http = new HttpRequest(); + // System.out.println(url); + // System.out.println(subCatJson); + RestResponse addCategoryResponse = http.httpSendPost(url, subCatJson, headersMap); + return addCategoryResponse; + } + + public static RestResponse deleteCatergoryHttpCspAtuUidIsMissing(CategoryDefinition categoryDataDefinition, User sdncModifierDetails) throws Exception { + Config config = Utils.getConfig(); + String url = String.format(Urls.DELETE_CONSUMER, config.getCatalogBeHost(), config.getCatalogBePort(), categoryDataDefinition.getName()); + String userId = sdncModifierDetails.getUserId(); + Map<String, String> headersMap = prepareHeadersMap(userId); + headersMap.remove("USER_ID"); + Gson gson = new Gson(); + String userBodyJson = gson.toJson(categoryDataDefinition); + HttpRequest http = new HttpRequest(); + // System.out.println(url); + // System.out.println(userBodyJson); + RestResponse deleteCategotyResponse = http.httpSendDelete(url, headersMap); + return deleteCategotyResponse; + } + + public static RestResponse createGrouping(GroupingDefinition grouping, SubCategoryDefinition subCategory, + CategoryDefinition parentCategory, User sdncModifierDetails, String categoryType) throws Exception { + Config config = Utils.getConfig(); + String url = String.format(Urls.CREATE_GROUPING, config.getCatalogBeHost(), config.getCatalogBePort(), categoryType, parentCategory.getUniqueId(), subCategory.getUniqueId()); + String bodyJson = gson.toJson(grouping); + RestResponse addGroupingResponse = BaseRestUtils.sendPost(url, bodyJson, sdncModifierDetails.getUserId(), acceptHeaderData); + return addGroupingResponse; + } + + public static RestResponse importCategories(MultipartEntityBuilder mpBuilder, String userId) throws IOException { + Config config = Utils.getConfig(); + String url = String.format(Urls.IMPORT_CATEGORIES, config.getCatalogBeHost(), config.getCatalogBePort()); + + RestResponse importResponse = BaseRestUtils.sendPost(url, mpBuilder.build(), userId, acceptHeaderData); + return importResponse; + } + + public static int getMatchingCategoriesNum(RestResponse getAllCategoryRest, CategoryDefinition categoryDefinition) { + String response = getAllCategoryRest.getResponse(); + Gson gson = new Gson(); + List<CategoryDefinition> categoryDefinitions = gson.fromJson(response, + new TypeToken<List<CategoryDefinition>>() { + }.getType()); + int categoriesNum = 0; + String catName = categoryDefinition.getName(); + for (CategoryDefinition elem : categoryDefinitions) { + if (elem.getName().equals(catName)) { + categoryDefinition.setUniqueId(elem.getUniqueId()); + categoriesNum++; + } + } + + return categoriesNum; + } + + public static int getMatchingSubCategoriesNum(RestResponse getAllCategoryRest, String parentCategoryId, + SubCategoryDefinition expectedSubCategoryDefinition) { + + String response = getAllCategoryRest.getResponse(); + Gson gson = new Gson(); + List<CategoryDefinition> categoryDefinitions = gson.fromJson(response, + new TypeToken<List<CategoryDefinition>>() { + }.getType()); + int subCatNum = 0; + String subCatName = expectedSubCategoryDefinition.getName(); + for (CategoryDefinition elem : categoryDefinitions) { + if (elem.getUniqueId().equals(parentCategoryId)) { + List<SubCategoryDefinition> subCategories = elem.getSubcategories(); + if (subCategories != null) { + for (SubCategoryDefinition subCategoryDataDefinition : subCategories) { + if (subCatName.equals(subCategoryDataDefinition.getName())) { + expectedSubCategoryDefinition.setUniqueId(subCategoryDataDefinition.getUniqueId()); + subCatNum++; + } + } + } + + } + } + return subCatNum; + } + + public static int getMatchingGroupingNum(RestResponse getAllCategoryRest, String parentCategoryId, + String subCategoryId, GroupingDefinition expectedGroupingDefinition) { + + String response = getAllCategoryRest.getResponse(); + Gson gson = new Gson(); + List<CategoryDefinition> categoryDefinitions = gson.fromJson(response, + new TypeToken<List<CategoryDefinition>>() { + }.getType()); + int groupingNum = 0; + String groupingName = expectedGroupingDefinition.getName(); + for (CategoryDefinition elem : categoryDefinitions) { + if (elem.getUniqueId().equals(parentCategoryId)) { + List<SubCategoryDefinition> subCategories = elem.getSubcategories(); + if (subCategories != null) { + for (SubCategoryDefinition subCategoryDataDefinition : subCategories) { + // if + // (subCategoryId.equals(subCategoryDataDefinition.getUniqueId())) + // { + if (subCategoryId.equals(subCategoryDataDefinition.getUniqueId()) + && subCategoryDataDefinition.getGroupings() != null) { + List<GroupingDefinition> grouping = subCategoryDataDefinition.getGroupings(); + for (GroupingDefinition groupingDataDefinition : grouping) { + if (groupingName.equals(groupingDataDefinition.getName())) { + expectedGroupingDefinition.setUniqueId(groupingDataDefinition.getUniqueId()); + groupingNum++; + } + } + + } + } + } + + } + } + return groupingNum; + } + + public enum CategoryAuditJsonKeysEnum { + ACTION("ACTION"), MODIFIER("MODIFIER"), CATEGORY_NAME("CATEGORY_NAME"), SUB_CATEGORY_NAME("SUB_CATEGORY_NAME"), GROUPING_NAME("GROUPING_NAME"), RESOURCE_TYPE("RESOURCE_TYPE"), ECOMP_USER("ECOMP_USER"), STATUS("STATUS"), + DESCRIPTION("DESCRIPTION"), DETAILS("DETAILS"); + + private String auditJsonKeyName; + + private CategoryAuditJsonKeysEnum(String auditJsonKeyName) { + this.auditJsonKeyName = auditJsonKeyName; + } + + public String getAuditJsonKeyName() { + return auditJsonKeyName.toLowerCase(); + } + } + +} diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ComponentInstanceRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ComponentInstanceRestUtils.java new file mode 100644 index 0000000000..10587390f2 --- /dev/null +++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ComponentInstanceRestUtils.java @@ -0,0 +1,276 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.utils.rest; + +import static org.testng.Assert.assertTrue; + +import java.io.IOException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; +import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.api.Urls; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.utils.Utils; + +import com.google.gson.Gson; + +public class ComponentInstanceRestUtils extends BaseRestUtils { + public static String acceptHeaderDate = "application/json"; + static Config config = Config.instance(); + public static Gson gson = new Gson(); + + // 'componentType' can be 'services' or 'resources' + + public static RestResponse createComponentInstance(ComponentInstanceReqDetails componentInstanceReqDetails, + User sdncModifierDetails, Component component) throws Exception { + return createComponentInstance(componentInstanceReqDetails, sdncModifierDetails, component.getUniqueId(), + component.getComponentType()); + } + + public static RestResponse createComponentInstance(ComponentInstanceReqDetails componentInstanceReqDetails, + User sdncModifierDetails, String componentId, ComponentTypeEnum componentType) throws Exception { + + return createComponentInstance(componentInstanceReqDetails, sdncModifierDetails, componentId, + ComponentTypeEnum.findParamByType(componentType)); + } + + public static RestResponse createComponentInstance(ComponentInstanceReqDetails componentInstanceReqDetails, + User sdncModifierDetails, String componentId, String componentType) throws Exception { + Config config = Utils.getConfig(); + String userId = sdncModifierDetails.getUserId(); + String serviceBodyJson = gson.toJson(componentInstanceReqDetails); + String url = String.format(Urls.CREATE_COMPONENT_INSTANCE, config.getCatalogBeHost(), config.getCatalogBePort(), + componentType, componentId); + RestResponse createResourceInstance = sendPost(url, serviceBodyJson, userId, acceptHeaderData); + if (createResourceInstance.getErrorCode().equals(BaseRestUtils.STATUS_CODE_CREATED)) { + String uniqueId = ResponseParser.getValueFromJsonResponse(createResourceInstance.getResponse(), "uniqueId"); + componentInstanceReqDetails.setUniqueId(uniqueId); + // Gson gson = new Gson(); + // ResourceInstanceReqDetails fromJson = + // gson.fromJson(createResourceInstance.getResponse(), + // ResourceInstanceReqDetails.class); + // componentInstanceReqDetails.setUniqueId(fromJson.getUniqueId()); + } + return createResourceInstance; + } + + public static RestResponse getComponentInstances(ComponentTypeEnum type, String componentId, User user) + throws IOException { + + Config config = Utils.getConfig(); + + Map<String, String> headersMap = new HashMap<String, String>(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderData); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), user.getUserId()); + + String url = String.format(Urls.GET_COMPONENT_INSTANCES, config.getCatalogBeHost(), config.getCatalogBePort(), + ComponentTypeEnum.findParamByType(type), componentId); + + RestResponse sendGetServerRequest = sendGet(url, user.getUserId(), headersMap); + + return sendGetServerRequest; + + } + + public static RestResponse deleteComponentInstance(User sdncModifierDetails, String componentId, + String resourceInstanceId, ComponentTypeEnum componentType) throws Exception { + + return deleteComponentInstance(sdncModifierDetails, componentId, resourceInstanceId, + ComponentTypeEnum.findParamByType(componentType)); + } + + public static RestResponse deleteComponentInstance(User sdncModifierDetails, String componentId, + String resourceInstanceId, String componentTypeString) throws Exception { + Config config = Utils.getConfig(); + String userId = sdncModifierDetails.getUserId(); + String url = String.format(Urls.DELETE_COMPONENT_INSTANCE, config.getCatalogBeHost(), config.getCatalogBePort(), + componentTypeString, componentId, resourceInstanceId); + RestResponse sendCreateUserRequest = sendDelete(url, userId); + return sendCreateUserRequest; + } + + public static RestResponse updateComponentInstance(ComponentInstanceReqDetails componentInstanceReqDetails, + User sdncModifierDetails, String componentId, ComponentTypeEnum componentType) throws IOException { + + Config config = Utils.getConfig(); + String userId = sdncModifierDetails.getUserId(); + String serviceBodyJson = gson.toJson(componentInstanceReqDetails); + String url = String.format(Urls.UPDATE_COMPONENT_INSTANCE, config.getCatalogBeHost(), config.getCatalogBePort(), + ComponentTypeEnum.findParamByType(componentType), componentId, + componentInstanceReqDetails.getUniqueId()); + RestResponse updateResourceInstance = sendPost(url, serviceBodyJson, userId, acceptHeaderData); + return updateResourceInstance; + } + + // TODO Tal CI for New API Multiple Instance Update + public static RestResponse updateMultipleComponentInstance( + List<ComponentInstanceReqDetails> componentInstanceReqDetailsList, User sdncModifierDetails, + String componentId, ComponentTypeEnum componentType) throws IOException { + Config config = Utils.getConfig(); + String userId = sdncModifierDetails.getUserId(); + String serviceBodyJson = gson.toJson(componentInstanceReqDetailsList.toArray()); + String url = String.format(Urls.UPDATE_MULTIPLE_COMPONENT_INSTANCE, config.getCatalogBeHost(), + config.getCatalogBePort(), ComponentTypeEnum.findParamByType(componentType), componentId); + RestResponse updateResourceInstance = sendPost(url, serviceBodyJson, userId, acceptHeaderData); + return updateResourceInstance; + } + + public static RestResponse associateInstances(RequirementCapabilityRelDef relation, User sdncModifierDetails, + String componentId, ComponentTypeEnum componentTypeEnum) throws IOException { + + Config config = Utils.getConfig(); + + String componentType = ""; + switch (componentTypeEnum) { + case RESOURCE: + componentType = ComponentTypeEnum.RESOURCE_PARAM_NAME; + break; + case SERVICE: + componentType = ComponentTypeEnum.SERVICE_PARAM_NAME; + break; + default: + break; + } + String serviceBodyJson = gson.toJson(relation); + String url = String.format(Urls.ASSOCIATE__RESOURCE_INSTANCE, config.getCatalogBeHost(), + config.getCatalogBePort(), componentType, componentId); + + RestResponse associateInstance = sendPost(url, serviceBodyJson, sdncModifierDetails.getUserId(), + acceptHeaderData); + return associateInstance; + + } + + public static RestResponse dissociateInstances(RequirementCapabilityRelDef relation, User sdncModifierDetails, + String componentId, ComponentTypeEnum componentTypeEnum) throws IOException { + + Config config = Utils.getConfig(); + + String componentType = ""; + switch (componentTypeEnum) { + case RESOURCE: + componentType = ComponentTypeEnum.RESOURCE_PARAM_NAME; + break; + case SERVICE: + componentType = ComponentTypeEnum.SERVICE_PARAM_NAME; + break; + default: + break; + } + String serviceBodyJson = gson.toJson(relation); + String url = String.format(Urls.DISSOCIATE__RESOURCE_INSTANCE, config.getCatalogBeHost(), + config.getCatalogBePort(), componentType, componentId); + + RestResponse associateInstance = sendPut(url, serviceBodyJson, sdncModifierDetails.getUserId(), + acceptHeaderData); + return associateInstance; + + } + + public static void checkComponentInstanceType(RestResponse response, String expectedComponentType) { + String actualComponentType = ResponseParser.getComponentTypeFromResponse(response); + assertTrue(expectedComponentType.equals(actualComponentType), + "Failed. expected: " + expectedComponentType + ", actual: " + actualComponentType + "/"); + } + + public static RestResponse updatePropertyValueOnResourceInstance(Component component, ComponentInstance instDetails, + User user, ComponentInstanceProperty updatedInstanceProperty) throws IOException { + + Config config = Utils.getConfig(); + + Map<String, String> headersMap = new HashMap<String, String>(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderData); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), user.getUserId()); + + String url = String.format(Urls.UPDATE_PROPERTY_TO_RESOURCE_INSTANCE, config.getCatalogBeHost(), + config.getCatalogBePort(), ComponentTypeEnum.findParamByType(component.getComponentType()), + component.getUniqueId(), instDetails.getUniqueId()); + String body = gson.toJson(updatedInstanceProperty); + + RestResponse sendGetServerRequest = sendPost(url, body, user.getUserId(), acceptHeaderData); + return sendGetServerRequest; + + } + + public static RestResponse changeComponentInstanceVersion(Component container, + ComponentInstance componentInstanceToReplace, Component newInstance, User sdncModifierDetails) + throws Exception { + + return changeComponentInstanceVersion(container.getUniqueId(), componentInstanceToReplace, newInstance, + sdncModifierDetails, container.getComponentType()); + } + + public static RestResponse changeComponentInstanceVersion(String containerUID, + ComponentInstance componentInstanceToReplace, Component component, User sdncModifierDetails, + ComponentTypeEnum componentType) throws IOException { + + Config config = Utils.getConfig(); + String resourceUid = ("{\"componentUid\":\"" + component.getUniqueId() + "\"}"); + String url = String.format(Urls.CHANGE__RESOURCE_INSTANCE_VERSION, config.getCatalogBeHost(), + config.getCatalogBePort(), ComponentTypeEnum.findParamByType(componentType), containerUID, + componentInstanceToReplace.getUniqueId()); + RestResponse changeResourceInstanceVersion = sendPost(url, resourceUid, sdncModifierDetails.getUserId(), + acceptHeaderData); + + if (changeResourceInstanceVersion.getErrorCode() == 200 + || changeResourceInstanceVersion.getErrorCode() == 201) { + Gson gson = new Gson(); + // ResourceInstanceReqDetails + // convertResourceInstanceResponseToJavaObject = + // ResponseParser.convertResourceInstanceResponseToJavaObject(createResourceInstance.getResponse()); + ComponentInstanceReqDetails fromJson = gson.fromJson(changeResourceInstanceVersion.getResponse(), + ComponentInstanceReqDetails.class); + + componentInstanceToReplace.setUniqueId(fromJson.getUniqueId()); + + } + + return changeResourceInstanceVersion; + + } + + public static RestResponse changeComponentInstanceVersion(String componentUniqueId, + String serviceInstanceToReplaceUniqueId, String serviceUniqueId, User sdncModifierDetails, + ComponentTypeEnum componentType) throws IOException { + Config config = Utils.getConfig(); + String resourceUid = ("{\"componentUid\":\"" + serviceUniqueId + "\"}"); + String url = String.format(Urls.CHANGE__RESOURCE_INSTANCE_VERSION, config.getCatalogBeHost(), + config.getCatalogBePort(), ComponentTypeEnum.findParamByType(componentType), componentUniqueId, + serviceInstanceToReplaceUniqueId); + RestResponse changeResourceInstanceVersion = sendPost(url, resourceUid, sdncModifierDetails.getUserId(), + acceptHeaderData); + return changeResourceInstanceVersion; + + } + +} diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ComponentRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ComponentRestUtils.java new file mode 100644 index 0000000000..dcebe4afa8 --- /dev/null +++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ComponentRestUtils.java @@ -0,0 +1,62 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.utils.rest; + +import java.io.IOException; + +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.model.CapReqDef; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.api.Urls; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.ComponentReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ProductReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.utils.Utils; + +public class ComponentRestUtils extends BaseRestUtils { + public static RestResponse getComponentRequirmentsCapabilities(User sdncModifierDetails, + ComponentReqDetails componentReqDetails) throws IOException { + Config config = Utils.getConfig(); + ComponentTypeEnum componentType = null; + if (componentReqDetails instanceof ResourceReqDetails) { + componentType = ComponentTypeEnum.RESOURCE; + } else if (componentReqDetails instanceof ServiceReqDetails) { + componentType = ComponentTypeEnum.SERVICE; + } else if (componentReqDetails instanceof ProductReqDetails) { + componentType = ComponentTypeEnum.PRODUCT; + } + String url = String.format(Urls.GET_COMPONENT_REQUIRMENTS_CAPABILITIES, config.getCatalogBeHost(), + config.getCatalogBePort(), ComponentTypeEnum.findParamByType(componentType), + componentReqDetails.getUniqueId()); + return sendGet(url, sdncModifierDetails.getUserId()); + } + + public static CapReqDef getAndParseComponentRequirmentsCapabilities(User user, ComponentReqDetails componentDetails) + throws IOException { + RestResponse getComponentReqCap = getComponentRequirmentsCapabilities(user, componentDetails); + ResourceRestUtils.checkSuccess(getComponentReqCap); + CapReqDef capReqDef = ResponseParser.parseToObject(getComponentReqCap.getResponse(), CapReqDef.class); + return capReqDef; + } +} diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ConsumerRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ConsumerRestUtils.java new file mode 100644 index 0000000000..1b93d8d778 --- /dev/null +++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ConsumerRestUtils.java @@ -0,0 +1,206 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.utils.rest; + +import static org.testng.AssertJUnit.assertEquals; + +import java.util.Map; + +import org.codehaus.jackson.map.ObjectMapper; +import org.openecomp.sdc.be.datatypes.elements.ConsumerDataDefinition; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.api.Urls; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.utils.Utils; + +import com.google.gson.Gson; + +public class ConsumerRestUtils extends BaseRestUtils { + + public static final int STATUS_CODE_SUCCESS = 200; + public static final int STATUS_CODE_CREATED = 201; + public static final int STATUS_CODE_DELETE = 204; + public static final int STATUS_CODE_NOT_FOUND = 404; + Utils utils = new Utils(); + private static Long expectedsLastupdatedtime; + private static Long expectedLastAuthenticationTime; + + public static RestResponse createConsumer(ConsumerDataDefinition consumerDataDefinition, User sdncModifierDetails) throws Exception { + + Config config = Utils.getConfig(); + String url = String.format(Urls.CREATE_CONSUMER, config.getCatalogBeHost(), config.getCatalogBePort()); + + String userId = sdncModifierDetails.getUserId(); + + Map<String, String> headersMap = prepareHeadersMap(userId); + + Gson gson = new Gson(); + String userBodyJson = gson.toJson(consumerDataDefinition); + + HttpRequest http = new HttpRequest(); + // System.out.println(url); + // System.out.println(userBodyJson); + RestResponse createConsumerResponse = http.httpSendPost(url, userBodyJson, headersMap); + if (createConsumerResponse.getErrorCode() == STATUS_CODE_CREATED) { + ConsumerDataDefinition getConsumerDataObject = parseComsumerResp(createConsumerResponse); + consumerDataDefinition.setConsumerDetailsLastupdatedtime(getConsumerDataObject.getConsumerDetailsLastupdatedtime()); + consumerDataDefinition.setConsumerLastAuthenticationTime(getConsumerDataObject.getConsumerLastAuthenticationTime()); + consumerDataDefinition.setLastModfierAtuid(getConsumerDataObject.getLastModfierAtuid()); + } + return createConsumerResponse; + } + + public static RestResponse createConsumerHttpCspAtuUidIsMissing(ConsumerDataDefinition consumerDataDefinition, User sdncModifierDetails) throws Exception { + + Config config = Utils.getConfig(); + String url = String.format(Urls.CREATE_CONSUMER, config.getCatalogBeHost(), config.getCatalogBePort()); + + String userId = sdncModifierDetails.getUserId(); + Map<String, String> headersMap = prepareHeadersMap(userId); + headersMap.remove("USER_ID"); + Gson gson = new Gson(); + String userBodyJson = gson.toJson(consumerDataDefinition); + HttpRequest http = new HttpRequest(); + // System.out.println(url); + // System.out.println(userBodyJson); + RestResponse createConsumerResponse = http.httpSendPost(url, userBodyJson, headersMap); + if (createConsumerResponse.getErrorCode() == STATUS_CODE_CREATED) { + ConsumerDataDefinition getConsumerDataObject = parseComsumerResp(createConsumerResponse); + consumerDataDefinition.setConsumerDetailsLastupdatedtime(getConsumerDataObject.getConsumerDetailsLastupdatedtime()); + consumerDataDefinition.setConsumerLastAuthenticationTime(getConsumerDataObject.getConsumerLastAuthenticationTime()); + consumerDataDefinition.setLastModfierAtuid(getConsumerDataObject.getLastModfierAtuid()); + } + return createConsumerResponse; + } + + public static RestResponse deleteConsumerHttpCspAtuUidIsMissing(ConsumerDataDefinition consumerDataDefinition, User sdncModifierDetails) throws Exception { + + Config config = Utils.getConfig(); + String url = String.format(Urls.DELETE_CONSUMER, config.getCatalogBeHost(), config.getCatalogBePort(), consumerDataDefinition.getConsumerName()); + + String userId = sdncModifierDetails.getUserId(); + Map<String, String> headersMap = prepareHeadersMap(userId); + headersMap.remove("USER_ID"); + Gson gson = new Gson(); + String userBodyJson = gson.toJson(consumerDataDefinition); + HttpRequest http = new HttpRequest(); + // System.out.println(url); + // System.out.println(userBodyJson); + RestResponse deleteConsumerResponse = http.httpSendDelete(url, headersMap); + return deleteConsumerResponse; + } + + public static ConsumerDataDefinition parseComsumerResp(RestResponse restResponse) throws Exception { + + String bodyToParse = restResponse.getResponse(); + ObjectMapper mapper = new ObjectMapper(); + try { + ConsumerDataDefinition component = mapper.readValue(bodyToParse, ConsumerDataDefinition.class); + return component; + } catch (Exception e) { + e.printStackTrace(); + } + + return null; + } + + public static RestResponse deleteConsumer(ConsumerDataDefinition consumerDataDefinition, User sdncModifierDetails) throws Exception { + + Config config = Utils.getConfig(); + String url = String.format(Urls.DELETE_CONSUMER, config.getCatalogBeHost(), config.getCatalogBePort(), consumerDataDefinition.getConsumerName()); + + String userId = sdncModifierDetails.getUserId(); + + Map<String, String> headersMap = prepareHeadersMap(userId); + HttpRequest http = new HttpRequest(); + // System.out.println(url); + RestResponse deleteConsumerResponse = http.httpSendDelete(url, headersMap); + return deleteConsumerResponse; + } + + public static RestResponse getConsumer(ConsumerDataDefinition consumerDataDefinition, User sdncModifierDetails) throws Exception { + + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_CONSUMER, config.getCatalogBeHost(), config.getCatalogBePort(), consumerDataDefinition.getConsumerName()); + + String userId = sdncModifierDetails.getUserId(); + + Map<String, String> headersMap = prepareHeadersMap(userId); + HttpRequest http = new HttpRequest(); + // System.out.println(url); + RestResponse getConsumerResponse = http.httpSendGet(url, headersMap); + return getConsumerResponse; + } + + public static void validateConsumerReqVsResp(ConsumerDataDefinition consumerDefinition, ConsumerDataDefinition getConsumerDataObject) { + + String expected; + + expected = consumerDefinition.getConsumerName(); + assertEquals("consumer name - ", expected, getConsumerDataObject.getConsumerName()); + + expected = consumerDefinition.getConsumerPassword().toLowerCase(); + assertEquals("consumer password - ", expected, getConsumerDataObject.getConsumerPassword()); + + expected = consumerDefinition.getLastModfierAtuid(); + assertEquals("consumer Last Modfier Atuid - ", expected, getConsumerDataObject.getLastModfierAtuid()); + + expected = consumerDefinition.getConsumerSalt(); + assertEquals("consumer Salt - ", expected, getConsumerDataObject.getConsumerSalt()); + + expectedsLastupdatedtime = consumerDefinition.getConsumerDetailsLastupdatedtime(); + assertEquals("consumer Last updated time - ", expectedsLastupdatedtime, getConsumerDataObject.getConsumerDetailsLastupdatedtime()); + + expectedLastAuthenticationTime = consumerDefinition.getConsumerLastAuthenticationTime(); + assertEquals("consumer Last authentication time - ", expectedLastAuthenticationTime, getConsumerDataObject.getConsumerLastAuthenticationTime()); + } + + ///// New + public enum EcompConsumerAuditJsonKeysEnum { + ACTION("ACTION"), MODIFIER("MODIFIER"), ECOMP_USER("ECOMP_USER"), STATUS("STATUS"), DESC("DESCRIPTION"); + private String auditJsonKeyName; + + private EcompConsumerAuditJsonKeysEnum(String auditJsonKeyName) { + this.auditJsonKeyName = auditJsonKeyName; + } + + public String getAuditJsonKeyName() { + return auditJsonKeyName.toLowerCase(); + } + } + + /* + * protected void resourceArtifatAuditSuccess(String action, ArtifactReqDetails artifact, ResourceReqDetails resourceDetails , User user) throws Exception { ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = + * Convertor.constructFieldsForAuditValidation(resourceDetails, resourceDetails.getVersion(), user); String auditAction = action; expectedResourceAuditJavaObject.setAction(auditAction); expectedResourceAuditJavaObject.setPrevState(""); + * expectedResourceAuditJavaObject.setPrevVersion(""); expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum. NOT_CERTIFIED_CHECKOUT).toString()); expectedResourceAuditJavaObject.setStatus("200"); + * expectedResourceAuditJavaObject.setDesc("OK"); expectedResourceAuditJavaObject.setArtifactName(artifact.getArtifactName( )); AuditUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null); } + */ + + /* + * protected void resourceArtifatValidateAuditWithErrorMessage(String actionStatus, ResourceReqDetails resourceDetails, String auditAction, String setCurrState, Object ... variables)throws Exception { ErrorInfo errorInfo = + * utils.parseYaml(actionStatus); ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor.constructFieldsForAuditValidation(resourceDetails, resourceDetails.getVersion(), sdncUserDetails); + * expectedResourceAuditJavaObject.setAction(auditAction); expectedResourceAuditJavaObject.setPrevState(""); expectedResourceAuditJavaObject.setPrevVersion(""); expectedResourceAuditJavaObject.setCurrState(setCurrState); + * expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString()) ; expectedResourceAuditJavaObject.setDesc(errorInfo.getAuditDesc(variables) ); expectedResourceAuditJavaObject.setArtifactName(""); + * AuditUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null); } + */ +} diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/EcompUserRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/EcompUserRestUtils.java new file mode 100644 index 0000000000..a71711dde6 --- /dev/null +++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/EcompUserRestUtils.java @@ -0,0 +1,255 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.utils.rest; + +import java.io.IOException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.openecomp.portalsdk.core.restful.domain.EcompRole; +import org.openecomp.portalsdk.core.restful.domain.EcompUser; +import org.openecomp.sdc.ci.tests.api.Urls; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum; +import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.run.StartTest; +import org.openecomp.sdc.ci.tests.utils.Utils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.gson.Gson; + +public class EcompUserRestUtils extends BaseRestUtils { + + static Gson gson = new Gson(); + + static Logger logger = LoggerFactory.getLogger(UserRestUtils.class.getName()); + static String contentTypeHeaderData = "application/json"; + static String acceptHeaderDate = "application/json"; + static String ecompUsername = "12345"; + static String ecompPassword = "12345"; + + public EcompUserRestUtils() { + super(); + + StartTest.enableLogger(); + } + + public static RestResponse pushUser(EcompUser ecompUser) throws IOException { + Config config = Utils.getConfig(); + + Map<String, String> headersMap = new HashMap<String, String>(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + headersMap.put(HttpHeaderEnum.ECOMP_USERNAME.getValue(), ecompUsername); + headersMap.put(HttpHeaderEnum.ECOMP_PASSWORD.getValue(), ecompPassword); + + String userBodyJson = gson.toJson(ecompUser); + + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.ECOMP_PUSH_USER, config.getCatalogBeHost(), config.getCatalogBePort()); + + logger.debug("Send POST request to create user: {}", url); + logger.debug("User body: {}", userBodyJson); + logger.debug("User headers: {}", headersMap); + + RestResponse sendPushUserResponse = http.httpSendPost(url, userBodyJson, headersMap); + + return sendPushUserResponse; + } + + /* + * loginId - equals to userId + */ + public static RestResponse editUser(String loginId, EcompUser ecompUser) throws IOException { + Config config = Utils.getConfig(); + + Map<String, String> headersMap = new HashMap<String, String>(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + headersMap.put(HttpHeaderEnum.ECOMP_USERNAME.getValue(), ecompUsername); + headersMap.put(HttpHeaderEnum.ECOMP_PASSWORD.getValue(), ecompPassword); + + String userBodyJson = gson.toJson(ecompUser); + + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.ECOMP_EDIT_USER, config.getCatalogBeHost(), config.getCatalogBePort(), loginId); + + logger.debug("Send POST request to edit user: {}", url); + logger.debug("User body: {}", userBodyJson); + logger.debug("User headers: {}", headersMap); + + RestResponse sendEditUserResponse = http.httpSendPost(url, userBodyJson, headersMap); + + return sendEditUserResponse; + } + + /* + * loginId - equals to userId + */ + public static RestResponse getUser(String loginId) throws IOException { + Config config = Utils.getConfig(); + + Map<String, String> headersMap = new HashMap<String, String>(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + headersMap.put(HttpHeaderEnum.ECOMP_USERNAME.getValue(), ecompUsername); + headersMap.put(HttpHeaderEnum.ECOMP_PASSWORD.getValue(), ecompPassword); + + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.ECOMP_GET_USER, config.getCatalogBeHost(), config.getCatalogBePort(), loginId); + + logger.debug("Send GET request to get user: {}", url); + logger.debug("User headers: {}", headersMap); + + RestResponse sendGetUserRequest = http.httpSendGet(url, headersMap); + + return sendGetUserRequest; + } + + public static RestResponse getAllUsers() throws IOException { + Config config = Utils.getConfig(); + + Map<String, String> headersMap = new HashMap<String, String>(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + headersMap.put(HttpHeaderEnum.ECOMP_USERNAME.getValue(), ecompUsername); + headersMap.put(HttpHeaderEnum.ECOMP_PASSWORD.getValue(), ecompPassword); + + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.ECOMP_GET_ALL_USERS, config.getCatalogBeHost(), config.getCatalogBePort()); + + logger.debug("Send POST request to get all users: {}", url); + logger.debug("User headers: {}" , headersMap); + + RestResponse sendGetAllUsersRequest = http.httpSendGet(url, headersMap); + + return sendGetAllUsersRequest; + } + + public static RestResponse getAllAvailableRoles() throws IOException { + Config config = Utils.getConfig(); + + Map<String, String> headersMap = new HashMap<String, String>(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + headersMap.put(HttpHeaderEnum.ECOMP_USERNAME.getValue(), ecompUsername); + headersMap.put(HttpHeaderEnum.ECOMP_PASSWORD.getValue(), ecompPassword); + + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.ECOMP_GET_ALL_AVAILABLE_ROLES, config.getCatalogBeHost(), + config.getCatalogBePort()); + + logger.debug("Send GET request to get all available roles: {}", url); + logger.debug("User headers: {}", headersMap); + + RestResponse sendUpdateUserRequest = http.httpSendGet(url, headersMap); + + return sendUpdateUserRequest; + } + + /* + * loginId - equals to userId + */ + public static RestResponse pushUserRoles(String loginId, List<EcompRole> roles) throws IOException { + Config config = Utils.getConfig(); + + Map<String, String> headersMap = new HashMap<String, String>(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + headersMap.put(HttpHeaderEnum.ECOMP_USERNAME.getValue(), ecompUsername); + headersMap.put(HttpHeaderEnum.ECOMP_PASSWORD.getValue(), ecompPassword); + + String roleBodyJson = gson.toJson(roles); + + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.ECOMP_PUSH_USER_ROLES, config.getCatalogBeHost(), config.getCatalogBePort(), + loginId); + + logger.debug("Send POST request to push user role: {}", url); + logger.debug("Roles body: {}", roleBodyJson); + logger.debug("Request headers: {}", headersMap); + + RestResponse sendpushUserRolesResponse = http.httpSendPost(url, roleBodyJson, headersMap); + + return sendpushUserRolesResponse; + } + + /* + * loginId - equals to userId + */ + public static RestResponse getUserRoles(String loginId) throws IOException { + Config config = Utils.getConfig(); + + Map<String, String> headersMap = new HashMap<String, String>(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + headersMap.put(HttpHeaderEnum.ECOMP_USERNAME.getValue(), ecompUsername); + headersMap.put(HttpHeaderEnum.ECOMP_PASSWORD.getValue(), ecompPassword); + + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.ECOMP_GET_USER_ROLES, config.getCatalogBeHost(), config.getCatalogBePort(), + loginId); + + logger.debug("Send GET request to get user roles: {}", url); + logger.debug("User headers: {}", headersMap); + + RestResponse sendGetUserRolesRequest = http.httpSendGet(url, headersMap); + + return sendGetUserRolesRequest; + } + + // TODO !!!!!!!!!!!!!! + /* + * Ask Eli if implementation of users is needed DELETE ECOMP USER + */ + + /* + * public static void main(String[] args) { EcompUser ecompUser = new + * EcompUser(); ecompUser.setFirstName("Test"); + * ecompUser.setLastName("Testovich"); + * ecompUser.setEmail("ttes@intl.sdc.com"); ecompUser.setLoginId("tt0004"); + * ecompUser.setActive(true); + * + * EcompRole roleToUpdate = new EcompRole(); roleToUpdate.setId(new + * Long(6)); roleToUpdate.setName("PRODUCT_STRATEGIST"); List<EcompRole> + * listOfRoles = new LinkedList<>(); listOfRoles.add(roleToUpdate); + * + * try { + * System.out.println("\n-----------------------------\n Testing pushUser"); + * System.out.println(pushUser(ecompUser)); + * System.out.println("\n-----------------------------\n Testing editUser"); + * // System.out.println(editUser("tt0001", ecompUser)); + * System.out.println("\n-----------------------------\n Testing getUser"); + * // System.out.println(getUser(ecompUser.getLoginId())); System.out. + * println("\n-----------------------------\n Testing getAllUsers"); // + * System.out.println(getAllUsers()); System.out. + * println("\n-----------------------------\n Testing getAllAvailableRoles" + * ); // System.out.println(getAllAvailableRoles().toString()); System.out. + * println("\n-----------------------------\n Testing pushUserRoles"); // + * System.out.println(pushUserRoles("tt0001", listOfRoles)); System.out. + * println("\n-----------------------------\n Testing getUserRoles"); // + * System.out.println(getUserRoles("tt0001")); } catch (IOException e) { // + * TODO Auto-generated catch block e.printStackTrace(); } } + */ +} diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/GroupRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/GroupRestUtils.java new file mode 100644 index 0000000000..d79c8e002c --- /dev/null +++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/GroupRestUtils.java @@ -0,0 +1,61 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.utils.rest; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.api.Urls; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.utils.Utils; + +import com.google.gson.Gson; + +public class GroupRestUtils extends BaseRestUtils { + public static String acceptHeaderDate = "application/json"; + static Config config = Config.instance(); + public static Gson gson = new Gson(); + + public static RestResponse getGroupById(Component component, String groupId, User user) throws IOException { + + Config config = Utils.getConfig(); + + Map<String, String> headersMap = new HashMap<String, String>(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderData); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), user.getUserId()); + + String url = String.format(Urls.GET_GROUP_BY_ID, config.getCatalogBeHost(), config.getCatalogBePort(), + ComponentTypeEnum.findParamByType(component.getComponentType()), component.getUniqueId(), groupId); + + RestResponse sendGetServerRequest = sendGet(url, user.getUserId(), headersMap); + + return sendGetServerRequest; + + } + +} diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ImportRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ImportRestUtils.java new file mode 100644 index 0000000000..3ce48962fd --- /dev/null +++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ImportRestUtils.java @@ -0,0 +1,339 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.utils.rest; + +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertNotNull; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +import org.apache.commons.io.IOUtils; +import org.apache.http.HttpEntity; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.mime.MultipartEntityBuilder; +import org.apache.http.entity.mime.content.FileBody; +import org.apache.http.entity.mime.content.StringBody; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.codehaus.jettison.json.JSONException; +import org.openecomp.sdc.be.dao.rest.HttpRestClient; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.api.Urls; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo; +import org.openecomp.sdc.ci.tests.datatypes.enums.ImportTestTypesEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.utils.Utils; +import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils; +import org.openecomp.sdc.common.rest.api.RestResponseAsByteArray; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ImportRestUtils extends BaseRestUtils { + + private static Logger log = LoggerFactory.getLogger(ImportRestUtils.class.getName()); + private static Properties downloadCsarHeaders = new Properties(); + + static { + downloadCsarHeaders.put("Accept", "application/octet-stream"); + } + + @SuppressWarnings("unused") + private static Integer importNormativeResource(NormativeTypesEnum resource, UserRoleEnum userRole) throws IOException { + Config config = Utils.getConfig(); + CloseableHttpResponse response = null; + MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create(); + + mpBuilder.addPart("resourceZip", new FileBody(getTestZipFile(resource.getFolderName()))); + mpBuilder.addPart("resourceMetadata", new StringBody(getTestJsonStringOfFile(resource.getFolderName(), resource.getFolderName() + ".json"), ContentType.APPLICATION_JSON)); + + String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE, config.getCatalogBeHost(), config.getCatalogBePort()); + + CloseableHttpClient client = HttpClients.createDefault(); + try { + HttpPost httpPost = new HttpPost(url); + httpPost.addHeader("USER_ID", userRole.getUserId()); + httpPost.setEntity(mpBuilder.build()); + response = client.execute(httpPost); + return response.getStatusLine().getStatusCode(); + } finally { + closeResponse(response); + closeHttpClient(client); + + } + } + + public static RestResponse importResourceByName(ResourceReqDetails resourceDetails, User importer) throws Exception { + Config config = Utils.getConfig(); + CloseableHttpResponse response = null; + MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create(); + + mpBuilder.addPart("resourceZip", new FileBody(getTestZipFile(resourceDetails.getName()))); + mpBuilder.addPart("resourceMetadata", new StringBody(getTestJsonStringOfFile(resourceDetails.getName(), resourceDetails.getName() + ".json"), ContentType.APPLICATION_JSON)); + + String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE, config.getCatalogBeHost(), config.getCatalogBePort()); + + CloseableHttpClient client = HttpClients.createDefault(); + try { + HttpPost httpPost = new HttpPost(url); + RestResponse restResponse = new RestResponse(); + httpPost.addHeader("USER_ID", importer.getUserId()); + httpPost.setEntity(mpBuilder.build()); + response = client.execute(httpPost); + HttpEntity entity = response.getEntity(); + String responseBody = null; + if (entity != null) { + InputStream instream = entity.getContent(); + StringWriter writer = new StringWriter(); + IOUtils.copy(instream, writer); + responseBody = writer.toString(); + try { + + } finally { + instream.close(); + } + } + + restResponse.setErrorCode(response.getStatusLine().getStatusCode()); + restResponse.setResponse(responseBody); + + if (restResponse.getErrorCode() == STATUS_CODE_CREATED) { + resourceDetails.setUUID(ResponseParser.getUuidFromResponse(restResponse)); + resourceDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(restResponse)); + resourceDetails.setVersion(ResponseParser.getVersionFromResponse(restResponse)); + resourceDetails.setCreatorUserId(importer.getUserId()); + resourceDetails.setCreatorFullName(importer.getFullName()); + } + + return restResponse; + + } finally { + closeResponse(response); + closeHttpClient(client); + + } + + } + + public static RestResponse importNewResourceByName(String resourceName, UserRoleEnum userRole) throws IOException { + Config config = Utils.getConfig(); + + MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create(); + + mpBuilder.addPart("resourceZip", new FileBody(getTestZipFile(resourceName))); + mpBuilder.addPart("resourceMetadata", new StringBody(getTestJsonStringOfFile(resourceName, resourceName + ".json"), ContentType.APPLICATION_JSON)); + HttpEntity requestEntity = mpBuilder.build(); + String url = String.format(Urls.IMPORT_USER_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort()); + Map<String, String> headers = new HashMap<String, String>(); + headers.put("USER_ID", userRole.getUserId()); + + return HttpRequest.sendHttpPostWithEntity(requestEntity, url, headers); + } + + public static RestResponse importNormativeResourceByName(String resourceName, UserRoleEnum userRole) throws IOException { + Config config = Utils.getConfig(); + + MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create(); + + mpBuilder.addPart("resourceZip", new FileBody(getTestZipFile(resourceName))); + mpBuilder.addPart("resourceMetadata", new StringBody(getTestJsonStringOfFile(resourceName, resourceName + ".json"), ContentType.APPLICATION_JSON)); + HttpEntity requestEntity = mpBuilder.build(); + String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE, config.getCatalogBeHost(), config.getCatalogBePort()); + Map<String, String> headers = new HashMap<String, String>(); + headers.put("USER_ID", userRole.getUserId()); + + return HttpRequest.sendHttpPostWithEntity(requestEntity, url, headers); + } + + public static RestResponse importTestResource(ImportTestTypesEnum resource, UserRoleEnum userRole) throws IOException { + Config config = Utils.getConfig(); + CloseableHttpResponse response = null; + MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create(); + + mpBuilder.addPart("resourceZip", new FileBody(getTestZipFile(resource.getFolderName()))); + mpBuilder.addPart("resourceMetadata", new StringBody(getTestJsonStringOfFile(resource.getFolderName(), resource.getFolderName() + ".json"), ContentType.APPLICATION_JSON)); + + String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE, config.getCatalogBeHost(), config.getCatalogBePort()); + + CloseableHttpClient client = HttpClients.createDefault(); + try { + HttpPost httpPost = new HttpPost(url); + RestResponse restResponse = new RestResponse(); + httpPost.addHeader("USER_ID", UserRoleEnum.ADMIN.getUserId()); + httpPost.setEntity(mpBuilder.build()); + response = client.execute(httpPost); + HttpEntity entity = response.getEntity(); + String responseBody = null; + if (entity != null) { + InputStream instream = entity.getContent(); + StringWriter writer = new StringWriter(); + IOUtils.copy(instream, writer); + responseBody = writer.toString(); + try { + + } finally { + instream.close(); + } + } + + restResponse.setErrorCode(response.getStatusLine().getStatusCode()); + // restResponse.setResponse(response.getEntity().toString()); + restResponse.setResponse(responseBody); + return restResponse; + } finally { + closeResponse(response); + closeHttpClient(client); + + } + } + + public static Boolean removeNormativeTypeResource(NormativeTypesEnum current) throws FileNotFoundException, IOException, ClientProtocolException { + User user = new User(UserRoleEnum.ADMIN.getFirstName(), UserRoleEnum.ADMIN.getLastName(), UserRoleEnum.ADMIN.getUserId(), null, null, null); + RestResponse deleteResponse = ResourceRestUtils.deleteResourceByNameAndVersion(user, current.getNormativeName(), "1.0"); + if (deleteResponse.getErrorCode() == 200) { + return true; + } + return false; + } + + public static void validateImportTestTypesResp(ImportTestTypesEnum currResource, RestResponse restResponse) throws IOException, JSONException { + + // assertTrue( status != ResourceUtils.STATUS_CODE_IMPORT_SUCCESS ); + + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(currResource.getActionStatus().name()); + + assertNotNull("check response object is not null after create service", restResponse); + assertNotNull("check error code exists in response after create service", restResponse.getErrorCode()); + assertEquals("Check response code after create service", errorInfo.getCode(), restResponse.getErrorCode()); + + // validate create service response vs actual + List<String> variables = (currResource.getErrorParams() != null ? currResource.getErrorParams() : new ArrayList<String>()); + if (restResponse.getErrorCode() != 200) { + ErrorValidationUtils.checkBodyResponseOnError(currResource.getActionStatus().name(), variables, restResponse.getResponse()); + } + } + + private static String getTestJsonStringOfFile(String folderName, String fileName) throws IOException { + // String sourceDir = "src/test/resources/CI/importResourceTests"; + Config config = Utils.getConfig(); + String sourceDir = config.getImportResourceTestsConfigDir(); + java.nio.file.Path filePath = FileSystems.getDefault().getPath(sourceDir + File.separator + folderName, fileName); + byte[] fileContent = Files.readAllBytes(filePath); + String content = new String(fileContent); + return content; + } + + private static File getTestZipFile(String elementName) throws IOException { + Config config = Utils.getConfig(); + String sourceDir = config.getImportResourceTestsConfigDir(); + java.nio.file.Path filePath = FileSystems.getDefault().getPath(sourceDir + File.separator + elementName, "normative-types-new-" + elementName + ".zip"); + return filePath.toFile(); + } + + private static void closeHttpClient(CloseableHttpClient client) { + try { + if (client != null) { + client.close(); + } + } catch (IOException e) { + log.debug("failed to close client or response: ", e); + } + } + + private static void closeResponse(CloseableHttpResponse response) { + try { + if (response != null) { + response.close(); + } + } catch (IOException e) { + log.debug("failed to close client or response: {}", e); + } + } + + public static RestResponseAsByteArray getCsar(String csarUid, User sdncModifierDetails) throws Exception { + + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_CSAR_USING_SIMULATOR, config.getCatalogBeHost(), config.getCatalogBePort(), csarUid); + + String userId = sdncModifierDetails.getUserId(); + + Map<String, String> headersMap = prepareHeadersMap(userId); + + // Gson gson = new Gson(); + // String userBodyJson = gson.toJson(resourceDetails); + HttpRequest http = new HttpRequest(); + // System.out.println(url); + // System.out.println(userBodyJson); + + HttpRestClient httpRestClient = new HttpRestClient(); + + for (Map.Entry<String, String> mapEntry : headersMap.entrySet()) { + + downloadCsarHeaders.put(mapEntry.getKey(), mapEntry.getValue()); + } + RestResponseAsByteArray doGetAsByteArray = httpRestClient.doGetAsByteArray(url, downloadCsarHeaders); + // RestResponse getCsar = http.httpSendGet(url, headersMap); + + return doGetAsByteArray; + + } + + private static File getGroupTypeZipFile(String elementName) throws IOException { + Config config = Utils.getConfig(); + String sourceDir = config.getImportResourceTestsConfigDir(); + sourceDir += File.separator + ".." + File.separator + "importTypesTest" + File.separator; + java.nio.file.Path filePath = FileSystems.getDefault().getPath(sourceDir + File.separator + elementName, elementName + ".zip"); + return filePath.toFile(); + } + + public static RestResponse importNewGroupTypeByName(String groupTypeName, UserRoleEnum userRole) throws IOException { + Config config = Utils.getConfig(); + + MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create(); + + mpBuilder.addPart("groupTypesZip", new FileBody(getGroupTypeZipFile(groupTypeName))); + HttpEntity requestEntity = mpBuilder.build(); + String url = String.format(Urls.IMPORT_GROUP_TYPE, config.getCatalogBeHost(), config.getCatalogBePort()); + Map<String, String> headers = new HashMap<String, String>(); + headers.put("USER_ID", userRole.getUserId()); + + return HttpRequest.sendHttpPostWithEntity(requestEntity, url, headers); + } + +} diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/InputsRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/InputsRestUtils.java new file mode 100644 index 0000000000..de7be077d1 --- /dev/null +++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/InputsRestUtils.java @@ -0,0 +1,122 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.utils.rest; + +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstInputsMap; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.ci.tests.api.Urls; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.utils.Utils; +import org.openecomp.sdc.ci.tests.utils.general.ElementFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.gson.Gson; + +/** + * RestUtils for inputs + * + * @author il0695 + * + */ +public class InputsRestUtils extends BaseRestUtils { + + @SuppressWarnings("unused") + private static Logger logger = LoggerFactory.getLogger(InputsRestUtils.class.getName()); + + /** + * Add inputs to service + * + * @param component + * @param inputs + * @param userRole + * @return {@link org.openecomp.sdc.ci.tests.datatypes.http.RestResponse} + * @throws Exception + */ + public static RestResponse addInput(Component component, ComponentInstInputsMap inputs, UserRoleEnum userRole) throws Exception { + Config config = Utils.getConfig(); + String url = String.format(Urls.ADD_INPUTS, config.getCatalogBeHost(), config.getCatalogBePort(), ComponentTypeEnum.findParamByType(component.getComponentType()), component.getUniqueId()); + String json = new Gson().toJson(inputs); + return sendPost(url, json, userRole.getUserId(), acceptHeaderData); + } + + /** + * Get all Component inputs + * + * @param component + * @return {@link org.openecomp.sdc.ci.tests.datatypes.http.RestResponse} + * @throws Exception + */ + public static RestResponse getComponentInputs(Component component) throws Exception { + Config config = Utils.getConfig(); + //services/{componentId}/inputs + String url = String.format(Urls.GET_COMPONENT_INPUTS, config.getCatalogBeHost(), config.getCatalogBePort(), component.getUniqueId()); + return sendGet(url, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER).getUserId()); + } + + /** + * Get all inputs of component instance + * + * @param parentComponent + * @param componentInstance + * @return {@link org.openecomp.sdc.ci.tests.datatypes.http.RestResponse} + * @throws Exception + */ + public static RestResponse getComponentInstanceInputs(Component parentComponent, ComponentInstance componentInstance) throws Exception { + Config config = Utils.getConfig(); + //{componentType}/{componentId}/componentInstances/{instanceId}/{originComonentUid}/inputs + String url = String.format(Urls.GET_COMPONENT_INSTANCE_INPUTS, config.getCatalogBeHost(), config.getCatalogBePort(), ComponentTypeEnum.findParamByType(parentComponent.getComponentType()), parentComponent.getUniqueId(), componentInstance.getUniqueId(), componentInstance.getComponentUid()); + return sendGet(url, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER).getUserId()); + } + + /** + * Delete input from component + * + * @param parentComponent + * @param inputId + * @return {@link org.openecomp.sdc.ci.tests.datatypes.http.RestResponse} + * @throws Exception + */ + public static RestResponse deleteInputFromComponent(Component parentComponent, String inputId) throws Exception { + return deleteInputFromComponent(ComponentTypeEnum.findParamByType(parentComponent.getComponentType()), parentComponent.getUniqueId(), inputId); + } + + /** + * Delete input from component + * + * @param componentType + * @param componentId + * @param inputUniqueId + * @return {@link org.openecomp.sdc.ci.tests.datatypes.http.RestResponse} + * @throws Exception + */ + public static RestResponse deleteInputFromComponent(String componentType, String componentId, String inputUniqueId) throws Exception { + Config config = Utils.getConfig(); + //{componentType}/{componentId}/delete/{inputId}/input + String url = String.format(Urls.DELETE_INPUT_BY_ID, config.getCatalogBeHost(), config.getCatalogBePort(), componentType, componentId, inputUniqueId); + return sendDelete(url, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER).getUserId()); + } + +} diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/LifecycleRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/LifecycleRestUtils.java new file mode 100644 index 0000000000..34651c1b7a --- /dev/null +++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/LifecycleRestUtils.java @@ -0,0 +1,360 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.utils.rest; + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import org.json.simple.JSONObject; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.DistributionStatusEnum; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.Product; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.api.Urls; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.ProductReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum; +import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.utils.Utils; +import org.openecomp.sdc.ci.tests.utils.general.ElementFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class LifecycleRestUtils extends BaseRestUtils { + private static Logger logger = LoggerFactory.getLogger(LifecycleRestUtils.class.getName()); + public static final String COMMENT = "comment"; + + public static RestResponse changeResourceState(ResourceReqDetails resourceDetails, User sdncModifierDetails, + String version, LifeCycleStatesEnum LifeCycleStatesEnum) throws IOException { + return changeResourceState(resourceDetails, sdncModifierDetails, LifeCycleStatesEnum, + createLifecycleCommentJson(COMMENT)); + } + + public static RestResponse changeResourceState(ResourceReqDetails resourceDetails, User sdncModifierDetails, + String version, LifeCycleStatesEnum LifeCycleStatesEnum, String LifecycleChangeInfo) throws IOException { + + return changeResourceState(resourceDetails, sdncModifierDetails, LifeCycleStatesEnum, LifecycleChangeInfo); + + } + + public static RestResponse changeResourceState(ResourceReqDetails resourceDetails, User sdncModifierDetails, + LifeCycleStatesEnum LifeCycleStatesEnum) throws IOException { + + return changeResourceState(resourceDetails, sdncModifierDetails, LifeCycleStatesEnum, + createLifecycleCommentJson(COMMENT)); + + } + + public static RestResponse changeResourceState(ResourceReqDetails resourceDetails, String modifierUserId, + LifeCycleStatesEnum LifeCycleStatesEnum) throws IOException { + User user = new User(); + user.setUserId(modifierUserId); + return changeResourceState(resourceDetails, user, LifeCycleStatesEnum, createLifecycleCommentJson(COMMENT)); + } + + private static RestResponse changeResourceState(ResourceReqDetails resourceDetails, User sdncModifierDetails, + LifeCycleStatesEnum LifeCycleStatesEnum, String LifecycleChangeInfo) throws IOException { + Config config = Utils.getConfig(); + String url = String.format(Urls.CHANGE_RESOURCE_LIFECYCLE_STATE, config.getCatalogBeHost(), + config.getCatalogBePort(), resourceDetails.getUniqueId(), LifeCycleStatesEnum); + // System.out.println("url: " + url); + + RestResponse LifeCycleStatesEnumResourceResponse = sendPost(url, LifecycleChangeInfo, + sdncModifierDetails.getUserId(), acceptHeaderData); + if (LifeCycleStatesEnumResourceResponse.getErrorCode() == STATUS_CODE_SUCCESS) { + String stateFromJsonResponse = ResponseParser + .getValueFromJsonResponse(LifeCycleStatesEnumResourceResponse.getResponse(), "lifecycleState"); + resourceDetails.setVersion(ResponseParser.getVersionFromResponse(LifeCycleStatesEnumResourceResponse)); + resourceDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(LifeCycleStatesEnumResourceResponse)); + if (stateFromJsonResponse != null) { + resourceDetails.setLifecycleState(LifecycleStateEnum.valueOf(stateFromJsonResponse)); + } + } + return LifeCycleStatesEnumResourceResponse; + } + + public static RestResponse changeServiceState(ServiceReqDetails serviceDetails, User sdncModifierDetails, + String version, LifeCycleStatesEnum LifeCycleStatesEnum) throws Exception { + { + return changeServiceState(serviceDetails, sdncModifierDetails, version, LifeCycleStatesEnum, + createLifecycleCommentJson(COMMENT)); + } + } + + public static RestResponse changeServiceState(ServiceReqDetails serviceDetails, User sdncModifierDetails, + LifeCycleStatesEnum LifeCycleStatesEnum) throws Exception { + { + return changeServiceState(serviceDetails, sdncModifierDetails, null, LifeCycleStatesEnum, + createLifecycleCommentJson(COMMENT)); + } + } + + public static RestResponse changeServiceState(ServiceReqDetails serviceDetails, User sdncModifierDetails, + LifeCycleStatesEnum LifeCycleStatesEnum, String lifecycleChangeInfo) throws Exception { + { + return changeServiceState(serviceDetails, sdncModifierDetails, null, LifeCycleStatesEnum, + lifecycleChangeInfo); + } + } + + public static RestResponse changeServiceState(ServiceReqDetails serviceDetails, User sdncModifierDetails, + String version, LifeCycleStatesEnum LifeCycleStatesEnum, String lifecycleChangeInfo) throws Exception { + + Config config = Utils.getConfig(); + Map<String, String> headersMap = prepareHeadersMap(sdncModifierDetails); + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.CHANGE_SERVICE_LIFECYCLE_STATE, config.getCatalogBeHost(), + config.getCatalogBePort(), serviceDetails.getUniqueId(), LifeCycleStatesEnum); + // System.out.println("url: " + url); + RestResponse LifeCycleStatesEnumServiceResponse = http.httpSendPost(url, lifecycleChangeInfo, headersMap); + if (LifeCycleStatesEnumServiceResponse.getErrorCode() == STATUS_CODE_SUCCESS) { + String serviceUniqueId = ResponseParser + .getValueFromJsonResponse(LifeCycleStatesEnumServiceResponse.getResponse(), "uniqueId"); + serviceDetails.setUniqueId(serviceUniqueId); + String serviceVersion = ResponseParser + .getValueFromJsonResponse(LifeCycleStatesEnumServiceResponse.getResponse(), "version"); + serviceDetails.setVersion(serviceVersion); + String stateFromJsonResponse = ResponseParser + .getValueFromJsonResponse(LifeCycleStatesEnumServiceResponse.getResponse(), "lifecycleState"); + serviceDetails.setLifecycleState(LifecycleStateEnum.valueOf(stateFromJsonResponse)); + } + return LifeCycleStatesEnumServiceResponse; + } + + public static RestResponse changeProductState(Product product, User sdncModifierDetails, + LifeCycleStatesEnum LifeCycleStatesEnum, String lifecycleChangeInfo) throws Exception { + { + return _changeProductState(product, sdncModifierDetails, LifeCycleStatesEnum, lifecycleChangeInfo); + } + } + + public static RestResponse changeProductState(Product product, User sdncModifierDetails, + LifeCycleStatesEnum LifeCycleStatesEnum) throws Exception { + { + return _changeProductState(product, sdncModifierDetails, LifeCycleStatesEnum, COMMENT); + } + } + + public static RestResponse changeProductState(ProductReqDetails productDetails, User sdncModifierDetails, + LifeCycleStatesEnum LifeCycleStatesEnum) throws Exception { + Config config = Utils.getConfig(); + String url = String.format(Urls.CHANGE_PRODUCT_LIFECYCLE_STATE, config.getCatalogBeHost(), + config.getCatalogBePort(), productDetails.getUniqueId(), LifeCycleStatesEnum); + RestResponse LifeCycleStatesEnumServiceResponse = sendPost(url, createLifecycleCommentJson(COMMENT), + sdncModifierDetails.getUserId(), acceptHeaderData); + if (LifeCycleStatesEnumServiceResponse.getErrorCode() == STATUS_CODE_SUCCESS) { + String productUniqueId = ResponseParser + .getValueFromJsonResponse(LifeCycleStatesEnumServiceResponse.getResponse(), "uniqueId"); + productDetails.setUniqueId(productUniqueId); + String productVersion = ResponseParser + .getValueFromJsonResponse(LifeCycleStatesEnumServiceResponse.getResponse(), "version"); + productDetails.setVersion(productVersion); + String newLifecycleState = ResponseParser + .getValueFromJsonResponse(LifeCycleStatesEnumServiceResponse.getResponse(), "lifecycleState"); + productDetails.setLifecycleState(LifecycleStateEnum.valueOf(newLifecycleState)); + } + return LifeCycleStatesEnumServiceResponse; + + } + + public static RestResponse changeComponentState(Component component, User sdncModifierDetails, + LifeCycleStatesEnum LifeCycleStatesEnum) throws Exception { + Config config = Utils.getConfig(); + String url = String.format(Urls.CHANGE_COMPONENT_LIFECYCLE_STATE, config.getCatalogBeHost(), + config.getCatalogBePort(), ComponentTypeEnum.findParamByType(component.getComponentType()), + component.getUniqueId(), LifeCycleStatesEnum); + RestResponse LifeCycleStatesEnumServiceResponse = sendPost(url, createLifecycleCommentJson(COMMENT), + sdncModifierDetails.getUserId(), acceptHeaderData); + if (LifeCycleStatesEnumServiceResponse.getErrorCode() == STATUS_CODE_SUCCESS) { + String productUniqueId = ResponseParser + .getValueFromJsonResponse(LifeCycleStatesEnumServiceResponse.getResponse(), "uniqueId"); + component.setUniqueId(productUniqueId); + String productVersion = ResponseParser + .getValueFromJsonResponse(LifeCycleStatesEnumServiceResponse.getResponse(), "version"); + component.setVersion(productVersion); + String newLifecycleState = ResponseParser + .getValueFromJsonResponse(LifeCycleStatesEnumServiceResponse.getResponse(), "lifecycleState"); + component.setLifecycleState(LifecycleStateEnum.valueOf(newLifecycleState)); + } + return LifeCycleStatesEnumServiceResponse; + + } + + public static RestResponse certifyResource(ResourceReqDetails resourceDetails) throws Exception { + RestResponse restResponseResource = LifecycleRestUtils.changeResourceState(resourceDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), LifeCycleStatesEnum.CHECKIN); + // if (restResponseResource.getErrorCode() == 200){ + restResponseResource = LifecycleRestUtils.changeResourceState(resourceDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), LifeCycleStatesEnum.CERTIFICATIONREQUEST); + // }else + // return restResponseResource; + User testerDetails = ElementFactory.getDefaultUser(UserRoleEnum.TESTER); + if (restResponseResource.getErrorCode() == 200) { + restResponseResource = LifecycleRestUtils.changeResourceState(resourceDetails, testerDetails, + LifeCycleStatesEnum.STARTCERTIFICATION); + } else + return restResponseResource; + if (restResponseResource.getErrorCode() == 200) { + restResponseResource = LifecycleRestUtils.changeResourceState(resourceDetails, testerDetails, + LifeCycleStatesEnum.CERTIFY); + if (restResponseResource.getErrorCode() == 200) { + String newVersion = ResponseParser.getVersionFromResponse(restResponseResource); + resourceDetails.setVersion(newVersion); + resourceDetails.setLifecycleState(LifecycleStateEnum.CERTIFIED); + resourceDetails.setLastUpdaterUserId(testerDetails.getUserId()); + resourceDetails.setLastUpdaterFullName(testerDetails.getFullName()); + String uniqueIdFromRresponse = ResponseParser.getUniqueIdFromResponse(restResponseResource); + resourceDetails.setUniqueId(uniqueIdFromRresponse); + } + } + return restResponseResource; + } + + public static RestResponse certifyService(ServiceReqDetails serviceDetails) throws Exception { + RestResponse restResponseService = LifecycleRestUtils.changeServiceState(serviceDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), LifeCycleStatesEnum.CHECKIN); + // if (restResponseService.getErrorCode() == 200){ + restResponseService = LifecycleRestUtils.changeServiceState(serviceDetails, + ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), LifeCycleStatesEnum.CERTIFICATIONREQUEST); + // }else + // return restResponseService; + if (restResponseService.getErrorCode() == 200) { + restResponseService = LifecycleRestUtils.changeServiceState(serviceDetails, + ElementFactory.getDefaultUser(UserRoleEnum.TESTER), LifeCycleStatesEnum.STARTCERTIFICATION); + } else + return restResponseService; + if (restResponseService.getErrorCode() == 200) { + User testerDetails = ElementFactory.getDefaultUser(UserRoleEnum.TESTER); + restResponseService = LifecycleRestUtils.changeServiceState(serviceDetails, testerDetails, + LifeCycleStatesEnum.CERTIFY); + if (restResponseService.getErrorCode() == 200) { + String newVersion = ResponseParser.getVersionFromResponse(restResponseService); + serviceDetails.setVersion(newVersion); + serviceDetails.setLifecycleState(LifecycleStateEnum.CERTIFIED); + serviceDetails.setLastUpdaterUserId(testerDetails.getUserId()); + serviceDetails.setLastUpdaterFullName(testerDetails.getFullName()); + String uniqueIdFromRresponse = ResponseParser.getUniqueIdFromResponse(restResponseService); + serviceDetails.setUniqueId(uniqueIdFromRresponse); + } + } + return restResponseService; + } + + private static RestResponse _changeProductState(Product product, User sdncModifierDetails, + LifeCycleStatesEnum LifeCycleStatesEnum, String lifecycleChangeInfo) throws Exception { + + Config config = Utils.getConfig(); + String url = String.format(Urls.CHANGE_PRODUCT_LIFECYCLE_STATE, config.getCatalogBeHost(), + config.getCatalogBePort(), product.getUniqueId(), LifeCycleStatesEnum); + RestResponse LifeCycleStatesEnumServiceResponse = sendPost(url, createLifecycleCommentJson(lifecycleChangeInfo), + sdncModifierDetails.getUserId(), acceptHeaderData); + + return LifeCycleStatesEnumServiceResponse; + } + + public static String createLifecycleCommentJson(String commentContent) { + String res = null; + if (commentContent != null) { + res = "{\"userRemarks\": \"" + commentContent + "\"}"; + } + return res; + } + + public static void checkLCS_Response(RestResponse response) { + checkStatusCode(response, "change lifecycle request failed", false, STATUS_CODE_SUCCESS); + } + + private static Map<String, String> prepareHeadersMap(User sdncModifierDetails) { + Map<String, String> headersMap = new HashMap<String, String>(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderData); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId()); + return headersMap; + } + + public static RestResponse changeDistributionStatus(ServiceReqDetails serviceDetails, String version, User user, + String userRemarks, DistributionStatusEnum reqDistributionStatus) throws Exception { + String uniqueId = serviceDetails.getUniqueId(); + if (reqDistributionStatus == DistributionStatusEnum.DISTRIBUTION_APPROVED) { + return sendApproveDistribution(user, uniqueId, userRemarks); + } else if (reqDistributionStatus == DistributionStatusEnum.DISTRIBUTION_REJECTED) { + return rejectDistribution(user, userRemarks, uniqueId); + } else if (reqDistributionStatus == DistributionStatusEnum.DISTRIBUTED) { + Config config = Utils.getConfig(); + // String url = + // String.format("http://%s:%s/sdc2/rest/v1/catalog/services/%s/tempUrlToBeDeleted", + // config.getCatalogBeHost(), config.getCatalogBePort(), uniqueId); + String url = String.format(Urls.ACTIVATE_DISTRIBUTION, config.getCatalogBeHost(), config.getCatalogBePort(), + uniqueId, "PROD"); + return sendDistrState(user, userRemarks, url); + } else + return null; + + } + + public static RestResponse sendApproveDistribution(User sdncModifierDetails, String uniqueId, String userRemarks) + throws FileNotFoundException, IOException { + Config config = Utils.getConfig(); + String url = String.format(Urls.APPROVE_DISTRIBUTION, config.getCatalogBeHost(), config.getCatalogBePort(), + uniqueId); + return sendDistrState(sdncModifierDetails, userRemarks, url); + } + + public static RestResponse rejectDistribution(ServiceReqDetails serviceDetails, String version, User user, + String userRemarks) throws Exception { + return rejectDistribution(user, userRemarks, serviceDetails.getUniqueId()); + } + + public static RestResponse rejectDistribution(User user, String userRemarks, String uniqueId) + throws FileNotFoundException, IOException { + Config config = Utils.getConfig(); + String url = String.format(Urls.REJECT_DISTRIBUTION, config.getCatalogBeHost(), config.getCatalogBePort(), + uniqueId); + return sendDistrState(user, userRemarks, url); + } + + private static RestResponse sendDistrState(User user, String userRemarks, String url) throws IOException { + Map<String, String> headersMap = prepareHeadersMap(user); + Map<String, String> userRemarksMap = new HashMap<String, String>(); + userRemarksMap.put("userRemarks", userRemarks); + + String serviceBodyJson = new JSONObject().toJSONString(userRemarksMap); + + HttpRequest httpRequest = new HttpRequest(); + logger.debug(url); + logger.debug("Send POST request to create service: {}", url); + logger.debug("Service body: {}", serviceBodyJson); + logger.debug("Service headers: {}", headersMap); + RestResponse rejectDistributionResponse = httpRequest.httpSendPost(url, serviceBodyJson, headersMap); + + return rejectDistributionResponse; + } + +} diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ProductRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ProductRestUtils.java new file mode 100644 index 0000000000..8e617ed75c --- /dev/null +++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ProductRestUtils.java @@ -0,0 +1,185 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.utils.rest; + +import java.io.IOException; + +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.Product; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.api.Urls; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.ProductReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.utils.Utils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.gson.Gson; + +public class ProductRestUtils extends BaseRestUtils { + private static Gson gson = new Gson(); + private static Logger logger = LoggerFactory.getLogger(ProductRestUtils.class.getName()); + + public static RestResponse createProduct(ProductReqDetails product, User user) throws Exception { + Config config = Utils.getConfig(); + String url = String.format(Urls.CREATE_PRODUCT, config.getCatalogBeHost(), config.getCatalogBePort()); + String serviceBodyJson = gson.toJson(product); + + logger.debug("Send POST request to create service: {}", url); + logger.debug("Service body: {}", serviceBodyJson); + + RestResponse res = sendPost(url, serviceBodyJson, user.getUserId(), acceptHeaderData); + if (res.getErrorCode() == STATUS_CODE_CREATED) { + product.setUniqueId(ResponseParser.getUniqueIdFromResponse(res)); + product.setVersion(ResponseParser.getVersionFromResponse(res)); + product.setUUID(ResponseParser.getUuidFromResponse(res)); + // Creator details never change after component is created - Ella, + // 12/1/2016 + product.setCreatorUserId(user.getUserId()); + product.setCreatorFullName(user.getFullName()); + product.setLastUpdaterFullName(user.getFullName()); + product.setLastUpdaterUserId(user.getUserId()); + product.setLastUpdaterFullName(user.getFullName()); + product.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + product.setVersion("0.1"); + String lastUpdate = ResponseParser.getValueFromJsonResponse(res.getResponse(), "lastUpdateDate"); + product.setLastUpdateDate(Long.parseLong(lastUpdate, 10)); + product.setCreationDate(Long.parseLong(lastUpdate, 10)); + } + return res; + } + + public static RestResponse updateProduct(ProductReqDetails product, User user) throws Exception { + Config config = Utils.getConfig(); + String url = String.format(Urls.UPDATE_PRODUCT, config.getCatalogBeHost(), config.getCatalogBePort(), + product.getUniqueId()); + String serviceBodyJson = gson.toJson(product); + + logger.debug("Send POST request to create service: {}", url); + logger.debug("Service body: {}", serviceBodyJson); + + RestResponse res = sendPut(url, serviceBodyJson, user.getUserId(), acceptHeaderData); + if (res.getErrorCode() == STATUS_CODE_CREATED) { + product.setUniqueId(ResponseParser.getUniqueIdFromResponse(res)); + product.setVersion(ResponseParser.getVersionFromResponse(res)); + product.setUUID(ResponseParser.getUuidFromResponse(res)); + // Creator details never change after component is created - Ella, + // 12/1/2016 + product.setCreatorUserId(user.getUserId()); + product.setCreatorFullName(user.getFullName()); + product.setLastUpdaterFullName(user.getFullName()); + product.setLastUpdaterUserId(user.getUserId()); + product.setLastUpdaterFullName(user.getFullName()); + product.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + String valueFromJsonResponse = ResponseParser.getValueFromJsonResponse(res.getResponse(), "version"); + product.setVersion(valueFromJsonResponse); + String lastUpdate = ResponseParser.getValueFromJsonResponse(res.getResponse(), "lastUpdateDate"); + product.setLastUpdateDate(Long.parseLong(lastUpdate, 10)); + product.setCreationDate(Long.parseLong(lastUpdate, 10)); + } + return res; + } + + public static RestResponse createProduct_Invalid_Json(String userId) throws Exception { + Config config = Utils.getConfig(); + String url = String.format(Urls.CREATE_PRODUCT, config.getCatalogBeHost(), config.getCatalogBePort()); + + RestResponse res = sendPost(url, "kukumuku", userId, acceptHeaderData); + return res; + } + + public static RestResponse deleteProduct(String id, String userId) throws IOException { + + Config config = Utils.getConfig(); + String url = String.format(Urls.DELETE_PRODUCT, config.getCatalogBeHost(), config.getCatalogBePort(), id); + return sendDelete(url, userId); + } + + public static RestResponse getProduct(String productId, String userId) throws Exception { + + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_PRODUCT, config.getCatalogBeHost(), config.getCatalogBePort(), productId); + logger.debug("Send GET request to get product: {}", url); + + return sendGet(url, userId); + } + + public static RestResponse getFollowed(String userId) throws Exception { + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_FOLLWED_LIST, config.getCatalogBeHost(), config.getCatalogBePort()); + logger.debug("Send GET request to get user followed page: {}", url); + return sendGet(url, userId); + + } + + public static RestResponse changeProductLifeCycle(Product product, User userModifier, LifeCycleStatesEnum lifeCycle) + throws Exception { + String checkinComment = "my comment"; + RestResponse changeLifeCycleResponse = LifecycleRestUtils.changeProductState(product, userModifier, lifeCycle, + checkinComment); + if (changeLifeCycleResponse.getErrorCode() == STATUS_CODE_SUCCESS) { + product.setLastUpdaterUserId(userModifier.getUserId()); + product.setLastUpdaterFullName(userModifier.getFullName()); + String latestVersion = ResponseParser.getValueFromJsonResponse(changeLifeCycleResponse.getResponse(), + "version"); + product.setVersion(latestVersion); + String lifecycleState = ResponseParser.getValueFromJsonResponse(changeLifeCycleResponse.getResponse(), + "lifecycleState"); + product.setLifecycleState((LifecycleStateEnum.valueOf(lifecycleState))); + String uniqueId = ResponseParser.getValueFromJsonResponse(changeLifeCycleResponse.getResponse(), + "uniqueId"); + product.setUniqueId(uniqueId); + String lastUpdate = ResponseParser.getValueFromJsonResponse(changeLifeCycleResponse.getResponse(), + "lastUpdateDate"); + product.setLastUpdateDate((Long.parseLong(lastUpdate, 10))); + String uuid = ResponseParser.getValueFromJsonResponse(changeLifeCycleResponse.getResponse(), "uuid"); + product.setUUID(uuid); + } + return changeLifeCycleResponse; + } + + public static RestResponse changeServiceInstanceVersion(String componentUniqueId, + String serviceInstanceToReplaceUniqueId, String serviceUniqueId, User sdncModifierDetails, + ComponentTypeEnum componentType) throws IOException { + Config config = Utils.getConfig(); + String resourceUid = ("{\"componentUid\":\"" + serviceUniqueId + "\"}"); + String url = String.format(Urls.CHANGE__RESOURCE_INSTANCE_VERSION, config.getCatalogBeHost(), + config.getCatalogBePort(), ComponentTypeEnum.findParamByType(componentType), componentUniqueId, + serviceInstanceToReplaceUniqueId); + RestResponse changeResourceInstanceVersion = sendPost(url, resourceUid, sdncModifierDetails.getUserId(), + acceptHeaderData); + return changeResourceInstanceVersion; + + } + + public static RestResponse getProductByNameAndVersion(String productName, String productVersion, String userId) + throws Exception { + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_PRODUCT_BY_NAME_AND_VERSION, config.getCatalogBeHost(), + config.getCatalogBePort(), productName, productVersion); + logger.debug("Send GET request to get product by name and version: {}", url); + return sendGet(url, userId); + } + +} diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/PropertyRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/PropertyRestUtils.java new file mode 100644 index 0000000000..56ff5ec12b --- /dev/null +++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/PropertyRestUtils.java @@ -0,0 +1,310 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.utils.rest; + +import static org.testng.AssertJUnit.assertNotNull; +import static org.testng.AssertJUnit.assertNull; +import static org.testng.AssertJUnit.assertTrue; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; +import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.api.Urls; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class PropertyRestUtils extends BaseRestUtils { + private static Logger logger = LoggerFactory.getLogger(PropertyRestUtils.class.getName()); + + public static RestResponse createProperty(String resourceId, String body, User user) throws Exception { + Config config = Config.instance(); + String url = String.format(Urls.CREATE_PROPERTY, config.getCatalogBeHost(), config.getCatalogBePort(), + resourceId); + + return sendPost(url, body, user.getUserId(), acceptHeaderData); + } + + public static RestResponse updateProperty(String resourceId, String propertyId, String body, User user) + throws Exception { + Config config = Config.instance(); + + String url = String.format(Urls.UPDATE_PROPERTY, config.getCatalogBeHost(), config.getCatalogBePort(), + resourceId, propertyId); + return sendPut(url, body, user.getUserId(), acceptHeaderData); + } + + public static RestResponse getProperty(String resourceId, String propertyId, User user) throws Exception { + Config config = Config.instance(); + String url = String.format(Urls.GET_PROPERTY, config.getCatalogBeHost(), config.getCatalogBePort(), resourceId, + propertyId); + return sendGet(url, user.getUserId()); + } + + public static RestResponse deleteProperty(String resourceId, String propertyId, User user) throws Exception { + Config config = Config.instance(); + String url = String.format(Urls.DELETE_PROPERTY, config.getCatalogBeHost(), config.getCatalogBePort(), + resourceId, propertyId); + + return sendDelete(url, user.getUserId()); + } + + public static ComponentInstanceProperty getPropFromListByPropNameAndType(List<ComponentInstanceProperty> propList, + String propNameToUpdate, String propTypeToUpdate) { + for (ComponentInstanceProperty componentInstanceProperty : propList) { + if (componentInstanceProperty.getName().equals(propNameToUpdate) + && componentInstanceProperty.getType().equals(propTypeToUpdate)) { + return componentInstanceProperty; + } + } + return null; + } + + public static ComponentInstanceProperty getPropFromListByPropNameTypeAndPath( + List<ComponentInstanceProperty> propList, String propNameToUpdate, String propTypeToUpdate, + List<String> path) { + for (ComponentInstanceProperty componentInstanceProperty : propList) { + if (componentInstanceProperty.getPath() == null) { + return getPropFromListByPropNameAndType(propList, propNameToUpdate, propTypeToUpdate); + } + if (componentInstanceProperty.getName().equals(propNameToUpdate) + && componentInstanceProperty.getType().equals(propTypeToUpdate) + && path.containsAll(componentInstanceProperty.getPath())) { + return componentInstanceProperty; + } + } + return null; + } + + public static ComponentInstanceProperty getPropFromListByPropIdAndPath(List<ComponentInstanceProperty> propList, + String propId, List<String> path) { + + for (ComponentInstanceProperty componentInstanceProperty : propList) { + if (path != null) { + if (componentInstanceProperty.getUniqueId().equals(propId) + && componentInstanceProperty.getPath().equals(path)) { + return componentInstanceProperty; + } + } else { + if (componentInstanceProperty.getUniqueId().equals(propId)) { + return componentInstanceProperty; + } + } + } + return null; + } + + public static void comparePropertyLists(List<ComponentInstanceProperty> expectedList, + List<ComponentInstanceProperty> actualList, Boolean isUpdate) { + + assertTrue( + "list size are not equals, expected size is: " + expectedList.size() + " ,actual: " + actualList.size(), + expectedList.size() == actualList.size()); + Boolean flag = false; + for (ComponentInstanceProperty expectedcompInstProp : expectedList) { + for (ComponentInstanceProperty actualcompInstProp : actualList) { + flag = comparePropertyObjects(expectedcompInstProp, actualcompInstProp, isUpdate); + if (flag) { + break; + } + } + } + // System.out.println("expected: " + expectedList + ", actual: " + + // actualList); + logger.debug("expected: {}, actual: {}", expectedList, actualList); + assertTrue("actual lists does not contain all uniqeIds", flag); + } + + public static Boolean comparePropertyObjects(ComponentInstanceProperty expectedCompInstProp, + ComponentInstanceProperty actualCompInstProp, Boolean isUpdate) { + String uniqueId = expectedCompInstProp.getUniqueId(); + String type = expectedCompInstProp.getType(); + String defaulValue = expectedCompInstProp.getDefaultValue(); + if (actualCompInstProp.getUniqueId().equals(uniqueId) + && actualCompInstProp.getPath().equals(expectedCompInstProp.getPath())) { + assertTrue("expected type is: " + type + " ,actual: " + actualCompInstProp.getType(), + actualCompInstProp.getType().equals(type)); + if (defaulValue == null) { + assertTrue( + "expected defaulValue is: " + defaulValue + " ,actual: " + actualCompInstProp.getDefaultValue(), + actualCompInstProp.getDefaultValue() == defaulValue); + } else { + assertTrue( + "expected defaulValue is: " + defaulValue + " ,actual: " + actualCompInstProp.getDefaultValue(), + actualCompInstProp.getDefaultValue().equals(defaulValue)); + } + if (isUpdate) { + assertTrue( + "actual [Value] parameter " + actualCompInstProp.getName() + + "should equal to expected [Value]: " + actualCompInstProp.getValue() + " ,Value: " + + actualCompInstProp.getValue(), + actualCompInstProp.getValue().equals(expectedCompInstProp.getValue())); + assertNotNull("valueId is null", actualCompInstProp.getValueUniqueUid()); + } else { + if (defaulValue == null) { + assertTrue( + "actual [Value] parameter " + actualCompInstProp.getName() + + "should equal to expected [defaultValue]: " + actualCompInstProp.getValue() + + " ,defaultValue: " + actualCompInstProp.getDefaultValue(), + actualCompInstProp.getValue() == expectedCompInstProp.getDefaultValue()); + } else { + assertTrue( + "actual [Value] parameter " + actualCompInstProp.getName() + + "should equal to expected [defaultValue]: " + actualCompInstProp.getValue() + + " ,defaultValue: " + actualCompInstProp.getDefaultValue(), + actualCompInstProp.getValue().equals(expectedCompInstProp.getDefaultValue())); + } + assertNull("valueId is not null", actualCompInstProp.getValueUniqueUid()); + } + return true; + } + return false; + } + + public static List<ComponentInstanceProperty> addResourcePropertiesToList(Resource resource, + List<ComponentInstanceProperty> listToFill) { + for (PropertyDefinition prop : resource.getProperties()) { + listToFill.add(new ComponentInstanceProperty(prop, null, null)); + } + return listToFill; + } + + public static List<ComponentInstanceProperty> addComponentInstPropertiesToList(Component component, + List<ComponentInstanceProperty> listToFill, String componentId) { + + if (componentId != null) { + List<ComponentInstanceProperty> list = component.getComponentInstancesProperties().get(componentId); + for (ComponentInstanceProperty prop : list) { + ComponentInstanceProperty componentInstanceProperty = new ComponentInstanceProperty(prop, null, null); + componentInstanceProperty.setPath(prop.getPath()); + componentInstanceProperty.setValueUniqueUid(prop.getValueUniqueUid()); + componentInstanceProperty.setValue(prop.getValue()); + listToFill.add(componentInstanceProperty); + } + } else { + Map<String, List<ComponentInstanceProperty>> componentInstancesProperties = component + .getComponentInstancesProperties(); + for (Map.Entry<String, List<ComponentInstanceProperty>> componentInstanceProperties : componentInstancesProperties + .entrySet()) { + for (ComponentInstanceProperty prop : componentInstanceProperties.getValue()) { + ComponentInstanceProperty componentInstanceProperty = new ComponentInstanceProperty(prop, null, + null); + componentInstanceProperty.setPath(prop.getPath()); + componentInstanceProperty.setValueUniqueUid(prop.getValueUniqueUid()); + componentInstanceProperty.setValue(prop.getValue()); + listToFill.add(componentInstanceProperty); + } + } + } + + if (component.getComponentType().getValue().equals("Resource")) { + for (PropertyDefinition prop : ((Resource) component).getProperties()) { + listToFill.add(new ComponentInstanceProperty(prop, null, null)); + } + } + return listToFill; + } + + public static ComponentInstanceProperty getCompPropInstListByInstIdAndPropName(Component component, + ComponentInstance componentInstanceDetails, String name, String type) { + List<ComponentInstanceProperty> propList = component.getComponentInstancesProperties() + .get(componentInstanceDetails.getUniqueId()); + if (propList != null) { + return getPropFromListByPropNameAndType(propList, name, type); + } + return null; + } + + private static void updatePropertyListWithPathParameter(Resource resource, List<String> path, + List<ComponentInstanceProperty> expectedPropertyList) { + List<PropertyDefinition> propertyList = resource.getProperties(); + for (PropertyDefinition propertyDefinition : propertyList) { + ComponentInstanceProperty propDetailsToRemove = PropertyRestUtils.getPropFromListByPropNameAndType( + expectedPropertyList, propertyDefinition.getName(), propertyDefinition.getType()); + ComponentInstanceProperty propDetailsToAdd = propDetailsToRemove; + propDetailsToAdd.setPath(path); + expectedPropertyList.remove(propDetailsToRemove); + expectedPropertyList.add(propDetailsToAdd); + } + } + + private static void updatePropertyListWithPathParameterOnCompInst(Service service, List<String> path, + List<ComponentInstanceProperty> expectedPropertyList) { + List<ComponentInstanceProperty> servicePropertyList = new ArrayList<>(); + servicePropertyList = PropertyRestUtils.addComponentInstPropertiesToList(service, servicePropertyList, + path.get(0)); + + for (ComponentInstanceProperty serviceCompInstProperty : servicePropertyList) { + ComponentInstanceProperty propDetailsToRemove = PropertyRestUtils.getPropFromListByPropNameTypeAndPath( + expectedPropertyList, serviceCompInstProperty.getName(), serviceCompInstProperty.getType(), + serviceCompInstProperty.getPath()); + ComponentInstanceProperty propDetailsToAdd = propDetailsToRemove; + List<String> tempPathList = new ArrayList<String>(); + for (String tempPath : path) { + tempPathList.add(tempPath); + } + // path parameter can not contain the same service unique ID twice + if (propDetailsToAdd.getPath() != null + && !propDetailsToAdd.getPath().get(0).contains(service.getUniqueId())) { + if (!propDetailsToAdd.getPath().containsAll(tempPathList)) { + tempPathList.addAll(propDetailsToAdd.getPath()); + } + } + propDetailsToAdd.setPath(tempPathList); + expectedPropertyList.remove(propDetailsToRemove); + expectedPropertyList.add(propDetailsToAdd); + } + } + + public static void updatePropertyListWithPathOnResource(ComponentInstance componentInstDetails, Resource resource, + List<ComponentInstanceProperty> list, Component container) { + List<String> path = new ArrayList<>(); + if (container != null) { + List<ComponentInstance> componentInstances = container.getComponentInstances(); + for (ComponentInstance componentInstance : componentInstances) { + if (componentInstance.getNormalizedName().equals(componentInstDetails.getNormalizedName())) { + path.add(componentInstance.getUniqueId()); + break; + } + } + + } else { + path.add(componentInstDetails.getUniqueId()); + } + updatePropertyListWithPathParameter(resource, path, list); + } + + public static void updatePropertyListWithPathOnComponentInstance(ComponentInstance componentInstDetails, + Service service, List<ComponentInstanceProperty> list) { + List<String> path = new ArrayList<>(); + path.add(componentInstDetails.getUniqueId()); + updatePropertyListWithPathParameterOnCompInst(service, path, list); + } +} diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtils.java new file mode 100644 index 0000000000..16ffd2f9e2 --- /dev/null +++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtils.java @@ -0,0 +1,575 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.utils.rest; + +import static org.testng.AssertJUnit.assertEquals; + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.http.client.ClientProtocolException; +import org.json.JSONException; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.RequirementDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.RelationshipInstData; +import org.openecomp.sdc.ci.tests.api.Urls; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ImportReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum; +import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.utils.Utils; +import org.openecomp.sdc.ci.tests.utils.general.ElementFactory; +import org.openecomp.sdc.common.util.GeneralUtility; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonParser; + +public class ResourceRestUtils extends BaseRestUtils { + private static Logger logger = LoggerFactory.getLogger(ResourceRestUtils.class.getName()); + + // ****** CREATE ******* + + public static RestResponse createResource(ResourceReqDetails resourceDetails, User sdncModifierDetails) throws Exception { + + Config config = Utils.getConfig(); + String url = String.format(Urls.CREATE_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort()); + + String userId = sdncModifierDetails.getUserId(); + + Map<String, String> headersMap = prepareHeadersMap(userId); + + Gson gson = new Gson(); + String userBodyJson = gson.toJson(resourceDetails); + String calculateMD5 = GeneralUtility.calculateMD5ByString(userBodyJson); + headersMap.put(HttpHeaderEnum.Content_MD5.getValue(), calculateMD5); + HttpRequest http = new HttpRequest(); + // System.out.println(url); + // System.out.println(userBodyJson); + RestResponse createResourceResponse = http.httpSendPost(url, userBodyJson, headersMap); + if (createResourceResponse.getErrorCode() == STATUS_CODE_CREATED) { + resourceDetails.setUUID(ResponseParser.getUuidFromResponse(createResourceResponse)); + resourceDetails.setVersion(ResponseParser.getVersionFromResponse(createResourceResponse)); + resourceDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(createResourceResponse)); + String lastUpdaterUserId = ResponseParser.getValueFromJsonResponse(createResourceResponse.getResponse(), "lastUpdaterUserId"); + resourceDetails.setLastUpdaterUserId(lastUpdaterUserId); + String lastUpdaterFullName = ResponseParser.getValueFromJsonResponse(createResourceResponse.getResponse(), "lastUpdaterFullName"); + resourceDetails.setLastUpdaterFullName(lastUpdaterFullName); + // Creator details never change after component is created - Ella, + // 12/1/2016 + resourceDetails.setCreatorUserId(userId); + resourceDetails.setCreatorFullName(sdncModifierDetails.getFullName()); + } + return createResourceResponse; + + } + + public static RestResponse createImportResource(ImportReqDetails importReqDetails, User sdncModifierDetails, Map<String, String> additionalHeaders) throws JSONException, IOException { + + Config config = Utils.getConfig(); + String url = String.format(Urls.CREATE_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort()); + String userId = sdncModifierDetails.getUserId(); + + Gson gson = new Gson(); + String resourceImportBodyJson = gson.toJson(importReqDetails); + HttpRequest http = new HttpRequest(); + // System.out.println(url); + // System.out.println(resourceImportBodyJson); + + Map<String, String> headersMap = prepareHeadersMap(userId); + if (additionalHeaders != null) { + headersMap.putAll(additionalHeaders); + } else { + headersMap.put(HttpHeaderEnum.Content_MD5.getValue(), ArtifactRestUtils.calculateMD5(resourceImportBodyJson)); + } + + RestResponse createResourceResponse = http.httpSendPost(url, resourceImportBodyJson, headersMap); + if (createResourceResponse.getErrorCode() == STATUS_CODE_CREATED) { + importReqDetails.setVersion(ResponseParser.getVersionFromResponse(createResourceResponse)); + importReqDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(createResourceResponse)); + // Creator details never change after component is created - Ella, + // 12/1/2016 + importReqDetails.setCreatorUserId(userId); + importReqDetails.setCreatorFullName(sdncModifierDetails.getFullName()); + importReqDetails.setToscaResourceName(ResponseParser.getToscaResourceNameFromResponse(createResourceResponse)); + importReqDetails.setDerivedList(ResponseParser.getDerivedListFromJson(createResourceResponse)); + } + return createResourceResponse; + + } + + // ***** DELETE **** + public static RestResponse deleteResource(ResourceReqDetails resourceDetails, User sdncModifierDetails, String version) throws IOException { + + if (resourceDetails.getUniqueId() != null) { + Config config = Utils.getConfig(); + String url = String.format(Urls.DELETE_RESOURCE_BY_NAME_AND_VERSION, config.getCatalogBeHost(), config.getCatalogBePort(), resourceDetails.getName(), version); + return sendDelete(url, sdncModifierDetails.getUserId()); + } else { + return null; + } + + } + + public static RestResponse markResourceToDelete(String resourceId, String userId) throws IOException { + + Config config = Utils.getConfig(); + String url = String.format(Urls.DELETE_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceId); + RestResponse sendDelete = sendDelete(url, userId); + + return sendDelete; + + } + + public static RestResponse deleteResource(String resourceId, String userId) throws IOException { + + Config config = Utils.getConfig(); + String url = String.format(Urls.DELETE_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceId); + RestResponse sendDelete = sendDelete(url, userId); + + deleteMarkedResources(userId); + + return sendDelete; + + } + + public static void deleteMarkedResources(String userId) throws IOException { + String url; + Config config = Utils.getConfig(); + url = String.format(Urls.DELETE_MARKED_RESOURCES, config.getCatalogBeHost(), config.getCatalogBePort()); + sendDelete(url, userId); + } + + public static RestResponse deleteResourceByNameAndVersion(User sdncModifierDetails, String resourceName, String resourceVersion) throws IOException { + Config config = Utils.getConfig(); + String url = String.format(Urls.DELETE_RESOURCE_BY_NAME_AND_VERSION, config.getCatalogBeHost(), config.getCatalogBePort(), resourceName, resourceVersion); + RestResponse sendDelete = sendDelete(url, sdncModifierDetails.getUserId()); + + deleteMarkedResources(sdncModifierDetails.getUserId()); + + return sendDelete; + } + + public static Boolean deleteResourceByNameAndVersion(String resourceName, String resourceVersion) throws IOException { + RestResponse deleteResponse = ResourceRestUtils.deleteResourceByNameAndVersion(ElementFactory.getDefaultUser(UserRoleEnum.ADMIN), resourceName, resourceVersion); + return checkErrorCode(deleteResponse); + } + + public static Boolean removeResource(String resourceId) throws FileNotFoundException, IOException, ClientProtocolException { + RestResponse response = deleteResource(resourceId, ElementFactory.getDefaultUser(UserRoleEnum.ADMIN).getUserId()); + return checkErrorCode(response); + } + + // ************** GET ************* + public static RestResponse getResource(User sdncModifierDetails, String uniqueId) throws IOException { + + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(), uniqueId); + return sendGet(url, sdncModifierDetails.getUserId()); + } + + public static RestResponse getModule(User sdncModifierDetails, String componentId, String moduleId) throws IOException { + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_MODULE_BY_ID, config.getCatalogBeHost(), config.getCatalogBePort(), componentId, moduleId); + return sendGet(url, sdncModifierDetails.getUserId()); + } + + public static RestResponse getLatestResourceFromCsarUuid(User sdncModifierDetails, String csarUuid) throws IOException { + + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_RESOURCE_BY_CSAR_UUID, config.getCatalogBeHost(), config.getCatalogBePort(), csarUuid); + return sendGet(url, sdncModifierDetails.getUserId()); + } + + public static RestResponse getResource(ResourceReqDetails resourceDetails, User sdncModifierDetails) throws IOException { + + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceDetails.getUniqueId()); + return sendGet(url, sdncModifierDetails.getUserId()); + } + + public static RestResponse getResourceByNameAndVersion(String userId, String resourceName, String resourceVersion) throws IOException { + + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_RESOURCE_BY_NAME_AND_VERSION, config.getCatalogBeHost(), config.getCatalogBePort(), resourceName, resourceVersion); + + return sendGet(url, userId); + } + + public static RestResponse getResourceList(User sdncModifierDetails) throws IOException { + + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_FOLLWED_LIST, config.getCatalogBeHost(), config.getCatalogBePort()); + + return sendGet(url, sdncModifierDetails.getUserId()); + + } + + public static RestResponse getResource(String resourceId) throws ClientProtocolException, IOException { + return getResource(ElementFactory.getDefaultUser(UserRoleEnum.ADMIN), resourceId); + } + + public static RestResponse getLatestResourceFromCsarUuid(String csarUuid) throws ClientProtocolException, IOException { + return getLatestResourceFromCsarUuid(ElementFactory.getDefaultUser(UserRoleEnum.ADMIN), csarUuid); + } + + public static RestResponse getResourceLatestVersionList(User sdncModifierDetails) throws IOException { + + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_RESOURCE_lATEST_VERSION, config.getCatalogBeHost(), config.getCatalogBePort()); + + return sendGet(url, sdncModifierDetails.getUserId()); + + } + + public static RestResponse putAllCategoriesTowardsCatalogFeWithUuidNotAllowed(String uuid) throws IOException { + + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_ALL_CATEGORIES_FE, config.getCatalogFeHost(), config.getCatalogFePort(), BaseRestUtils.RESOURCE_COMPONENT_TYPE); + + Map<String, String> headersMap = new HashMap<String, String>(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderData); + headersMap.put(HttpHeaderEnum.X_ECOMP_REQUEST_ID_HEADER.getValue(), uuid); + HttpRequest http = new HttpRequest(); + + logger.debug("Send PUT request to get all categories (should be 405): {}", url); + return http.httpSendByMethod(url, "PUT", null, headersMap); + } + + public static RestResponse getAllTagsTowardsCatalogBe() throws IOException { + + Config config = Utils.getConfig(); + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.GET_ALL_TAGS, config.getCatalogBeHost(), config.getCatalogBePort()); + + Map<String, String> headersMap = new HashMap<String, String>(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderData); + + // logger.debug("Send GET request to get all tags: {}", url); + return http.httpSendGet(url, headersMap); + + } + + public static RestResponse getAllPropertyScopesTowardsCatalogBe() throws IOException { + + Config config = Utils.getConfig(); + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.GET_PROPERTY_SCOPES_LIST, config.getCatalogBeHost(), config.getCatalogBePort()); + + Map<String, String> headersMap = new HashMap<String, String>(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json"); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json"); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), "cs0008"); + + // logger.debug("Send GET request to get all property scopes: {}", url); + return http.httpSendGet(url, headersMap); + + } + + public static RestResponse getAllArtifactTypesTowardsCatalogBe() throws IOException { + + Config config = Utils.getConfig(); + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.GET_ALL_ARTIFACTS, config.getCatalogBeHost(), config.getCatalogBePort()); + + Map<String, String> headersMap = new HashMap<String, String>(); + + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json"); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json"); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), "cs0008"); + + // logger.debug("Send GET request to get all property scopes: {}", url); + return http.httpSendGet(url, headersMap); + + } + + public static RestResponse getConfigurationTowardsCatalogBe() throws IOException { + + Config config = Utils.getConfig(); + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.GET_CONFIGURATION, config.getCatalogBeHost(), config.getCatalogBePort()); + + Map<String, String> headersMap = new HashMap<String, String>(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json"); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json"); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), "cs0008"); + + // logger.debug("Send GET request to get all property scopes: {}", url); + return http.httpSendGet(url, headersMap); + + } + + public static RestResponse sendOptionsTowardsCatalogFeWithUuid() throws IOException { + + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_ALL_CATEGORIES_FE, config.getCatalogFeHost(), config.getCatalogFePort(), BaseRestUtils.RESOURCE_COMPONENT_TYPE); + + Map<String, String> headersMap = new HashMap<String, String>(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderData); + HttpRequest http = new HttpRequest(); + + logger.debug("Send OPTIONS request for categories: {}", url); + return http.httpSendByMethod(url, "OPTIONS", null, headersMap); + } + + // ********** UPDATE ************* + public static RestResponse updateResourceMetadata(ResourceReqDetails updatedResourceDetails, User sdncModifierDetails, String uniqueId, String encoding) throws Exception { + Config config = Utils.getConfig(); + String url = String.format(Urls.UPDATE_RESOURCE_METADATA, config.getCatalogBeHost(), config.getCatalogBePort(), uniqueId); + + String ContentTypeString = String.format("%s;%s", contentTypeHeaderData, encoding); + + Gson gson = new Gson(); + String userBodyJson = gson.toJson(updatedResourceDetails); + String userId = sdncModifierDetails.getUserId(); + + RestResponse updateResourceResponse = sendPut(url, userBodyJson, userId, ContentTypeString); + + updatedResourceDetails.setVersion(ResponseParser.getVersionFromResponse(updateResourceResponse)); + updatedResourceDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(updateResourceResponse)); + + return updateResourceResponse; + } + + public static RestResponse updateResourceTEST(Resource resource, User sdncModifierDetails, String uniqueId, String encoding) throws Exception { + Config config = Utils.getConfig(); + String url = String.format(Urls.UPDATE_RESOURCE_METADATA, config.getCatalogBeHost(), config.getCatalogBePort(), uniqueId); + + String ContentTypeString = String.format("%s;%s", contentTypeHeaderData, encoding); + + Gson gson = new Gson(); + String userBodyJson = gson.toJson(resource); + String userId = sdncModifierDetails.getUserId(); + + RestResponse updateResourceResponse = sendPut(url, userBodyJson, userId, ContentTypeString); + return updateResourceResponse; + } + + public static RestResponse updateResourceMetadata(ResourceReqDetails updatedResourceDetails, User sdncModifierDetails, String uniqueId) throws Exception { + return updateResourceMetadata(updatedResourceDetails, sdncModifierDetails, uniqueId, ""); + } + + public static RestResponse updateResourceMetadata(String json, User sdncModifierDetails, String resourceId) throws IOException { + Config config = Utils.getConfig(); + String url = String.format(Urls.UPDATE_RESOURCE_METADATA, config.getCatalogBeHost(), config.getCatalogBePort(), resourceId); + String userId = sdncModifierDetails.getUserId(); + RestResponse updateResourceResponse = sendPut(url, json, userId, contentTypeHeaderData); + return updateResourceResponse; + } + + public static RestResponse updateResource(ResourceReqDetails resourceDetails, User sdncModifierDetails, String resourceId) throws IOException { + String userId = sdncModifierDetails.getUserId(); + Config config = Utils.getConfig(); + String url = String.format(Urls.UPDATE_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceId); + + Map<String, String> headersMap = prepareHeadersMap(userId); + + Gson gson = new Gson(); + String userBodyJson = gson.toJson(resourceDetails); + String calculateMD5 = GeneralUtility.calculateMD5ByString(userBodyJson); + headersMap.put(HttpHeaderEnum.Content_MD5.getValue(), calculateMD5); + HttpRequest http = new HttpRequest(); + RestResponse updateResourceResponse = http.httpSendPut(url, userBodyJson, headersMap); + if (updateResourceResponse.getErrorCode() == STATUS_CODE_UPDATE_SUCCESS) { + resourceDetails.setUUID(ResponseParser.getUuidFromResponse(updateResourceResponse)); + resourceDetails.setVersion(ResponseParser.getVersionFromResponse(updateResourceResponse)); + resourceDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(updateResourceResponse)); + String lastUpdaterUserId = ResponseParser.getValueFromJsonResponse(updateResourceResponse.getResponse(), "lastUpdaterUserId"); + resourceDetails.setLastUpdaterUserId(lastUpdaterUserId); + String lastUpdaterFullName = ResponseParser.getValueFromJsonResponse(updateResourceResponse.getResponse(), "lastUpdaterFullName"); + resourceDetails.setLastUpdaterFullName(lastUpdaterFullName); + resourceDetails.setCreatorUserId(userId); + resourceDetails.setCreatorFullName(sdncModifierDetails.getFullName()); + } + return updateResourceResponse; + } + + public static RestResponse createResourceInstance(ResourceReqDetails resourceDetails, User modifier, String vfResourceUniqueId) throws Exception { + ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory.getComponentResourceInstance(resourceDetails); + RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(resourceInstanceReqDetails, modifier, vfResourceUniqueId, ComponentTypeEnum.RESOURCE); + ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse); + return createResourceInstanceResponse; + } + + public static RestResponse associateResourceInstances(JSONObject body, User sdncModifierDetails, Component component) throws IOException { + + Config config = Utils.getConfig(); + Gson gson = new Gson(); + String bodyJson = gson.toJson(body); + component.getComponentType(); + String componentType = ComponentTypeEnum.findParamByType(component.getComponentType()); + String url = String.format(Urls.ASSOCIATE__RESOURCE_INSTANCE, config.getCatalogBeHost(), config.getCatalogBePort(), componentType, component.getUniqueId()); + return sendPost(url, bodyJson, sdncModifierDetails.getUserId(), null); + + } + + public static RestResponse getFollowedList(User sdncModifierDetails) throws Exception { + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_FOLLWED_LIST, config.getCatalogBeHost(), config.getCatalogBePort()); + return sendGet(url, sdncModifierDetails.getUserId()); + } + + public static List<Resource> restResponseToResourceObjectList(String restResponse) { + JsonElement jelement = new JsonParser().parse(restResponse); + JsonArray jsonArray = jelement.getAsJsonArray(); + List<Resource> restResponseArray = new ArrayList<>(); + Resource resource = null; + for (int i = 0; i < jsonArray.size(); i++) { + String resourceString = (String) jsonArray.get(i).toString(); + resource = ResponseParser.convertResourceResponseToJavaObject(resourceString); + restResponseArray.add(resource); + } + + return restResponseArray; + + } + + public static Resource getResourceObjectFromResourceListByUid(List<Resource> resourceList, String uid) { + if (resourceList != null && resourceList.size() > 0) { + for (Resource resource : resourceList) { + if (resource.getUniqueId().equals(uid)) + return resource; + } + } else + return null; + return null; + } + + // =======================================resource + // associate================================================== + public static RestResponse associate2ResourceInstances(Component container, ComponentInstance fromNode, ComponentInstance toNode, String assocType, User sdncUserDetails) throws IOException { + return associate2ResourceInstances(container, fromNode.getUniqueId(), toNode.getUniqueId(), assocType, sdncUserDetails); + } + + public static RestResponse associate2ResourceInstances(Component component, String fromNode, String toNode, String assocType, User sdncUserDetails) throws IOException { + + RelationshipInstData relationshipInstData = new RelationshipInstData(); + Map<String, List<CapabilityDefinition>> capabilitiesMap = component.getCapabilities(); + Map<String, List<RequirementDefinition>> requirementMap = component.getRequirements(); + List<CapabilityDefinition> capabilitiesList = capabilitiesMap.get(assocType); + List<RequirementDefinition> requirementList = requirementMap.get(assocType); + + RequirementDefinition requirementDefinitionFrom = getRequirementDefinitionByOwnerId(requirementList, fromNode); + CapabilityDefinition capabilityDefinitionTo = getCapabilityDefinitionByOwnerId(capabilitiesList, toNode); + relationshipInstData.setCapabilityOwnerId(capabilityDefinitionTo.getOwnerId()); + relationshipInstData.setCapabiltyId(capabilityDefinitionTo.getUniqueId()); + relationshipInstData.setRequirementOwnerId(requirementDefinitionFrom.getOwnerId()); + relationshipInstData.setRequirementId(requirementDefinitionFrom.getUniqueId()); + + JSONObject assocBody = assocBuilder(relationshipInstData, capabilityDefinitionTo, requirementDefinitionFrom, toNode, fromNode); + return ResourceRestUtils.associateResourceInstances(assocBody, sdncUserDetails, component); + + } + + private static JSONObject assocBuilder(RelationshipInstData relationshipInstData, CapabilityDefinition capabilityDefinitionTo, RequirementDefinition requirementDefinitionFrom, String toNode, String fromNode) { + + String type = capabilityDefinitionTo.getType(); + String requirement = requirementDefinitionFrom.getName(); + String capability = requirementDefinitionFrom.getName(); + + JSONObject wrapper = new JSONObject(); + JSONArray relationshipsArray = new JSONArray(); + JSONObject relationship = new JSONObject(); + JSONObject simpleObject = new JSONObject(); + + relationship.put("type", type); + simpleObject.put("relationship", relationship); + simpleObject.put("requirement", requirement); + simpleObject.put("capability", capability); + simpleObject.put("capabilityUid", relationshipInstData.getCapabiltyId()); + simpleObject.put("capabilityOwnerId", relationshipInstData.getCapabilityOwnerId()); + simpleObject.put("requirementOwnerId", relationshipInstData.getRequirementOwnerId()); + simpleObject.put("requirementUid", relationshipInstData.getRequirementId()); + relationshipsArray.add(simpleObject); + + ArrayList<Object> relationships = new ArrayList<Object>(relationshipsArray); + wrapper.put("fromNode", fromNode); + wrapper.put("toNode", toNode); + wrapper.put("relationships", relationships); + return wrapper; + + } + + private static CapabilityDefinition getCapabilityDefinitionByOwnerId(List<CapabilityDefinition> capabilityDefinitionList, String ownerId) { + + for (CapabilityDefinition capabilityDefinition : capabilityDefinitionList) { + if (capabilityDefinition.getOwnerId().equals(ownerId)) { + return capabilityDefinition; + } + } + return null; + } + + private static RequirementDefinition getRequirementDefinitionByOwnerId(List<RequirementDefinition> requirementDefinitionList, String ownerId) { + + for (RequirementDefinition requirementDefinition : requirementDefinitionList) { + if (requirementDefinition.getOwnerId().equals(ownerId)) { + return requirementDefinition; + } + } + return null; + } + + public static String getRiUniqueIdByRiName(Component component, String resourceInstanceName) { + + List<ComponentInstance> componentInstances = component.getComponentInstances(); + String name = null; + for (ComponentInstance componentInstance : componentInstances) { + if (componentInstance.getName().equals(resourceInstanceName)) { + name = componentInstance.getUniqueId(); + break; + } + } + return name; + } + + public static Resource convertResourceGetResponseToJavaObject(ResourceReqDetails resourceDetails) throws IOException { + RestResponse response = ResourceRestUtils.getResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + assertEquals("Check response code after get resource", 200, response.getErrorCode().intValue()); + return ResponseParser.convertResourceResponseToJavaObject(response.getResponse()); + } + + public static RestResponse changeResourceInstanceVersion(String containerUniqueId, String instanceToReplaceUniqueId, String newResourceUniqueId, User sdncModifierDetails, ComponentTypeEnum componentType) throws IOException { + return ProductRestUtils.changeServiceInstanceVersion(containerUniqueId, instanceToReplaceUniqueId, newResourceUniqueId, sdncModifierDetails, componentType); + } + +} diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResponseParser.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResponseParser.java new file mode 100644 index 0000000000..dfcb9c2736 --- /dev/null +++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResponseParser.java @@ -0,0 +1,541 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.utils.rest; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.apache.commons.codec.binary.Base64; +import org.apache.log4j.Logger; +import org.codehaus.jackson.Version; +import org.codehaus.jackson.map.JsonDeserializer; +import org.codehaus.jackson.map.ObjectMapper; +import org.codehaus.jackson.map.module.SimpleModule; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.simple.JSONObject; +import org.json.simple.JSONValue; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; +import org.openecomp.sdc.be.model.Product; +import org.openecomp.sdc.be.model.PropertyConstraint; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintJacksonDeserialiser; +import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ResourceRespJavaObject; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; + +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; + +public class ResponseParser { + + private static final String INVARIANT_UUID = "invariantUUID"; + public static final String UNIQUE_ID = "uniqueId"; + public static final String VERSION = "version"; + public static final String UUID = "uuid"; + public static final String NAME = "name"; + public static final String ORIGIN_TYPE = "originType"; + public static final String TOSCA_RESOURCE_NAME = "toscaResourceName"; + + static Logger logger = Logger.getLogger(ResponseParser.class.getName()); + + public static String getValueFromJsonResponse(String response, String fieldName) { + try { + JSONObject jsonResp = (JSONObject) JSONValue.parse(response); + Object fieldValue = jsonResp.get(fieldName); + return fieldValue.toString(); + + } catch (Exception e) { + return null; + } + + } + + public static String getUniqueIdFromResponse(RestResponse response) { + return getValueFromJsonResponse(response.getResponse(), UNIQUE_ID); + } + + public static String getInvariantUuid(RestResponse response) { + return getValueFromJsonResponse(response.getResponse(), INVARIANT_UUID); + } + + public static String getUuidFromResponse(RestResponse response) { + return getValueFromJsonResponse(response.getResponse(), UUID); + } + + public static String getNameFromResponse(RestResponse response) { + return getValueFromJsonResponse(response.getResponse(), NAME); + } + + public static String getVersionFromResponse(RestResponse response) { + return ResponseParser.getValueFromJsonResponse(response.getResponse(), VERSION); + } + + public static String getComponentTypeFromResponse(RestResponse response) { + return ResponseParser.getValueFromJsonResponse(response.getResponse(), ORIGIN_TYPE); + } + + public static String getToscaResourceNameFromResponse(RestResponse response) { + return getValueFromJsonResponse(response.getResponse(), TOSCA_RESOURCE_NAME); + } + + @SuppressWarnings("unchecked") + public static ResourceRespJavaObject parseJsonListReturnResourceDetailsObj(RestResponse restResponse, + String resourceType, String searchPattern, String expectedResult) throws Exception { + + // Gson gson = new Gson; + + JsonElement jElement = new JsonParser().parse(restResponse.getResponse()); + JsonObject jObject = jElement.getAsJsonObject(); + JsonArray arrayOfObjects = (JsonArray) jObject.get(resourceType); + Gson gson = new Gson(); + Map<String, Object> map = new HashMap<String, Object>(); + ResourceRespJavaObject jsonToJavaObject = new ResourceRespJavaObject(); + + for (int counter = 0; counter < arrayOfObjects.size(); counter++) { + JsonObject jHitObject = (JsonObject) arrayOfObjects.get(counter); + + map = (Map<String, Object>) gson.fromJson(jHitObject.toString(), map.getClass()); + if (map.get(searchPattern).toString().contains(expectedResult)) { + + jsonToJavaObject = gson.fromJson(jObject, ResourceRespJavaObject.class); + break; + } + } + return jsonToJavaObject; + + } + + public static Resource convertResourceResponseToJavaObject(String response) { + + ObjectMapper mapper = new ObjectMapper(); + final SimpleModule module = new SimpleModule("customerSerializationModule", + new Version(1, 0, 0, "static version")); + JsonDeserializer<PropertyConstraint> desrializer = new PropertyConstraintJacksonDeserialiser(); + addDeserializer(module, PropertyConstraint.class, desrializer); + + mapper.registerModule(module); + Resource resource = null; + try { + resource = mapper.readValue(response, Resource.class); + logger.debug(resource.toString()); + } catch (IOException e) { + try { + List<Resource> resources = Arrays.asList(mapper.readValue(response.toString(), Resource[].class)); + resource = resources.get(0); + } catch (Exception e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + } + + return resource; + } + + public static ComponentInstanceProperty convertPropertyResponseToJavaObject(String response) { + + ObjectMapper mapper = new ObjectMapper(); + final SimpleModule module = new SimpleModule("customerSerializationModule", + new Version(1, 0, 0, "static version")); + JsonDeserializer<PropertyConstraint> desrializer = new PropertyConstraintJacksonDeserialiser(); + addDeserializer(module, PropertyConstraint.class, desrializer); + + mapper.registerModule(module); + ComponentInstanceProperty propertyDefinition = null; + try { + propertyDefinition = mapper.readValue(response, ComponentInstanceProperty.class); + logger.debug(propertyDefinition.toString()); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return propertyDefinition; + } + + // public static ResourceInstanceReqDetails + // convertResourceInstanceResponseToJavaObject(String response) { + // + // ObjectMapper mapper = new ObjectMapper(); + // final SimpleModule module = new + // SimpleModule("customerSerializationModule", new Version(1, 0, 0, "static + // version")); + // JsonDeserializer<PropertyConstraint> desrializer = new + // PropertyConstraintJacksonDeserialiser(); + // addDeserializer(module, PropertyConstraint.class, desrializer); + // + // mapper.registerModule(module); + // ResourceInstanceReqDetails resourceInstanceReqDetails = null; + // try { + // resourceInstanceReqDetails = mapper.readValue(response, + // ResourceInstanceReqDetails.class); + // logger.debug(resourceInstanceReqDetails.toString()); + // } catch (IOException e) { + // // TODO Auto-generated catch block + // e.printStackTrace(); + // } + // + // return resourceInstanceReqDetails; + // } + public static String toJson(Object object) { + Gson gson = new Gson(); + return gson.toJson(object); + } + + public static ArtifactDefinition convertArtifactDefinitionResponseToJavaObject(String response) { + ObjectMapper mapper = new ObjectMapper(); + ArtifactDefinition artifactDefinition = null; + try { + + artifactDefinition = mapper.readValue(response, ArtifactDefinition.class); + logger.debug(artifactDefinition.toString()); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + return artifactDefinition; + + } + + public static ArtifactReqDetails convertArtifactReqDetailsToJavaObject(String response) { + + ArtifactReqDetails artifactReqDetails = null; + // try { + // + // artifactDefinition = mapper.readValue(response, + // ArtifactReqDetails.class); + // logger.debug(artifactDefinition.toString()); + // } catch (IOException e) { + // // TODO Auto-generated catch block + // e.printStackTrace(); + // } + // + // return artifactDefinition; + Gson gson = new Gson(); + artifactReqDetails = gson.fromJson(response, ArtifactReqDetails.class); + return artifactReqDetails; + } + + public static <T> T parseToObject(String json, Class<T> clazz) { + Gson gson = new Gson(); + T object; + try { + object = gson.fromJson(json, clazz); + } catch (Exception e) { + object = parseToObjectUsingMapper(json, clazz); + } + return object; + } + + public static <T> T parseToObjectUsingMapper(String json, Class<T> clazz) { + // Generic convert + ObjectMapper mapper = new ObjectMapper(); + T object = null; + final SimpleModule module = new SimpleModule("customerSerializationModule", + new Version(1, 0, 0, "static version")); + JsonDeserializer<PropertyConstraint> desrializer = new PropertyConstraintJacksonDeserialiser(); + addDeserializer(module, PropertyConstraint.class, desrializer); + mapper.registerModule(module); + try { + object = mapper.readValue(json, clazz); + // System.out.println("Class: "+clazz.getSimpleName()+", json: + // "+json); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + return object; + } + + public static ArtifactReqDetails convertArtifactDefinitionToArtifactReqDetailsObject( + ArtifactDefinition artifactDefinition) { + + ArtifactReqDetails artifactReqDetails = null; + // try { + // + // artifactDefinition = mapper.readValue(response, + // ArtifactReqDetails.class); + // logger.debug(artifactDefinition.toString()); + // } catch (IOException e) { + // // TODO Auto-generated catch block + // e.printStackTrace(); + // } + // + // return artifactDefinition; + Gson gson = new Gson(); + String artDef = gson.toJson(artifactDefinition); + artifactReqDetails = gson.fromJson(artDef, ArtifactReqDetails.class); + return artifactReqDetails; + } + + public static <T> void addDeserializer(SimpleModule module, Class<T> clazz, + final JsonDeserializer<T> deserializer) { + module.addDeserializer(clazz, deserializer); + } + + public static Service convertServiceResponseToJavaObject(String response) { + + ObjectMapper mapper = new ObjectMapper(); + final SimpleModule module = new SimpleModule("customerSerializationModule", + new Version(1, 0, 0, "static version")); + JsonDeserializer<PropertyConstraint> desrializer = new PropertyConstraintJacksonDeserialiser(); + addDeserializer(module, PropertyConstraint.class, desrializer); + + mapper.registerModule(module); + Service service = null; + try { + service = mapper.readValue(response, Service.class); + logger.debug(service.toString()); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + return service; + } + + public static Product convertProductResponseToJavaObject(String response) { + + ObjectMapper mapper = new ObjectMapper(); + Product product = null; + try { + product = mapper.readValue(response, Product.class); + logger.debug(product.toString()); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + return product; + } + + public static ComponentInstance convertComponentInstanceResponseToJavaObject(String response) { + + ObjectMapper mapper = new ObjectMapper(); + final SimpleModule module = new SimpleModule("customerSerializationModule", + new Version(1, 0, 0, "static version")); + JsonDeserializer<PropertyConstraint> desrializer = new PropertyConstraintJacksonDeserialiser(); + addDeserializer(module, PropertyConstraint.class, desrializer); + + mapper.registerModule(module); + ComponentInstance componentInstance = null; + try { + componentInstance = mapper.readValue(response, ComponentInstance.class); + logger.debug(componentInstance.toString()); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + return componentInstance; + } + + public static List<String> getValuesFromJsonArray(RestResponse message) throws Exception { + List<String> artifactTypesArrayFromApi = new ArrayList<String>(); + + org.json.JSONObject responseObject = new org.json.JSONObject(message.getResponse()); + JSONArray jArr = responseObject.getJSONArray("artifactTypes"); + + for (int i = 0; i < jArr.length(); i++) { + org.json.JSONObject jObj = jArr.getJSONObject(i); + String value = jObj.get("name").toString(); + + artifactTypesArrayFromApi.add(value); + } + return artifactTypesArrayFromApi; + } + + public static String calculateMD5Header(ArtifactReqDetails artifactDetails) { + Gson gson = new Gson(); + String jsonBody = gson.toJson(artifactDetails); + // calculate MD5 for json body + return calculateMD5(jsonBody); + + } + + public static String calculateMD5(String data) { + String calculatedMd5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(data); + // encode base-64 result + byte[] encodeBase64 = Base64.encodeBase64(calculatedMd5.getBytes()); + String encodeBase64Str = new String(encodeBase64); + return encodeBase64Str; + + } + + public static List<Map<String, Object>> getAuditFromMessage(Map auditingMessage) { + List<Map<String, Object>> auditList = new ArrayList<Map<String, Object>>(); + // JsonElement jElement = new JsonParser().parse(auditingMessage); + // JsonObject jObject = jElement.getAsJsonObject(); + // JsonObject hitsObject = (JsonObject) jObject.get("hits"); + // JsonArray hitsArray = (JsonArray) hitsObject.get("hits"); + // + // Iterator<JsonElement> hitsIterator = hitsArray.iterator(); + // while(hitsIterator.hasNext()) + // { + // JsonElement nextHit = hitsIterator.next(); + // JsonObject jHitObject = nextHit.getAsJsonObject(); + // JsonObject jSourceObject = (JsonObject) jHitObject.get("_source"); + // + // Gson gson=new Gson(); + // String auditUnparsed = jSourceObject.toString(); + // + // Map<String,Object> map = new HashMap<String,Object>(); + // map = (Map<String,Object>) gson.fromJson(auditUnparsed, + // map.getClass()); + + auditList.add(auditingMessage); + // } + return auditList; + } + + public static List<CategoryDefinition> parseCategories(RestResponse getAllCategoriesRest) { + + List<CategoryDefinition> categories = new ArrayList<>(); + try { + JsonElement jElement = new JsonParser().parse(getAllCategoriesRest.getResponse()); + JsonArray cagegories = jElement.getAsJsonArray(); + Iterator<JsonElement> iter = cagegories.iterator(); + while (iter.hasNext()) { + JsonElement next = iter.next(); + CategoryDefinition category = ResponseParser.parseToObject(next.toString(), CategoryDefinition.class); + categories.add(category); + } + + } catch (Exception e) { + e.printStackTrace(); + } + + return categories; + } + + public static JSONArray getListFromJson(RestResponse res, String field) throws JSONException { + String valueFromJsonResponse = getValueFromJsonResponse(res.getResponse(), field); + JSONArray jArr = new JSONArray(valueFromJsonResponse); + + return jArr; + } + + public static List<String> getDerivedListFromJson(RestResponse res) throws JSONException { + JSONArray listFromJson = getListFromJson(res, "derivedList"); + List<String> lst = new ArrayList<String>(); + for (int i = 0; i < listFromJson.length(); i++) { + lst.add(listFromJson.getString(i)); + } + + return lst; + } + + public static Map<String, Object> convertStringToMap(String obj) { + Map<String, Object> object = (Map<String, Object>) JSONValue.parse(obj); + return object; + } + + public static List<Map<String, Object>> getListOfMapsFromJson(RestResponse res, String field) throws Exception { + List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); + JSONArray listFromJson = getListFromJson(res, field); + for (int i = 0; i < listFromJson.length(); i++) { + Map<String, Object> convertStringToMap = convertStringToMap(listFromJson.getString(i)); + list.add(convertStringToMap); + } + return list; + + } + + public static Map<String, Object> getJsonValueAsMap(RestResponse response, String key) { + String valueField = getValueFromJsonResponse(response.getResponse(), key); + Map<String, Object> convertToMap = convertStringToMap(valueField); + return convertToMap; + } + + public static String getJsonObjectValueByKey(String metadata, String key) { + JsonElement jelement = new JsonParser().parse(metadata); + + JsonObject jobject = jelement.getAsJsonObject(); + Object obj = jobject.get(key); + if (obj == null) { + return null; + } else { + return obj.toString(); + } + } + + public static Map<String, ArrayList<Component>> convertCatalogResponseToJavaObject(String response) { + + Map<String, ArrayList<Component>> map = new HashMap<String, ArrayList<Component>>(); + + JsonElement jElement = new JsonParser().parse(response); + JsonObject jObject = jElement.getAsJsonObject(); + JsonArray jArrReousrces = jObject.getAsJsonArray("resources"); + JsonArray jArrServices = jObject.getAsJsonArray("services"); + JsonArray jArrProducts = jObject.getAsJsonArray("products"); + + //////// RESOURCE///////////////////////////// + ArrayList<Component> restResponseArray = new ArrayList<>(); + Component component = null; + for (int i = 0; i < jArrReousrces.size(); i++) { + String resourceString = (String) jArrReousrces.get(i).toString(); + component = ResponseParser.convertResourceResponseToJavaObject(resourceString); + restResponseArray.add(component); + } + + map.put("resources", restResponseArray); + + ///////// SERVICE///////////////////////////// + + restResponseArray = new ArrayList<>(); + component = null; + for (int i = 0; i < jArrServices.size(); i++) { + String resourceString = (String) jArrServices.get(i).toString(); + component = ResponseParser.convertServiceResponseToJavaObject(resourceString); + restResponseArray.add(component); + } + + map.put("services", restResponseArray); + + ///////// PRODUCT///////////////////////////// + restResponseArray = new ArrayList<>(); + component = null; + for (int i = 0; i < jArrProducts.size(); i++) { + String resourceString = (String) jArrProducts.get(i).toString(); + component = ResponseParser.convertProductResponseToJavaObject(resourceString); + restResponseArray.add(component); + } + + map.put("products", restResponseArray); + + return map; + + } +} diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ServiceRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ServiceRestUtils.java new file mode 100644 index 0000000000..d62c74c3d2 --- /dev/null +++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ServiceRestUtils.java @@ -0,0 +1,262 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.utils.rest; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.JSONValue; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.api.Urls; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum; +import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.utils.Utils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.gson.Gson; + +public class ServiceRestUtils extends BaseRestUtils { + private static Logger logger = LoggerFactory.getLogger(ServiceRestUtils.class.getName()); + private final static String cacheControl = "no-cache"; + private final static String contentTypeHeaderData = "application/json"; + private final static String acceptHeaderDate = "application/json"; + // ****** CREATE ******* + + private static Gson gson = new Gson(); + + public static RestResponse deleteService(String serviceName, String version, User sdncModifierDetails) throws IOException { + Config config = Utils.getConfig(); + String url = String.format(Urls.DELETE_SERVICE_BY_NAME_AND_VERSION, config.getCatalogBeHost(), config.getCatalogBePort(), serviceName, version); + String userId = sdncModifierDetails.getUserId(); + RestResponse sendDelete = sendDelete(url, userId); + deleteMarkedServices(userId); + return sendDelete; + } + + public static RestResponse deleteServiceById(String serviceId, String userId) throws IOException { + Config config = Utils.getConfig(); + String url = String.format(Urls.DELETE_SERVICE, config.getCatalogBeHost(), config.getCatalogBePort(), serviceId); + RestResponse sendDelete = sendDelete(url, userId); + deleteMarkedServices(userId); + return sendDelete; + } + + public static void deleteMarkedServices(String userId) throws IOException { + String url; + Config config = Utils.getConfig(); + url = String.format(Urls.DELETE_MARKED_SERVICES, config.getCatalogBeHost(), config.getCatalogBePort()); + sendDelete(url, userId); + } + + public static RestResponse createService(ServiceReqDetails service, User user) throws Exception { + Config config = Utils.getConfig(); + String url = String.format(Urls.CREATE_SERVICE, config.getCatalogBeHost(), config.getCatalogBePort()); + String serviceBodyJson = gson.toJson(service); + + logger.debug("Send POST request to create service: {]", url); + logger.debug("Service body: {}", serviceBodyJson); + + RestResponse res = sendPost(url, serviceBodyJson, user.getUserId(), acceptHeaderData); + if (res.getErrorCode() == STATUS_CODE_CREATED) { + service.setUniqueId(ResponseParser.getUniqueIdFromResponse(res)); + service.setVersion(ResponseParser.getVersionFromResponse(res)); + service.setUUID(ResponseParser.getUuidFromResponse(res)); + // Creator details never change after component is created - Ella, + // 12/1/2016 + service.setCreatorUserId(user.getUserId()); + service.setCreatorFullName(user.getFullName()); + } + + return res; + } + + public static RestResponse updateService(ServiceReqDetails service, User user) throws Exception { + Config config = Utils.getConfig(); + String url = String.format(Urls.UPDATE_SERVICE_METADATA, config.getCatalogBeHost(), config.getCatalogBePort(), + service.getUniqueId()); + String serviceBodyJson = gson.toJson(service); + + logger.debug("Send PUT request to create service: {}", url); + logger.debug("Service body: {}", serviceBodyJson); + + RestResponse res = sendPut(url, serviceBodyJson, user.getUserId(), acceptHeaderData); + if (res.getErrorCode() == STATUS_CODE_CREATED) { + service.setUniqueId(ResponseParser.getUniqueIdFromResponse(res)); + service.setVersion(ResponseParser.getVersionFromResponse(res)); + } + + return res; + } + + public static RestResponse getService(ServiceReqDetails serviceReqDetails, User sdncModifierDetails) + throws IOException { + + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_SERVICE, config.getCatalogBeHost(), config.getCatalogBePort(), + serviceReqDetails.getUniqueId()); + return getServiceFromUrl(url, sdncModifierDetails, false); + } + + public static RestResponse getService(String serviceId, User sdncModifierDetails) throws IOException { + + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_SERVICE, config.getCatalogBeHost(), config.getCatalogBePort(), serviceId); + return getServiceFromUrl(url, sdncModifierDetails, false); + } + + public static RestResponse getServiceByNameAndVersion(User sdncModifierDetails, String serviceName, + String serviceVersion) throws IOException { + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_SERVICE_BY_NAME_AND_VERSION, config.getCatalogBeHost(), + config.getCatalogBePort(), serviceName, serviceVersion); + return getServiceFromUrl(url, sdncModifierDetails, false); + } + + public static RestResponse getServiceFromUrl(String url, User sdncModifierDetails, boolean isCached) + throws IOException { + Map<String, String> headersMap = prepareHeadersMap(sdncModifierDetails, isCached); + HttpRequest http = new HttpRequest(); + logger.debug("Send GET request to create service: {}", url); + logger.debug("Service headers: {}", headersMap); + RestResponse sendGetServerRequest = http.httpSendGet(url, headersMap); + + return sendGetServerRequest; + } + + public static Map<String, String> prepareHeadersMap(User sdncModifierDetails, boolean isCached) { + Map<String, String> headersMap = new HashMap<String, String>(); + if (isCached) + headersMap.put(HttpHeaderEnum.CACHE_CONTROL.getValue(), cacheControl); + + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId()); + return headersMap; + } + + public static RestResponse approveServiceDistribution(String serviceId, String userId) throws Exception { + return changeServiceDistributionState(serviceId, userId, Urls.APPROVE_DISTRIBUTION); + } + + public static RestResponse rejectServiceDistribution(String serviceId, String userId) throws Exception { + return changeServiceDistributionState(serviceId, userId, Urls.REJECT_DISTRIBUTION); + } + + // Benny + public static RestResponse rejectServiceDistribution(String serviceId, String userId, String comment) + throws Exception { + Config config = Utils.getConfig(); + String url = String.format(Urls.REJECT_DISTRIBUTION, config.getCatalogBeHost(), config.getCatalogBePort(), + serviceId); + String userBodyJson = gson.toJson(comment); + return sendPost(url, userBodyJson, userId, acceptHeaderData); + + } + + private static RestResponse changeServiceDistributionState(String serviceId, String userId, String distributionUrl) + throws Exception { + Config config = Utils.getConfig(); + String url = String.format(distributionUrl, config.getCatalogBeHost(), config.getCatalogBePort(), serviceId); + String defComment = "{ userRemarks : \"this is an test\" }"; + String userBodyJson = gson.toJson(defComment); + return sendPost(url, userBodyJson, userId, acceptHeaderData); + + } + + public static RestResponse getServiceLatestVersionList(User sdncModifierDetails) throws IOException { + + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_SERVICE_lATEST_VERSION, config.getCatalogBeHost(), + config.getCatalogBePort()); + + return sendGet(url, sdncModifierDetails.getUserId()); + + } + + public static RestResponse createServiceByHttpMethod(ServiceReqDetails serviceDetails, User sdncModifierDetails, + String method, String urls) throws IOException { + Map<String, String> headersMap = prepareHeadersMap(sdncModifierDetails, true); + + Config config = Utils.getConfig(); + String serviceBodyJson = gson.toJson(serviceDetails); + HttpRequest http = new HttpRequest(); + String url = String.format(urls, config.getCatalogBeHost(), config.getCatalogBePort()); + // TODO: ADD AUTHENTICATION IN REQUEST + logger.debug(url); + logger.debug("Send {} request to create user: {}", method, url); + logger.debug("User body: {}", serviceBodyJson); + logger.debug("User headers: {}", headersMap); + RestResponse sendCreateUserRequest = http.httpSendByMethod(url, method, serviceBodyJson, headersMap); + + return sendCreateUserRequest; + + } + + public static RestResponse deleteServiceByNameAndVersion(User sdncModifierDetails, String serviceName, + String serviceVersion) throws IOException { + Config config = Utils.getConfig(); + + Map<String, String> headersMap = prepareHeadersMap(sdncModifierDetails, true); + + HttpRequest http = new HttpRequest(); + + String url = String.format(Urls.DELETE_SERVICE_BY_NAME_AND_VERSION, config.getCatalogBeHost(), + config.getCatalogBePort(), serviceName, serviceVersion); + RestResponse deleteResponse = http.httpSendDelete(url, headersMap); + + return deleteResponse; + } + + public static RestResponse getFollowed(User user) throws Exception { + Config config = Utils.getConfig(); + + HttpRequest httpRequest = new HttpRequest(); + + String url = String.format(Urls.GET_FOLLWED_LIST, config.getCatalogBeHost(), config.getCatalogBePort()); + + Map<String, String> headersMap = new HashMap<String, String>(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json"); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json"); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), user.getUserId()); + + RestResponse getResourceNotAbstarctResponse = httpRequest.httpSendGet(url, headersMap); + + return getResourceNotAbstarctResponse; + } + + public static JSONArray getListArrayFromRestResponse(RestResponse restResponse) { + String json = restResponse.getResponse(); + JSONObject jsonResp = (JSONObject) JSONValue.parse(json); + JSONArray servicesArray = (JSONArray) jsonResp.get("services"); + + logger.debug("services = {}", servicesArray); + + return servicesArray; + } + +} diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/UserRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/UserRestUtils.java new file mode 100644 index 0000000000..a8f39b9ad8 --- /dev/null +++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/UserRestUtils.java @@ -0,0 +1,282 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.utils.rest; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import org.apache.commons.lang.StringUtils; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.api.Urls; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum; +import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.run.StartTest; +import org.openecomp.sdc.ci.tests.utils.Utils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.gson.Gson; + +public class UserRestUtils extends BaseRestUtils { + + static Gson gson = new Gson(); + + static Logger logger = LoggerFactory.getLogger(UserRestUtils.class.getName()); + static String contentTypeHeaderData = "application/json"; + static String acceptHeaderDate = "application/json"; + + public UserRestUtils() { + super(); + + StartTest.enableLogger(); + } + + public static RestResponse createUser(User sdncUserDetails, User sdncModifierDetails) throws IOException { + + Config config = Utils.getConfig(); + + Map<String, String> headersMap = new HashMap<String, String>(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId()); + + String userBodyJson = gson.toJson(sdncUserDetails); + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.CREATE_USER, config.getCatalogBeHost(), config.getCatalogBePort()); + + logger.debug("Send POST request to create user: {}", url); + logger.debug("User body: {}", userBodyJson); + logger.debug("User headers: {}", headersMap); + RestResponse sendCreateUserRequest = http.httpSendPost(url, userBodyJson, headersMap); + + return sendCreateUserRequest; + + } + + public static RestResponse deactivateUser(User sdncUserDetails, User sdncModifierDetails) throws IOException { + return deleteUser(sdncUserDetails, sdncModifierDetails, true); + } + + public static RestResponse deActivateUser(User sdncUserDetails, User sdncModifierDetails) throws IOException { + return deleteUser(sdncUserDetails, sdncModifierDetails, false); + } + + public static RestResponse deleteUser(User sdncUserDetails, User sdncModifierDetails, boolean isForceDelete) + throws IOException { + + Config config = Utils.getConfig(); + + Map<String, String> headersMap = new HashMap<String, String>(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId()); + if (isForceDelete) { + headersMap.put(User.FORCE_DELETE_HEADER_FLAG, User.FORCE_DELETE_HEADER_FLAG); + } + + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.DELETE_USER, config.getCatalogBeHost(), config.getCatalogBePort(), + sdncUserDetails.getUserId()); + RestResponse sendDeleteUserRequest = http.httpSendDelete(url, headersMap); + return sendDeleteUserRequest; + + } + + public static RestResponse updateUser(User sdncUserDetails, User sdncModifierDetails) + throws IOException, CloneNotSupportedException { + + Config config = Utils.getConfig(); + User user = new User(sdncModifierDetails); + + Map<String, String> headersMap = new HashMap<String, String>(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId()); + + user.setUserId(StringUtils.EMPTY); + user.setRole(StringUtils.EMPTY); + + Gson gson = new Gson(); + String userBodyJson = gson.toJson(user); + logger.debug("userBodyJson: {}", userBodyJson); + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.UPDATE_USER, config.getCatalogBeHost(), config.getCatalogBePort(), + sdncModifierDetails.getUserId()); + RestResponse sendUpdateUserRequest = http.httpSendPost(url, userBodyJson, headersMap); + + return sendUpdateUserRequest; + } + + /// Benny + public static RestResponse updateUserRole(User sdncUserDetails, User sdncModifierDetails, String userIdToUpdate) + throws IOException { + + Config config = Utils.getConfig(); + + Map<String, String> headersMap = new HashMap<String, String>(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId()); + + Gson gson = new Gson(); + String userBodyJson = gson.toJson(sdncUserDetails); + logger.debug("userBodyJson: {}", userBodyJson); + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.UPDATE_USER_ROLE, config.getCatalogBeHost(), config.getCatalogBePort(), + userIdToUpdate); + RestResponse sendUpdateUserRequest = http.httpSendPost(url, userBodyJson, headersMap); + + return sendUpdateUserRequest; + + } + + public static RestResponse getUser(User sdncUserDetails, User sdncModifierDetails) throws IOException { + + Config config = Utils.getConfig(); + + Map<String, String> headersMap = new HashMap<String, String>(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId()); + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.GET_USER, config.getCatalogBeHost(), config.getCatalogBePort(), + sdncUserDetails.getUserId()); + RestResponse sendGetUserRequest = http.httpSendGet(url, headersMap); + return sendGetUserRequest; + + } + + public static RestResponse getAllAdminUsers(User sdncModifierDetails) throws IOException { + + Config config = Utils.getConfig(); + + Map<String, String> headersMap = new HashMap<String, String>(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId()); + + // Gson gson = new Gson(); + // String userBodyJson = gson.toJson(sdncModifierDetails); + // System.out.println(userBodyJson); + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.GET_ALL_ADMIN_USERS, config.getCatalogBeHost(), config.getCatalogBePort()); + logger.debug("Send following url: {} and headers: {}", url, headersMap.toString()); + RestResponse sendGetUserRequest = http.httpSendGet(url, headersMap); + + return sendGetUserRequest; + + } + + // US571255 + public static RestResponse getUsersByRoles(User sdncModifierDetails, String roles) throws IOException { + + Config config = Utils.getConfig(); + Map<String, String> headersMap = new HashMap<String, String>(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId()); + + HttpRequest http = new HttpRequest(); + String url; + if (roles == "/") { + url = String.format(Urls.GET_ALL_USERS, config.getCatalogBeHost(), config.getCatalogBePort()); + } else { + url = String.format(Urls.GET_USERS_BY_ROLES, config.getCatalogBeHost(), config.getCatalogBePort(), roles); + + } + logger.debug("Send following url: {} and headers: {}", url, headersMap.toString()); + RestResponse sendGetUserRequest = http.httpSendGet(url, headersMap); + return sendGetUserRequest; + } + + public static RestResponse getUsersByRolesHttpCspAtuUidIsMissing(User sdncModifierDetails, String roles) + throws Exception { + + Config config = Utils.getConfig(); + Map<String, String> headersMap = new HashMap<String, String>(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId()); + headersMap.remove("USER_ID"); + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.GET_USERS_BY_ROLES, config.getCatalogBeHost(), config.getCatalogBePort(), + roles); + logger.debug( + "Send following url without USER_ID header : " + url + " headers: " + headersMap.toString()); + + RestResponse sendGetUserRequest = http.httpSendGet(url, headersMap); + return sendGetUserRequest; + } + + public static RestResponse authorizedUserTowardsCatalogBe(User sdncUserDetails) throws IOException { + + Map<String, String> headersMap = new HashMap<String, String>(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json"); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json"); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncUserDetails.getUserId()); + if (sdncUserDetails.getFirstName() != null) { + headersMap.put(HttpHeaderEnum.HTTP_CSP_FIRSTNAME.getValue(), sdncUserDetails.getFirstName()); + } + if (sdncUserDetails.getLastName() != null) { + headersMap.put(HttpHeaderEnum.HTTP_CSP_LASTNAME.getValue(), sdncUserDetails.getLastName()); + } + if (sdncUserDetails.getEmail() != null) { + headersMap.put(HttpHeaderEnum.HTTP_CSP_EMAIL.getValue(), sdncUserDetails.getEmail()); + } + + logger.debug("headersMap: {}", headersMap.toString()); + + Config config = Utils.getConfig(); + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.AUTHORIZE_USER, config.getCatalogBeHost(), config.getCatalogBePort()); + logger.debug("Send GET request to login as seal user : {}", url); + return http.httpSendGet(url, headersMap); + } + + public static RestResponse authorizedUserTowardsCatalogBeQA(User sdncUserDetails) throws IOException { + + Map<String, String> headersMap = new HashMap<String, String>(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json"); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json"); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncUserDetails.getUserId()); + if (sdncUserDetails.getFirstName() != null) { + headersMap.put(HttpHeaderEnum.HTTP_CSP_FIRSTNAME.getValue(), sdncUserDetails.getFirstName()); + } + if (sdncUserDetails.getLastName() != null) { + headersMap.put(HttpHeaderEnum.HTTP_CSP_LASTNAME.getValue(), sdncUserDetails.getLastName()); + } + if (sdncUserDetails.getEmail() != null) { + headersMap.put(HttpHeaderEnum.HTTP_CSP_EMAIL.getValue(), sdncUserDetails.getEmail()); + } + + logger.debug("headersMap: {}", headersMap.toString()); + + Config config = Utils.getConfig(); + HttpRequest http = new HttpRequest(); + String url = String.format(Urls.AUTHORIZE_USER, config.getCatalogBeHost(), config.getCatalogBePort()); + logger.debug("Send GET request to login as seal user : {}", url); + return http.httpSendGet(url, headersMap); + } + +} |