From 66af8b9b391879be78660d6ccb0a1f1f9340b423 Mon Sep 17 00:00:00 2001 From: Ittay Stern Date: Mon, 11 Mar 2019 09:34:34 +0200 Subject: Merge automation from ECOMP's repository Reference commit in ECOMP: 8e92a8c6 Issue-ID: VID-378 Change-Id: Ia32f4813378ef95097f788246aa5b1172e20ca48 Signed-off-by: Ittay Stern --- .../org/onap/sdc/ci/tests/api/BaseRestUtils.java | 263 ++++++ .../ci/tests/datatypes/ArtifactAssetStructure.java | 135 ++++ .../sdc/ci/tests/datatypes/AssetStructure.java | 122 +++ .../onap/sdc/ci/tests/datatypes/CanvasElement.java | 65 ++ .../onap/sdc/ci/tests/datatypes/CanvasManager.java | 268 +++++++ .../ci/tests/datatypes/ComponentReqDetails.java | 272 +++++++ .../onap/sdc/ci/tests/datatypes/Configuration.java | 325 ++++++++ .../onap/sdc/ci/tests/datatypes/CsarArtifacts.java | 59 ++ .../sdc/ci/tests/datatypes/DataTestIdEnum.java | 835 +++++++++++++++++++ .../ci/tests/datatypes/LocalLoginFieldsIds.java | 30 + .../datatypes/PropertyHeatMetaDefinition.java | 63 ++ .../ci/tests/datatypes/ResourceAssetStructure.java | 76 ++ .../datatypes/ResourceDetailedAssetStructure.java | 71 ++ .../datatypes/ResourceExternalReqDetails.java | 104 +++ .../datatypes/ResourceInstanceAssetStructure.java | 116 +++ .../sdc/ci/tests/datatypes/ResourceReqDetails.java | 194 +++++ .../ci/tests/datatypes/ResourceRespJavaObject.java | 369 +++++++++ .../ci/tests/datatypes/ServiceAssetStructure.java | 49 ++ .../datatypes/ServiceDetailedAssetStructure.java | 78 ++ .../tests/datatypes/ServiceDistributionStatus.java | 80 ++ .../sdc/ci/tests/datatypes/ServiceReqDetails.java | 74 ++ .../ci/tests/datatypes/ServiceRespJavaObject.java | 267 +++++++ .../sdc/ci/tests/datatypes/TopMenuButtonsEnum.java | 38 + .../java/org/onap/sdc/ci/tests/datatypes/User.java | 189 +++++ .../sdc/ci/tests/datatypes/UserCredentials.java | 53 ++ .../onap/sdc/ci/tests/datatypes/UserRoleEnum.java | 77 ++ .../sdc/ci/tests/datatypes/http/HeaderData.java | 114 +++ .../sdc/ci/tests/datatypes/http/HeaderValue.java | 38 + .../ci/tests/datatypes/http/HttpHeaderEnum.java | 58 ++ .../sdc/ci/tests/datatypes/http/HttpRequest.java | 889 +++++++++++++++++++++ .../sdc/ci/tests/datatypes/http/MustHeaders.java | 53 ++ .../sdc/ci/tests/datatypes/http/RestResponse.java | 84 ++ .../tests/devObjects/CategoryDataDefinition.java | 111 +++ .../ci/tests/devObjects/CategoryDefinition.java | 64 ++ .../sdc/ci/tests/devObjects/GraphPropertyEnum.java | 103 +++ .../tests/devObjects/GroupingDataDefinition.java | 112 +++ .../ci/tests/devObjects/GroupingDefinition.java | 33 + .../tests/devObjects/JsonPresentationFields.java | 193 +++++ .../ci/tests/devObjects/LifecycleStateEnum.java | 44 + .../sdc/ci/tests/devObjects/ResourceTypeEnum.java | 101 +++ .../devObjects/SubCategoryDataDefinition.java | 128 +++ .../ci/tests/devObjects/SubCategoryDefinition.java | 58 ++ .../ci/tests/devObjects/ToscaDataDefinition.java | 79 ++ .../sdc/ci/tests/execute/setup/DriverFactory.java | 132 +++ .../sdc/ci/tests/execute/setup/ExtentManager.java | 177 ++++ .../ci/tests/execute/setup/ExtentTestActions.java | 114 +++ .../ci/tests/execute/setup/ExtentTestManager.java | 60 ++ .../onap/sdc/ci/tests/execute/setup/MobProxy.java | 103 +++ .../ci/tests/execute/setup/OnboardCSVReport.java | 63 ++ .../execute/setup/ReportAfterTestManager.java | 129 +++ .../org/onap/sdc/ci/tests/execute/setup/Retry.java | 44 + .../sdc/ci/tests/execute/setup/SetupCDTest.java | 356 +++++++++ .../ci/tests/execute/setup/WebDriverThread.java | 177 ++++ .../sdc/ci/tests/execute/setup/WindowTest.java | 84 ++ .../ci/tests/execute/setup/WindowTestManager.java | 52 ++ .../java/org/onap/sdc/ci/tests/run/RunTest.java | 25 + .../java/org/onap/sdc/ci/tests/run/StartTest.java | 87 ++ .../ci/tests/utilities/AdditionalConditions.java | 133 +++ .../onap/sdc/ci/tests/utilities/CanvasElement.java | 54 ++ .../onap/sdc/ci/tests/utilities/CanvasManager.java | 179 +++++ .../org/onap/sdc/ci/tests/utilities/Constants.java | 128 +++ .../org/onap/sdc/ci/tests/utilities/Decoder.java | 62 ++ .../ci/tests/utilities/EcompPortalUtilities.java | 17 + .../onap/sdc/ci/tests/utilities/FileHandling.java | 489 ++++++++++++ .../org/onap/sdc/ci/tests/utilities/FindUtils.java | 52 ++ .../sdc/ci/tests/utilities/GeneralUIUtils.java | 803 +++++++++++++++++++ .../sdc/ci/tests/utilities/GeneralUtility.java | 155 ++++ .../onap/sdc/ci/tests/utilities/LoginUtils.java | 42 + 68 files changed, 10251 insertions(+) create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/api/BaseRestUtils.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/ArtifactAssetStructure.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/AssetStructure.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/CanvasElement.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/CanvasManager.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/ComponentReqDetails.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/Configuration.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/CsarArtifacts.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/DataTestIdEnum.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/LocalLoginFieldsIds.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/PropertyHeatMetaDefinition.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/ResourceAssetStructure.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/ResourceDetailedAssetStructure.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/ResourceExternalReqDetails.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/ResourceInstanceAssetStructure.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/ResourceReqDetails.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/ResourceRespJavaObject.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/ServiceAssetStructure.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/ServiceDetailedAssetStructure.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/ServiceDistributionStatus.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/ServiceReqDetails.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/ServiceRespJavaObject.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/TopMenuButtonsEnum.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/User.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/UserCredentials.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/UserRoleEnum.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/http/HeaderData.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/http/HeaderValue.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/http/HttpHeaderEnum.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/http/HttpRequest.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/http/MustHeaders.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/http/RestResponse.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/devObjects/CategoryDataDefinition.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/devObjects/CategoryDefinition.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/devObjects/GraphPropertyEnum.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/devObjects/GroupingDataDefinition.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/devObjects/GroupingDefinition.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/devObjects/JsonPresentationFields.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/devObjects/LifecycleStateEnum.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/devObjects/ResourceTypeEnum.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/devObjects/SubCategoryDataDefinition.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/devObjects/SubCategoryDefinition.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/devObjects/ToscaDataDefinition.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/execute/setup/DriverFactory.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/execute/setup/ExtentManager.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/execute/setup/ExtentTestActions.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/execute/setup/ExtentTestManager.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/execute/setup/MobProxy.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/execute/setup/OnboardCSVReport.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/execute/setup/ReportAfterTestManager.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/execute/setup/Retry.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/execute/setup/SetupCDTest.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/execute/setup/WebDriverThread.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/execute/setup/WindowTest.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/execute/setup/WindowTestManager.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/run/RunTest.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/run/StartTest.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/utilities/AdditionalConditions.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/utilities/CanvasElement.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/utilities/CanvasManager.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/utilities/Constants.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/utilities/Decoder.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/utilities/EcompPortalUtilities.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/utilities/FileHandling.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/utilities/FindUtils.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/utilities/GeneralUIUtils.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/utilities/GeneralUtility.java create mode 100644 vid-automation/src/main/java/org/onap/sdc/ci/tests/utilities/LoginUtils.java (limited to 'vid-automation/src/main/java/org/onap/sdc') diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/api/BaseRestUtils.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/api/BaseRestUtils.java new file mode 100644 index 000000000..f85225f36 --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/api/BaseRestUtils.java @@ -0,0 +1,263 @@ +/*- + * ============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.onap.sdc.ci.tests.api; + +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.onap.sdc.ci.tests.datatypes.http.HttpHeaderEnum; +import org.onap.sdc.ci.tests.datatypes.http.HttpRequest; +import org.onap.sdc.ci.tests.datatypes.http.RestResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class BaseRestUtils { + 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 = "onap"; + 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 prepareHeadersMap(String userId) { + return prepareHeadersMap(userId, acceptHeaderData); + } + + protected static Map prepareHeadersMap(String userId, String accept) { + Map headersMap = new HashMap(); + 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 additionalHeaders) + throws IOException { + Map 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 headersToRemove) + throws IOException { + Map 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 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 additionalHeaders) throws IOException { + Map 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.setStatusCode(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 headersMap = prepareHeadersMap(userId); + + return sendDelete(url, userId, null); + } + + protected static RestResponse sendDelete(String url, String userId, Map additionalHeaders) throws IOException { + Map headersMap = prepareHeadersMap(userId); + if (additionalHeaders != null) { + headersMap.putAll(additionalHeaders); + } + + 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 addAuthorizeHeader(String userName, String password) { + String userCredentials = userName + ":" + password; + encodeBase64 = Base64.encodeBase64(userCredentials.getBytes()); + String encodedUserCredentials = authorizationPrefixString + new String(encodeBase64); + Map authorizationHeader = new HashMap(); + authorizationHeader.put(HttpHeaderEnum.AUTHORIZATION.getValue(), encodedUserCredentials); + return authorizationHeader; + } + +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/ArtifactAssetStructure.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/ArtifactAssetStructure.java new file mode 100644 index 000000000..8eb4fa38b --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/ArtifactAssetStructure.java @@ -0,0 +1,135 @@ +/*- + * ============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.onap.sdc.ci.tests.datatypes; + +public class ArtifactAssetStructure { + + String artifactName; + String artifactType; + String artifactURL; + String artifactDescription; + int artifactTimeout;// optional + String artifactChecksum; + String artifactUUID; + String artifactVersion; + String generatedFromUUID;// optional + + public ArtifactAssetStructure(String artifactName, String artifactType, String artifactURL, + String artifactDescription, int artifactTimeout, String artifactChecksum, String artifactUUID, + String artifactVersion, String generatedFromUUID) { + super(); + this.artifactName = artifactName; + this.artifactType = artifactType; + this.artifactURL = artifactURL; + this.artifactDescription = artifactDescription; + this.artifactTimeout = artifactTimeout; + this.artifactChecksum = artifactChecksum; + this.artifactUUID = artifactUUID; + this.artifactVersion = artifactVersion; + this.generatedFromUUID = generatedFromUUID; + } + + public ArtifactAssetStructure() { + super(); + // TODO Auto-generated constructor stub + } + + public String getArtifactName() { + return artifactName; + } + + public void setArtifactName(String artifactName) { + this.artifactName = artifactName; + } + + public String getArtifactType() { + return artifactType; + } + + public void setArtifactType(String artifactType) { + this.artifactType = artifactType; + } + + public String getArtifactURL() { + return artifactURL; + } + + public void setArtifactURL(String artifactURL) { + this.artifactURL = artifactURL; + } + + public String getArtifactDescription() { + return artifactDescription; + } + + public void setArtifactDescription(String artifactDescription) { + this.artifactDescription = artifactDescription; + } + + public int getArtifactTimeout() { + return artifactTimeout; + } + + public void setArtifactTimeout(int artifactTimeout) { + this.artifactTimeout = artifactTimeout; + } + + public String getArtifactChecksum() { + return artifactChecksum; + } + + public void setArtifactChecksum(String artifactChecksum) { + this.artifactChecksum = artifactChecksum; + } + + public String getArtifactUUID() { + return artifactUUID; + } + + public void setArtifactUUID(String artifactUUID) { + this.artifactUUID = artifactUUID; + } + + public String getArtifactVersion() { + return artifactVersion; + } + + public void setArtifactVersion(String artifactVersion) { + this.artifactVersion = artifactVersion; + } + + public String getGeneratedFromUUID() { + return generatedFromUUID; + } + + public void setGeneratedFromUUID(String generatedFromUUID) { + this.generatedFromUUID = generatedFromUUID; + } + + @Override + public String toString() { + return "ArtifactAssetStructure [artifactName=" + artifactName + ", artifactType=" + artifactType + + ", artifactURL=" + artifactURL + ", artifactDescription=" + artifactDescription + ", artifactTimeout=" + + artifactTimeout + ", artifactChecksum=" + artifactChecksum + ", artifactUUID=" + artifactUUID + + ", artifactVersion=" + artifactVersion + ", generatedFromUUID=" + generatedFromUUID + "]"; + } + +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/AssetStructure.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/AssetStructure.java new file mode 100644 index 000000000..345181d6c --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/AssetStructure.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.onap.sdc.ci.tests.datatypes; + +public class AssetStructure { + + private String uuid; + private String invariantUUID; + private String name; + private String version; + private String toscaModelURL; + private String category; + private String lifecycleState; + private String lastUpdaterUserId; + + public AssetStructure() { + super(); + } + + public AssetStructure(String uuid, String invariantUUID, String name, String version, String toscaModelURL, + String category, String lifecycleState, String lastUpdaterUserId) { + super(); + this.uuid = uuid; + this.invariantUUID = invariantUUID; + this.name = name; + this.version = version; + this.toscaModelURL = toscaModelURL; + this.category = category; + this.lifecycleState = lifecycleState; + this.lastUpdaterUserId = lastUpdaterUserId; + } + + @Override + public String toString() { + return "AssetStructure [uuid=" + uuid + ", invariantUUID=" + invariantUUID + ", name=" + name + ", version=" + + version + ", toscaModelURL=" + toscaModelURL + ", category=" + category + ", lifecycleState=" + + lifecycleState + ", lastUpdaterUserId=" + lastUpdaterUserId + "]"; + } + + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public String getInvariantUUID() { + return invariantUUID; + } + + public void setInvariantUUID(String invariantUUID) { + this.invariantUUID = invariantUUID; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getToscaModelURL() { + return toscaModelURL; + } + + public void setToscaModelURL(String toscaModelURL) { + this.toscaModelURL = toscaModelURL; + } + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + public String getLifecycleState() { + return lifecycleState; + } + + public void setLifecycleState(String lifecycleState) { + this.lifecycleState = lifecycleState; + } + + public String getLastUpdaterUserId() { + return lastUpdaterUserId; + } + + public void setLastUpdaterUserId(String lastUpdaterUserId) { + this.lastUpdaterUserId = lastUpdaterUserId; + } + +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/CanvasElement.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/CanvasElement.java new file mode 100644 index 000000000..a17c38c7f --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/CanvasElement.java @@ -0,0 +1,65 @@ +/*- + * ============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.onap.sdc.ci.tests.datatypes; + +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.onap.sdc.ci.tests.datatypes.DataTestIdEnum.LeftPanelCanvasItems; + +public final class CanvasElement { + private final String uniqueId; + private ImmutablePair location; + private LeftPanelCanvasItems normativeElementType; + private String elementType; + + CanvasElement(String name, ImmutablePair location, LeftPanelCanvasItems canvasItem) { + super(); + this.uniqueId = name; + this.location = location; + normativeElementType = canvasItem; + } + + CanvasElement(String name, ImmutablePair location, String canvasItem) { + super(); + this.uniqueId = name; + this.location = location; + elementType = canvasItem; + } + + public String getUniqueId() { + return uniqueId; + } + + public ImmutablePair getLocation() { + return location; + } + + public void setLocation(ImmutablePair location) { + this.location = location; + } + + public LeftPanelCanvasItems getNormativeElementType() { + return normativeElementType; + } + + public String getElementType() { + return elementType; + } +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/CanvasManager.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/CanvasManager.java new file mode 100644 index 000000000..999a63bb3 --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/CanvasManager.java @@ -0,0 +1,268 @@ +/*- + * ============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.onap.sdc.ci.tests.datatypes; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Random; +import java.util.UUID; +import java.util.stream.Collectors; + +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.onap.sdc.ci.tests.datatypes.DataTestIdEnum.LeftPanelCanvasItems; +import org.onap.sdc.ci.tests.execute.setup.ExtentTestActions; +import org.onap.sdc.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.ci.tests.utilities.GeneralUIUtils; +import org.openqa.selenium.By; +import org.openqa.selenium.StaleElementReferenceException; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.interactions.Actions; +import org.testng.Assert; + +import com.aventstack.extentreports.Status; + +public final class CanvasManager { + private Map canvasElements; + private Actions actions; + private WebElement canvas; + private int reduceCanvasWidthFactor; + private CanvasElement canvasElement; + // Offsets Are used to find upper right corner of canvas element in order to + // connect links + private static final int CANVAS_ELEMENT_Y_OFFSET = 30; + private static final int CANVAS_ELEMENT_X_OFFSET = 18; // 14 - 27 + + private CanvasManager() { + canvasElements = new HashMap<>(); + actions = new Actions(GeneralUIUtils.getDriver()); + canvas = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.GeneralCanvasItems.CANVAS.getValue()); + try { + WebElement webElement = GeneralUIUtils + .getWebElementByTestID(DataTestIdEnum.GeneralCanvasItems.CANVAS_RIGHT_PANEL.getValue()); + reduceCanvasWidthFactor = webElement.getSize().width; + } catch (Exception e) { + reduceCanvasWidthFactor = 0; + } + } + + public static CanvasManager getCanvasManager() { + return new CanvasManager(); + } + + public List getCanvasElements() { + return canvasElements.values().stream().collect(Collectors.toList()); + } + + private void addCanvasElement(CanvasElement element) { + canvasElements.put(element.getUniqueId(), element); + } + + private void moveElementOnCanvas(CanvasElement canvasElement, ImmutablePair newLocation) + throws Exception { + GeneralUIUtils.waitForLoader(); + actions.moveToElement(canvas, canvasElement.getLocation().left, canvasElement.getLocation().right); + actions.clickAndHold(); + actions.moveToElement(canvas, newLocation.left, newLocation.right); + actions.release(); + actions.perform(); + canvasElement.setLocation(newLocation); + GeneralUIUtils.waitForLoader(); + + } + + public void moveToFreeLocation(String containerName) { + int maxWait = 5000; + int sumOfWaiting = 0; + int napPeriod = 200; + boolean isKeepWaiting = false; + while (!isKeepWaiting) { + ImmutablePair freePosition = getFreePosition(); + actions.moveToElement(canvas, freePosition.left, freePosition.right); + actions.clickAndHold(); + actions.release(); + actions.perform(); + isKeepWaiting = GeneralUIUtils.getWebElementByTestID("selectedCompTitle").getText() + .equals(containerName); + sumOfWaiting += napPeriod; + if (sumOfWaiting > maxWait) { + Assert.fail("Can't click on VF"); + } + } + } + + public void clickOnCanvaElement(CanvasElement canvasElement) { + actions.moveToElement(canvas, canvasElement.getLocation().left, canvasElement.getLocation().right); + actions.clickAndHold(); + actions.release(); + actions.perform(); + actions.click().perform(); + GeneralUIUtils.ultimateWait(); + ExtentTestActions.log(Status.INFO, String.format("Canvas element %s selected", canvasElement.getElementType())); + } + + public void moveElementOnCanvas(CanvasElement canvasElement) throws Exception { + moveElementOnCanvas(canvasElement, getFreePosition()); + } + + public void deleteElementFromCanvas(CanvasElement canvasElement) throws Exception { + GeneralUIUtils.waitForLoader(); + actions.moveToElement(canvas, canvasElement.getLocation().left, canvasElement.getLocation().right); + actions.click(); + actions.perform(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.GeneralCanvasItems.DELETE_INSTANCE_BUTTON.getValue()) + .click(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ModalItems.OK.getValue()).click(); + canvasElements.remove(canvasElement.getUniqueId()); + GeneralUIUtils.ultimateWait(); + if (canvasElement.getElementType().contains("-")){ + ExtentTestActions.log(Status.INFO, String.format("Canvas element %s removed", canvasElement.getElementType().split("-")[4])); + } + else{ + ExtentTestActions.log(Status.INFO, String.format("Canvas element %s removed", canvasElement.getElementType())); + } + } + + private WebElement findClickElement(String dataTestId) { + int attempts = 0; + while (attempts < 2) { + try { + return GeneralUIUtils.getWebElementByTestID(dataTestId); + } catch (StaleElementReferenceException e) { + } + attempts++; + } + return null; + } + + public CanvasElement createElementOnCanvas(String elementName) throws Exception { + String actionDuration = GeneralUIUtils.getActionDuration(() -> { + try { + canvasElement = createElementOnCanvasWithoutDuration(elementName); + } catch (Exception e) { + e.printStackTrace(); + } + }); + + if (canvasElement != null){ + ExtentTestActions.log(Status.INFO, String.format("The element %s should now be on the canvas", elementName), actionDuration); + } + return canvasElement; + } + + private CanvasElement createElementOnCanvasWithoutDuration(String elementDataTestId) throws Exception { + try { + WebElement element = findClickElement(elementDataTestId); + ImmutablePair freePosition = getFreePosition(); + actions.moveToElement(element, 20, 20); + actions.clickAndHold(); + actions.moveToElement(canvas, freePosition.left, freePosition.right); + actions.release(); + actions.perform(); + GeneralUIUtils.ultimateWait(); + String uniqueId = elementDataTestId + "_" + UUID.randomUUID().toString(); + CanvasElement canvasElement = new CanvasElement(uniqueId, freePosition, elementDataTestId); + addCanvasElement(canvasElement); + GeneralUIUtils.ultimateWait(); + return canvasElement; + } + catch (Exception e) { + System.out.println("Can't create element on canvas"); + e.printStackTrace(); + } + return null; + } + + public CanvasElement createElementOnCanvas(LeftPanelCanvasItems canvasItem) throws Exception { + return createElementOnCanvas(canvasItem.getValue()); + } + + private ImmutablePair getFreePosition() { + ImmutablePair randomPosition = null; + boolean freePosition = false; + int minSpace = 150; + while (!freePosition) { + ImmutablePair tempRandomPosition = getRandomPosition(); + freePosition = !canvasElements.values().stream().map(e -> e.getLocation()) + .filter(e -> Math.abs(e.left - tempRandomPosition.left) < minSpace + && Math.abs(e.right - tempRandomPosition.right) < minSpace) + .findAny().isPresent(); + randomPosition = tempRandomPosition; + } + return randomPosition; + } + + private ImmutablePair getRandomPosition() { + int edgeBuffer = 50; + Random random = new Random(); + int xElement = random.nextInt(canvas.getSize().width - 2 * edgeBuffer - reduceCanvasWidthFactor) + edgeBuffer; + int yElement = random.nextInt(canvas.getSize().height - 2 * edgeBuffer) + edgeBuffer; + return new ImmutablePair(xElement, yElement); + } + + public void linkElements(CanvasElement firstElement, CanvasElement secondElement) throws Exception { + ExtentTestActions.log(Status.INFO, String.format("Linking between the %s instance and the %s instance.", firstElement.getElementType(), secondElement.getElementType())); + drawSimpleLink(firstElement, secondElement); + selectReqAndCapAndConnect(); + ExtentTestActions.log(Status.INFO, String.format("The instances %s and %s should now be connected.", firstElement.getElementType(), secondElement.getElementType())); + } + + private void selectReqAndCapAndConnect() throws Exception { + // Select First Cap + GeneralUIUtils.getWebElementsListByTestID(DataTestIdEnum.LinkMenuItems.LINK_ITEM_CAP.getValue()).get(0).click(); + // Select First Req + GeneralUIUtils.getWebElementsListByTestID(DataTestIdEnum.LinkMenuItems.LINK_ITEM_REQ.getValue()).get(0).click(); + // Connect + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.LinkMenuItems.CONNECT_BUTTON.getValue()).click(); + + GeneralUIUtils.waitForLoader(); + } + + private void drawSimpleLink(CanvasElement firstElement, CanvasElement secondElement) throws Exception { + int yOffset = CANVAS_ELEMENT_Y_OFFSET; + int xOffset = CANVAS_ELEMENT_X_OFFSET; + + actions.moveToElement(canvas, firstElement.getLocation().left + xOffset, + firstElement.getLocation().right - yOffset); + + actions.clickAndHold(); + actions.moveToElement(canvas, secondElement.getLocation().left + xOffset, secondElement.getLocation().right - yOffset); + actions.release(); + actions.perform(); + GeneralUIUtils.ultimateWait(); + } + + public String updateElementNameInCanvas(CanvasElement canvasElement, String newInstanceName) throws Exception { + GeneralUIUtils.ultimateWait();; + clickOnCanvaElement(canvasElement); + WebElement updateInstanceName = GeneralUIUtils.getWebElementBy(By.id("editPencil")); + updateInstanceName.click(); + WebElement instanceNameField = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.GeneralCanvasItems.INSTANCE_NAME_FIELD.getValue()); + String oldInstanceName = instanceNameField.getAttribute("value"); + instanceNameField.clear(); + instanceNameField.sendKeys(newInstanceName); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ModalItems.OK.getValue()).click(); + GeneralUIUtils.ultimateWait(); + GeneralUIUtils.waitForElementInVisibilityByTestId(By.className("w-sdc-modal-resource-instance-name")); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Name of element instance changed from %s to %s", oldInstanceName, newInstanceName)); + return oldInstanceName; + } +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/ComponentReqDetails.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/ComponentReqDetails.java new file mode 100644 index 000000000..86d23e870 --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/ComponentReqDetails.java @@ -0,0 +1,272 @@ +/*- + * ============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.onap.sdc.ci.tests.datatypes; + +import java.util.ArrayList; +import java.util.List; + +import org.onap.sdc.ci.tests.devObjects.CategoryDefinition; +import org.onap.sdc.ci.tests.devObjects.LifecycleStateEnum; +import org.onap.sdc.ci.tests.devObjects.SubCategoryDefinition; + +public abstract class ComponentReqDetails { + + protected String name; + protected String description; + protected List tags = new ArrayList<>(); + protected String contactId; + protected String icon; + protected String uniqueId; + protected String creatorUserId; + protected String creatorFullName; + protected String lastUpdaterUserId; + protected String lastUpdaterFullName; + protected Long creationDate; + protected Long lastUpdateDate; + protected LifecycleStateEnum lifecycleState; + protected String version; + protected String UUID; + protected List categories; + protected String projectCode; + protected String csarUUID; + protected String csarVersion; + protected String importedToscaChecksum; + protected String invariantUUID; + + public String getCsarVersion() { + return csarVersion; + } + + public void setCsarVersion(String csarVersion) { + this.csarVersion = csarVersion; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + tags.add(name); + } + + public List getTags() { + return tags; + } + + public void setTags(List tags) { + this.tags = tags; + } + + // public String getCategory() { + // return category; + // } + // + public String getContactId() { + return contactId; + } + + public void setContactId(String contactId) { + this.contactId = contactId; + } + + public String getIcon() { + return icon; + } + + public void setIcon(String icon) { + this.icon = icon; + } + + public String getUniqueId() { + return uniqueId; + } + + public void setUniqueId(String uniqueId) { + this.uniqueId = uniqueId; + } + + public void setCreatorUserId(String creatorUserId) { + this.creatorUserId = creatorUserId; + } + + public void setCreatorFullName(String creatorFullName) { + this.creatorFullName = creatorFullName; + } + + public void setLastUpdaterUserId(String lastUpdaterUserId) { + this.lastUpdaterUserId = lastUpdaterUserId; + } + + public void setLastUpdaterFullName(String lastUpdaterFullName) { + this.lastUpdaterFullName = lastUpdaterFullName; + } + + public void setCreationDate(Long creationDate) { + this.creationDate = creationDate; + } + + public void setLastUpdateDate(Long lastUpdateDate) { + this.lastUpdateDate = lastUpdateDate; + } + + public void setLifecycleState(LifecycleStateEnum lifecycleState) { + this.lifecycleState = lifecycleState; + } + + public void setUUID(String uUID) { + this.UUID = uUID; + } + + public String getCreatorUserId() { + return creatorUserId; + } + + public String getCreatorFullName() { + return creatorFullName; + } + + public String getLastUpdaterUserId() { + return lastUpdaterUserId; + } + + public String getLastUpdaterFullName() { + return lastUpdaterFullName; + } + + public Long getCreationDate() { + return creationDate; + } + + public Long getLastUpdateDate() { + return lastUpdateDate; + } + + public LifecycleStateEnum getLifecycleState() { + return lifecycleState; + } + + public String getUUID() { + return UUID; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public List getCategories() { + return categories; + } + + public void setCategories(List categories) { + this.categories = categories; + } + + public void removeAllCategories() { + this.categories = new ArrayList<>(); + } + + public void addCategoryChain(String category, String subCategory) { + if (category != null || subCategory != null) { + if (categories == null) { + categories = new ArrayList<>(); + } + CategoryDefinition selectedCategory = null; + for (CategoryDefinition categoryDef : categories) { + if (categoryDef.getName().equals(category)) { + selectedCategory = categoryDef; + } + } + if (selectedCategory == null) { + selectedCategory = new CategoryDefinition(); + selectedCategory.setName(category); + categories.add(selectedCategory); + } + if (subCategory != null) { + List subcategories = selectedCategory.getSubcategories(); + if (subcategories == null) { + subcategories = new ArrayList<>(); + selectedCategory.setSubcategories(subcategories); + } + SubCategoryDefinition selectedSubcategory = null; + for (SubCategoryDefinition subcategory : subcategories) { + if (subcategory.getName().equals(subCategory)) { + selectedSubcategory = subcategory; + } + } + if (selectedSubcategory == null) { + selectedSubcategory = new SubCategoryDefinition(); + selectedSubcategory.setName(subCategory); + subcategories.add(selectedSubcategory); + } + } + } + } + + public void addCategory(String category) { + addCategoryChain(category, null); + } + + public String getProjectCode() { + return projectCode; + } + + public void setProjectCode(String projectCode) { + this.projectCode = projectCode; + } + + public String getCsarUUID() { + return csarUUID; + } + + public void setCsarUUID(String csarUUID) { + this.csarUUID = csarUUID; + } + + public String getImportedToscaChecksum() { + return importedToscaChecksum; + } + + public void setImportedToscaChecksum(String importedToscaChecksum) { + this.importedToscaChecksum = importedToscaChecksum; + } + + public String getInvariantUUID() { + return invariantUUID; + } + + public void setInvariantUUID(String invariantUUID) { + this.invariantUUID = invariantUUID; + } + +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/Configuration.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/Configuration.java new file mode 100644 index 000000000..d6a6c1f17 --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/Configuration.java @@ -0,0 +1,325 @@ +package org.onap.sdc.ci.tests.datatypes; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Paths; + +import org.yaml.snakeyaml.Yaml; + +public class Configuration { + + private String beHost; + private String feHost; + private int bePort; + private int fePort; + private String url; + private String remoteTestingMachineIP; + private int remoteTestingMachinePort; + private boolean remoteTesting; + private String browser; + private String systemUnderDebug; + private String reportDBhost; + private int reportDBport; + private boolean captureTraffic; + private boolean useBrowserMobProxy; + private String stopOnClassFailure; + private String reportFileName; + private String reportFolder; + private int numOfAttemptsToRefresh; + private boolean rerun; + private String windowsDownloadDirectory; + private String screenshotFolder; + private String harFilesFolder; + private boolean useCustomLogin; + private String geckoDriverPath; + + public Configuration(String url) { + super(); + basicInit(url, false); + } + + public Configuration(String url, boolean useCustomLogin) { + super(); + basicInit(url, useCustomLogin); + } + + private void basicInit(String url, boolean useCustomLogin) { + this.remoteTesting = false; + this.captureTraffic = false; + this.useBrowserMobProxy = false; + this.reportFolder = "." + File.separator + "ExtentReport" + File.separator; + this.reportFileName = "UI_Extent_Report.html"; + this.screenshotFolder = reportFolder + "screenshots" + File.separator; + this.harFilesFolder = reportFolder + "har_files" + File.separator; + this.browser = "firefox"; + this.url = url; + this.numOfAttemptsToRefresh = 2; + this.useCustomLogin = useCustomLogin; + this.geckoDriverPath = null; + } + + public String getGeckoDriverPath(){ + return this.geckoDriverPath; } + + public void setGeckoDriverPath(String geckoDriverPath){ this.geckoDriverPath = geckoDriverPath; } + + public String getBeHost() { + return beHost; + } + + public void setBeHost(String beHost) { + this.beHost = beHost; + } + + + public String getFeHost() { + return feHost; + } + + + public void setFeHost(String feHost) { + this.feHost = feHost; + } + + + public int getBePort() { + return bePort; + } + + + public void setBePort(int bePort) { + this.bePort = bePort; + } + + + public int getFePort() { + return fePort; + } + + + public void setFePort(int fePort) { + this.fePort = fePort; + } + + + public String getUrl() { + return url; + } + + + public void setUrl(String url) { + this.url = url; + } + + + public String getRemoteTestingMachineIP() { + return remoteTestingMachineIP; + } + + + public void setRemoteTestingMachineIP(String remoteTestingMachineIP) { + this.remoteTestingMachineIP = remoteTestingMachineIP; + } + + + public int getRemoteTestingMachinePort() { + return remoteTestingMachinePort; + } + + + public void setRemoteTestingMachinePort(int remoteTestingMachinePort) { + this.remoteTestingMachinePort = remoteTestingMachinePort; + } + + + public boolean isRemoteTesting() { + return remoteTesting; + } + + + public void setRemoteTesting(boolean remoteTesting) { + this.remoteTesting = remoteTesting; + } + + + public String getBrowser() { + return browser; + } + + + public void setBrowser(String browser) { + this.browser = browser; + } + + + public String getSystemUnderDebug() { + return systemUnderDebug; + } + + + public void setSystemUnderDebug(String systemUnderDebug) { + this.systemUnderDebug = systemUnderDebug; + } + + + public String getReportDBhost() { + return reportDBhost; + } + + + public void setReportDBhost(String reportDBhost) { + this.reportDBhost = reportDBhost; + } + + + public int getReportDBport() { + return reportDBport; + } + + + public void setReportDBport(int reportDBport) { + this.reportDBport = reportDBport; + } + + + public boolean isCaptureTraffic() { + return captureTraffic; + } + + + public void setCaptureTraffic(boolean captureTraffic) { + this.captureTraffic = captureTraffic; + } + + + public boolean isUseBrowserMobProxy() { + return useBrowserMobProxy; + } + + + public void setUseBrowserMobProxy(boolean useBrowserMobProxy) { + this.useBrowserMobProxy = useBrowserMobProxy; + } + + + public String getStopOnClassFailure() { + return stopOnClassFailure; + } + + + public void setStopOnClassFailure(String stopOnClassFailure) { + this.stopOnClassFailure = stopOnClassFailure; + } + + + public String getReportFileName() { + return reportFileName; + } + + + public void setReportFileName(String reportFileName) { + this.reportFileName = reportFileName; + } + + + public String getReportFolder() { + return reportFolder; + } + + + public void setReportFolder(String reportFolder) { + this.reportFolder = reportFolder; + } + + + public int getNumOfAttemptsToRefresh() { + return numOfAttemptsToRefresh; + } + + + public void setNumOfAttemptsToRefresh(int numOfAttemptsToRefresh) { + this.numOfAttemptsToRefresh = numOfAttemptsToRefresh; + } + + + public boolean isRerun() { + return rerun; + } + + + public void setRerun(boolean rerun) { + this.rerun = rerun; + } + + + + + public String getWindowsDownloadDirectory() { + return windowsDownloadDirectory; + } + + public void setWindowsDownloadDirectory(String windowsDownloadDirectory) { + this.windowsDownloadDirectory = windowsDownloadDirectory; + } + + public String getScreenshotFolder() { + return screenshotFolder; + } + + public void setScreenshotFolder(String screenshotFolder) { + this.screenshotFolder = screenshotFolder; + } + + public String getHarFilesFolder() { + return harFilesFolder; + } + + public void setHarFilesFolder(String harFilesFolder) { + this.harFilesFolder = harFilesFolder; + } + + public boolean isUseCustomLogin() { + return useCustomLogin; + } + + public void setUseCustomLogin(boolean useCustomLogin) { + this.useCustomLogin = useCustomLogin; + } + + public synchronized static Configuration loadConfigFile(File configFile) { + return loadConfigFile(configFile, Configuration.class); + } + + public Configuration(){ + super(); + } + + public synchronized static T loadConfigFile(File configFile, Class clazz){ + InputStream in = null; + T config = null; + try { + String absolutePath = configFile.getAbsolutePath(); + in = Files.newInputStream(Paths.get(absolutePath)); + Yaml yaml = new Yaml(); + config = yaml.loadAs(in, clazz); + + } catch (IOException e) { + e.printStackTrace(); + } finally { + if (in != null) { + try { + in.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + return config; + } + + + +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/CsarArtifacts.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/CsarArtifacts.java new file mode 100644 index 000000000..43dd8dfe3 --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/CsarArtifacts.java @@ -0,0 +1,59 @@ +/*- + * ============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.onap.sdc.ci.tests.datatypes; + +public class CsarArtifacts { + + private String artifactType; + private String artifactName; + + public CsarArtifacts() { + super(); + } + + public CsarArtifacts(String artifactName, String artifactType) { + super(); + this.artifactName = artifactName; + this.artifactType = artifactType; + } + + @Override + public String toString() { + return "AssetStructure [artifactName=" + artifactName + ", artifactType=" + artifactType + "]"; + } + + public String getArtifactType() { + return artifactType; + } + + public void setArtifactType(String artifactType) { + this.artifactType = artifactType; + } + + public String getArtifactName() { + return artifactName; + } + + public void setArtifactName(String artifactName) { + this.artifactName = artifactName; + } + +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/DataTestIdEnum.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/DataTestIdEnum.java new file mode 100644 index 000000000..98b184b93 --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/DataTestIdEnum.java @@ -0,0 +1,835 @@ +/*- + * ============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.onap.sdc.ci.tests.datatypes; + +import java.util.Arrays; +import java.util.List; + +public final class DataTestIdEnum { + private DataTestIdEnum() { + } + + public enum Dashboard { + IMPORT_AREA("importButtonsArea"), + ADD_AREA("AddButtonsArea"), + BUTTON_ADD_VF("createResourceButton"), + BUTTON_ADD_SERVICE("createServiceButton"), + IMPORT_VFC("importVFCbutton"), + IMPORT_VF("importVFbutton"), + IMPORT_VFC_FILE("file-importVFCbutton"), + IMPORT_VF_FILE("file-importVFbutton"), + BUTTON_ADD_PRODUCT("createProductButton"); + + private String value; + + public String getValue() { + return value; + } + + private Dashboard(String value) { + this.value = value; + } + } + + public enum LifeCyleChangeButtons { + CREATE("create/save"), + CHECK_IN("check_in"), + SUBMIT_FOR_TESTING("submit_for_testing"), + START_TESTING("start_testing"), + ACCEPT("accept"), + CHECKOUT("check_out"); + + private String value; + + public String getValue() { + return value; + } + + private LifeCyleChangeButtons(String value) { + this.value = value; + } + } + + public enum DistributionChangeButtons { + APPROVE("approve"), + REJECT("reject"), + DISTRIBUTE("distribute"), + MONITOR("monitor"), + APPROVE_MESSAGE("checkindialog"), + RE_DISTRIBUTE("redistribute"); + + private String value; + + public String getValue() { + return value; + } + + private DistributionChangeButtons(String value) { + this.value = value; + } + } + + public enum InformationalArtifactsPlaceholders { + CLOUD_QUESTIONNAIRE("Cloud Questionnaire (completed)"), + FEATURES("Features"), + VENDOR_TEST_RESULT("Vendor Test Result"), + TEST_SCRIPTS("Test Scripts"), + RESOURCE_SECURITY_TEMPLATE("Resource Security Template"), + HEAT_TEMPLATE_FROM_VENDOR("HEAT Template from Vendor"), + CAPACITY("Capacity"); + + private String value; + + public String getValue() { + return value; + } + + private InformationalArtifactsPlaceholders(String value) { + this.value = value; + } + } + + public enum ModalItems { + BROWSE_BUTTON("browseButton"), + ADD("Add"), + DESCRIPTION("description"), + SUMBIT_FOR_TESTING_MESSAGE("changeLifeCycleMessage"), + OK("OK"), + CANCEL("Cancel"), + ACCEP_TESTING_MESSAGE("checkindialog"); + + private String value; + + public String getValue() { + return value; + } + + private ModalItems(String value) { + this.value = value; + } + } + + public enum LeftPanelCanvasItems { + BLOCK_STORAGE("BlockStorage"), + CINDER_VOLUME("CinderVolume"), + COMPUTE("Compute"), + LOAD_BALANCER("LoadBalancer"), + NOVA_SERVER("NovaServer"), + OBJECT_STORAGE("ObjectStorage"), + NEUTRON_PORT("NeutronPort"), + PORT("Port"), DATABASE("Database"), + NETWORK("Network"); + + private String value; + + public String getValue() { + return value; + } + + private LeftPanelCanvasItems(String value) { + this.value = value; + } + } + + public enum LinkMenuItems { + CANCEL_BUTTON("link-menu-button-cancel"), + CONNECT_BUTTON("link-menu-button-connect"), + LINK_ITEM_CAP("link-item-capabilities"), + LINK_ITEM_REQ("link-item-requirements"), + LINK_MENU("link-menu-open"); + + private String value; + + public String getValue() { + return value; + } + + private LinkMenuItems(String value) { + this.value = value; + } + } + + public enum GeneralCanvasItems { + CANVAS("canvas"), + CANVAS_RIGHT_PANEL("w-sdc-designer-sidebar-head"), + DELETE_INSTANCE_BUTTON("e-sdc-small-icon-delete"), + UPDATE_INSTANCE_NAME("e-sdc-small-icon-update"), + INSTANCE_NAME_FIELD("instanceName"); + + private String value; + + public String getValue() { + return value; + } + + private GeneralCanvasItems(String value) { + this.value = value; + } + } + + public enum ResourceMetadataEnum { + RESOURCE_NAME("name"), + DESCRIPTION("description"), + CATEGORY("selectGeneralCategory"), + VENDOR_NAME("vendorName"), + VENDOR_RELEASE("vendorRelease"), + TAGS("i-sdc-tag-input"), + CONTACT_ID("contactId"), + ICON(" iconBox"), + TAGS_TABLE("i-sdc-tag-text"); + private String value; + + public String getValue() { + return value; + } + + private ResourceMetadataEnum(String value) { + this.value = value; + } + } + + public enum GeneralElementsEnum { + CREATE_BUTTON("create/save"), + CHECKIN_BUTTON("check_in"), + CHECKOUT_BUTTON("check_out"), + SUBMIT_FOR_TESTING_BUTTON("submit_for_testing"), + DELETE_VERSION_BUTTON("delete_version"), + REVERT_BUTTON("revert"), + LIFECYCLE_STATE("formlifecyclestate"), + VERSION_HEADER("versionHeader"), + OK("OK"), + UPLOAD_FILE_INPUT("browseButton"); + + private String value; + + public String getValue() { + return value; + } + + private GeneralElementsEnum(String value) { + this.value = value; + } + } + + public enum ArtifactPageEnum { + ADD_DEPLOYMENT_ARTIFACT("add-deployment-artifact-button"), + ADD_INFORMATIONAL_ARTIFACT("add-information-artifact-button"), + DOWNLOAD_ARTIFACT_ENV("download_env_"), + ADD_ANOTHER_ARTIFACT("add-another-artifact-button"), + EDIT_ARTIFACT("edit_"), //upload env file by its label(via deployment artifact view)/displayName(via Canvas) + DELETE_ARTIFACT("delete_"), + DOWNLOAD_ARTIFACT("download_"), + GET_DEPLOYMENT_ARTIFACT_DESCRIPTION("description"), + GET_INFORMATIONAL_ARTIFACT_DESCRIPTION("Description"), + OK("OK"), + TYPE("artifactType_"), + DEPLOYMENT_TIMEOUT("timeout_"), + VERSION("artifactVersion_"), + UUID("artifactUUID_"), + EDIT_PARAMETERS_OF_ARTIFACT("edit-parameters-of-"), + ARTIFACT_NAME("artifactDisplayName_"), + UPLOAD_HEAT_ENV_PARAMETERS("uplaodEnv_"), + VERSION_ENV("artifactEnvVersion_"); + private String value; + + public String getValue() { + return value; + } + + private ArtifactPageEnum(String value) { + this.value = value; + } + } + + public enum PropertiesPageEnum { + + ADD_NEW_PROPERTY("addGrey"), + EDIT_PROPERTY("edit_"), + DELETE_PROPERTY("delete_"), + PROPERTY_NAME("propertyName_"), + PROPERTY_DESCRIPTION("propertyDescription_"), + PROPERTY_TYPE("propertyType_"), + ENTRY_SCHEMA("propertySchema_"), + ADD("Add"), CANCEL("Cancel"), + DONE("Done"), + PROPERTY_ROW("propertyRow"), + SAVE("Save"), + POPUP_FORM("sdc-edit-property-container"); + private String value; + + public String getValue() { + return value; + } + + private PropertiesPageEnum(String value) { + this.value = value; + } + } + + public enum PropertiesPopupEnum { + + PROPERTY_NAME("propertyName"), + PROPERTY_VALUE("defaultvalue"), + PROPERTY_BOOLEAN_VALUE("booleantype"), + PROPERTY_DESCRIPTION("description"), + PROPERTY_TYPE("propertyType"), + ENTRY_SCHEMA("schema-type"), + CANCEL("Cancel"), + SAVE("Save"), + POPUP_FORM("sdc-edit-property-container"), + ADD("Add"), + DONE("Done"), + PROPERTY_RADIO_BUTTON_CONTAINER("propertyRadioButton_"), + RADIO_BUTTON_CLASS("tlv-radio-label"); + private String value; + + public String getValue() { + return value; + } + + private PropertiesPopupEnum(String value) { + this.value = value; + } + } + + public enum AdminPageTabs { + USER_MANAGEMENT("usermanagmenttab"), + CATEGORY_MANAGEMENT("categorymanagmenttab"); + + private String value; + + public String getValue() { + return value; + } + + private AdminPageTabs(String value) { + this.value = value; + } + } + + public enum UserManagementEnum { + + SEARCH_BOX("searchbox"), + NEW_USER_FIELD("newuserId"), + ROLE_SELECT("selectrole"), + CREATE_BUTTON("creategreen"), + CLASS__USER_MANAGEMENT_TABLE("sdc-user-management-table"), + ROW_TABLE("row_"), + FIRST_NAME("firstName_"), + LAST_NAME("lastName__"), + USER_ID("userId_"), + EMAIL("email_"), + ROLE("role_"), + LAST_ACTIVE("lastActive_"), + UPDATE_ROLE("selectRole_"), + UPDATE_USER_BUTTON("updateUser_"), + SAVE_USER("save_"), + DELETE_USER("delete_"), + ; + + + private String value; + + public String getValue() { + return value; + } + + private UserManagementEnum(String value) { + this.value = value; + } + } + + public enum CategoryManagement { + + SERVICE_CATEGORY_HEADER("servicecategoryheader"), + RESOURCE_CATEGORY_HEADER("resourcecategoryheader"), + SERVICE_CATEGORY_LIST("servicecategory"), + RESOURCE_CATEGORY_LIST("resourcecategory"), + NEW_CATEGORY_BUTTON("newcategory"), + NEW_SUB_CATEGORY_BUTTON("newsubcategory"), + NEW_CATEGORY_NAME("i-sdc-form-input"); + + private String value; + + public String getValue() { + return value; + } + + private CategoryManagement(String value) { + this.value = value; + } + } + + + + public enum MainMenuButtons { + HOME_BUTTON("main-menu-button-home"), + CATALOG_BUTTON("main-menu-button-catalog"), + ONBOARD_BUTTON("main-menu-button-onboard"), + SEARCH_BOX("main-menu-input-search"), + REPOSITORY_ICON("repository-icon"); + private String value; + + public String getValue() { + return value; + } + + private MainMenuButtons(String value) { + this.value = value; + } + } + + public enum MainMenuButtonsFromInsideFrame { + HOME_BUTTON("breadcrumbs-button-0"); + private String value; + + public String getValue() { + return value; + } + + private MainMenuButtonsFromInsideFrame(String value) { + this.value = value; + } + } + + public enum MenuOptionsEnum { + EDIT("Edit"), + CHECK_IN("Check in"), + CHECK_OUT("Check out"), + VIEW("View"), + SUBMIT_FOR_TEST("Submit For Test"), + ACCEPT("Accept"), + REJECT("Reject"), + START_TEST("Start test"), + DISTREBUTE("Distribute"); + + private String value; + + public String getValue() { + return value; + } + + private MenuOptionsEnum(String value) { + this.value = value; + } + } + + public enum StepsEnum { + GENERAL("Generalstep"), + ICON("Iconstep"), + DEPLOYMENT_ARTIFACT("Deployment Artifactstep"), + INFORMATION_ARTIFACT("Information Artifactstep"), + PROPERTIES("Propertiesstep"), + COMPOSITION("Compositionstep"), + ACTIVITY_LOG("Activity Logstep"), + DEPLOYMENT_VIEW("Deploymentstep"), + TOSCA_ARTIFACTS("TOSCA Artifactsstep"), + MONITOR("Monitor step"), + MANAGEMENT_WORKFLOW("Management Workflowstep"), + INPUTS("Inputsstep"), + HIERARCHY("Hierarchystep"); + + private String value; + + public String getValue() { + return value; + } + + private StepsEnum(String value) { + this.value = value; + } + } + + public enum ArtifactPopup { + + BROWSE("browseButton"), + ARTIFACT_DESCRIPTION("description"), + ARTIFACT_LABEL("artifactLabel"), + ARTIFACT_TYPE("artifacttype"), + OK("OK"), + SAVE("Save"), + DONE_BUTTON("Done"), + CANCEL_BUTTON("Cancel"), + URL("input[class^='i-sdc-form-input']"), + MODAL_WINDOW("sdc-add-artifact"); + + private String value; + + public String getValue() { + return value; + } + + private ArtifactPopup(String value) { + this.value = value; + } + } + + public enum ServiceMetadataEnum { + SERVICE_NAME("name"), DESCRIPTION("description"), CATEGORY("selectGeneralCategory"), PROJECT_CODE("projectCode"), TAGS("i-sdc-tag-input"), CONTACT_ID("contactId"), ICON(" iconBox"); + + private String value; + + public String getValue() { + return value; + } + + private ServiceMetadataEnum(String value) { + this.value = value; + } + } + + public enum ProductMetadataEnum { + PRODUCT_NAME("name"), + FULL_NAME("fullName"), + DESCRIPTION("description"), + PROJECT_CODE("projectCode"), + TAGS("i-sdc-tag-input"), + ATT_CONTACT("attContact"), + ICON(" iconBox"); + + private String value; + + public String getValue() { + return value; + } + + private ProductMetadataEnum(String value) { + this.value = value; + } + } + + public enum DashboardCardEnum { + ASSET_TYPE("asset-type"), LIFECYCLE_STATE("span[class^='w-sdc-dashboard-card-info-lifecycleState']"), + INFO_NAME("div.sdc-tile-content-info-item-name"), + VERSION("div[class^='w-sdc-dashboard-card-info-user']"), + DASHBOARD_CARD("div[class^='w-sdc-dashboard-card ']"), + ASSET_TYPE_CSS("span[data-tests-id='asset-type']"); + + private String value; + + public String getValue() { + return value; + } + + private DashboardCardEnum(String value) { + this.value = value; + } + } + + public enum CatalogPageLeftPanelCategoryCheckbox { + GENERIC_CHECKBOX("span[data-tests-id='checkbox-resourcenewcategory.generic']"), + NETWORK_L2_3("span[data-tests-id='checkbox-resourcenewcategory.networkl2-3']"), + NETWORK_L4_PLUS("span[data-tests-id='checkbox-resourcenewcategory.networkl4+']"), + NETWORK_CONNECTIVITY("span[data-tests-id='checkbox-resourcenewcategory.networkconnectivity']"), + APPLICATION_L4_PLUS("span[data-tests-id='checkbox-resourcenewcategory.applicationl4+']"), + DCAE("span[data-tests-id='checkbox-resourcenewcategory.dcaecomponent']"); + + private String value; + + public String getValue() { + return value; + } + + private CatalogPageLeftPanelCategoryCheckbox(String value) { + this.value = value; + } + } + + public enum CatalogPageLeftPanelFilterTitle { + TYPE("span[data-tests-id='typeFilterTitle']"), + CATEGORIES("span[data-tests-id='categoriesFilterTitle']"), + STATUS("span[data-tests-id='statusFilterTitle']"); + + private String value; + + public String getValue() { + return value; + } + + private CatalogPageLeftPanelFilterTitle(String value) { + this.value = value; + } + } + + public enum CatalogPageLeftPanelSubCategoryCheckbox { + COMMON_NETWORK_RESOURCES("span[data-tests-id='checkbox-resourcenewcategory.networkl4+.commonnetworkresources']"), + ROUTER("span[data-tests-id='checkbox-resourcenewcategory.networkl2-3.router']"), + WAN_CONNECTORS("span[data-tests-id='checkbox-resourcenewcategory.networkl2-3.wanconnectors']"), + LAN_CONNECTORS("span[data-tests-id='checkbox-resourcenewcategory.networkl2-3.lanconnectors']"), + INFRASTRUCTERE_NETWORKl2_3("span[data-tests-id='checkbox-resourcenewcategory.networkl2-3.infrastructure']"), + GATEWAY("span[data-tests-id='checkbox-resourcenewcategory.networkl2-3.gateway']"), + NETWORK_ELEMENTS("span[data-tests-id='checkbox-resourcenewcategory.generic.networkelements']"), + ABSTRACT("span[data-tests-id='checkbox-resourcenewcategory.generic.abstract']"), + RULES("span[data-tests-id='checkbox-resourcenewcategory.generic.rules']"), + DATABASE("span[data-tests-id='checkbox-resourcenewcategory.generic.database']"), + INFRASTRUCTERE_GENERIC("span[data-tests-id='checkbox-resourcenewcategory.generic.infrastructure']"), + VIRTUAL_LINKS("span[data-tests-id='checkbox-resourcenewcategory.networkconnectivity.virtuallinks']"), + CONNECTION_POINTS("span[data-tests-id='checkbox-resourcenewcategory.networkconnectivity.connectionpoints']"), + APPLICATION_SERVER("span[data-tests-id='checkbox-resourcenewcategory.applicationl4+.applicationserver']"), + CALL_CONTROL("span[data-tests-id='checkbox-resourcenewcategory.applicationl4+.callcontrol']"), + MEDIASERVERS("span[data-tests-id='checkbox-resourcenewcategory.applicationl4+.mediaservers']"), + WEBSERVER("span[data-tests-id='checkbox-resourcenewcategory.applicationl4+.webserver']"), + LOAD_BALANCER("span[data-tests-id='checkbox-resourcenewcategory.applicationl4+.loadbalancer']"), + BORDER_ELEMENT("span[data-tests-id='checkbox-resourcenewcategory.applicationl4+.borderelement']"), + DATABASE_APPLIVATION_L4_PLUS("span[data-tests-id='checkbox-resourcenewcategory.applicationl4+.database']"), + FIREWALL("span[data-tests-id='checkbox-resourcenewcategory.applicationl4+.firewall']"), + DATABASE_DCAE("span[data-tests-id='checkbox-resourcenewcategory.dcaecomponent.database']"), + POLICY("span[data-tests-id='checkbox-resourcenewcategory.dcaecomponent.policy']"), + MICROSERVICE("span[data-tests-id='checkbox-resourcenewcategory.dcaecomponent.microservice']"), + SOURCE("span[data-tests-id='checkbox-resourcenewcategory.dcaecomponent.source']"), + COLLECTOR("span[data-tests-id='checkbox-resourcenewcategory.dcaecomponent.collector']"), + UTILITY("span[data-tests-id='checkbox-resourcenewcategory.dcaecomponent.utility']"), + ANALYTICS("span[data-tests-id='checkbox-resourcenewcategory.dcaecomponent.analytics']"); + + private String value; + + public String getValue() { + return value; + } + + private CatalogPageLeftPanelSubCategoryCheckbox(String value) { + this.value = value; + } + } + + public enum CompositionScreenEnum { + + CHANGE_VERSION("changeVersion", Arrays.asList()), + DEPLOYMENT_ARTIFACT_TAB("deployment-artifact-tab", Arrays.asList("Deployment Artifacts")), + ADD_ARTIFACT("add_Artifact_Button", Arrays.asList()), + SEARCH_ASSET("searchAsset", Arrays.asList()), + PROPERTIES_AND_ATTRIBUTES_TAB("properties-and-attributes-tab",Arrays.asList()), + MENU_INPUTS("sub-menu-button-inputs",Arrays.asList()), + MENU_TRIANGLE_DROPDOWN("triangle-dropdown", Arrays.asList()), + ARTIFACTS_LIST("artifactName", Arrays.asList()), + INFORMATION_ARTIFACTS("button[tooltip-content='Information Artifacts']", Arrays.asList("Informational Artifacts")), + API("button[tooltip-content='API']", Arrays.asList("API Artifacts")), + INFORMATION("button[tooltip-content='Information']", Arrays.asList("General Info", "Additional Information", "Tags")), + COMPOSITION("button[tooltip-content='Composition']", Arrays.asList("Composition")), + INPUTS("button[tooltip-content='Inputs']", Arrays.asList("")), + REQUIREMENTS_AND_CAPABILITIES("button[tooltip-content='Requirements and Capabilities']", Arrays.asList()), + INFORMATION_TAB("information-tab", Arrays.asList()), + CUSTOMIZATION_UUID("rightTab_customizationModuleUUID", Arrays.asList()); + + private String value; + private List title; + + public String getValue() { + return value; + } + + public List getTitle() { + return title; + } + + private CompositionScreenEnum(String value, List title) { + this.value = value; + this.title = title; + } + } + + public enum ToscaArtifactsScreenEnum { + + TOSCA_MODEL("download-Tosca Model"), + TOSCA_TEMPLATE("download-Tosca Template"), + ARTIFACT_VERSION("version-"), + ARTIFACT_NAME("name-"), + ARTIFACT_TYPE("type-"), + ARTIFACT_DETAILS("details-"), + DOWNLOAD_ARTIFACT("download-"), + DOWNLOAD_CSAR("download-Tosca Model"); + + private String value; + + public String getValue() { + return value; + } + + private ToscaArtifactsScreenEnum(String value) { + this.value = value; + } + } + + public enum InformationalArtifactsService { + AFFINITY_RULES("artifact_Display_Name-Affinity Rules"), + CONTROL_LOOP_FUNCTIONS("artifact_Display_Name-Control Loop Functions"), + DEPLOYMENT_VOTING_RECORD("artifact_Display_Name-Deployment Voting Record"), + DIMENSIONING_INFO("artifact_Display_Name-Dimensioning Info"), + DISTRIBUTION_INSTRUCTION("artifact_Display_Name-Distribution Instructions"), + ENGINEERING_RULES("artifact_Display_Name-Engineering Rules (ERD)"), + OPERATIONAL_POLICES("artifact_Display_Name-Operational Policies"), + SERVICE_ARTIFACT_PLAN("artifact_Display_Name-Service Artifact Plan"), + SERVICE_QUESTIONNAIRE("artifact_Display_Name-Service Questionnaire"), + SERVICE_SECURITY_TEMPLATE("artifact_Display_Name-Service Security Template"), + SERVICE_SPECIFIC_POLICIES("artifact_Display_Name-Service-specific Policies"), + SUMMARY_OF_IMPACTS_TO_ECOMP("artifact_Display_Name-Summary of impacts to ECOMP elements,OSSs, BSSs"), + TD_CERTIFICATION_TEST_RESULTS("artifact_Display_Name-TD Certification Test Results"); + + private String value; + + public String getValue() { + return value; + } + + private InformationalArtifactsService(String value) { + this.value = value; + } + } + + public enum APIArtifactsService { + + CONFIGURATION("artifact_Display_Name-Configuration"), + INSTANTIATION("artifact_Display_Name-Instantiation"), + LOGGING("artifact_Display_Name-Logging"), + MONITORING("artifact_Display_Name-Monitoring"), + REPORTING("artifact_Display_Name-Reporting"), + TESTING("artifact_Display_Name-Testing"); + + private String value; + + public String getValue() { + return value; + } + + private APIArtifactsService(String value) { + this.value = value; + } + } + + public enum DeploymentArtifactCompositionRightMenu { + ARTIFACT_NAME("artifactName-"), + ARTIFACT_DISPLAY_NAME("artifact_Display_Name-"), + DOWNLOAD("download_"), + DELETE("delete_"), + ADD_ARTIFACT_BUTTON("add_Artifact_Button"), + EDIT_PARAMETERS_OF_ARTIFACT("edit-parameters-of-"), + ARTIFACT_ITEM("artifact-item-"), + ARTIFACT_ENV("heat_env_"); + + private String value; + + public String getValue() { + return value; + } + + private DeploymentArtifactCompositionRightMenu(String value) { + this.value = value; + } + + } + + public enum InputsScreenService { + ADD_SELECTED_INPUTS_BTN("add-inputs-to-service-button"), + VF_INSTANCE_ROWS("expand-collapse[expanded-selector^='.vf-instance-list.']"), + VF_INSTANCE_ROW_NAME("span[class^='title-text']"), + VF_INSTANCE_INPUTS("div[class^='vf-instance-list ']"), + VF_INSTANCE_INPUT("div[class^='input-row ng-scope']"), + VF_INSTNCE_PROPERTY_NAME("div[class^='title-text']"), + INPUT_CHECKBOX("span[class^='tlv-checkbox-label']"), + SERVICE_INPUT_ROW("div[class^='service-input-row input-row']"), + DELETE_INPUT_BTN("span[class$='remove-input-icon']"), + RESOURCE_INSTANCE_PROPERTY_NAME("propertyName_"), + RESOURCE_INSTANCE_PROPERTY_TYPE("propertyType_"), + RESOURCE_INSTANCE_PROPERTY_CHECKBOX("propertyCheckbox_"), + SERVICE_INPUTS_DELETE_BUTTON("deleteInput_") + ; + + private String value; + + public String getValue() { + return value; + } + + private InputsScreenService(String value) { + this.value = value; + } + + } + + public enum DeploymentScreen { + MODULES("span[class^='expand-collapse-title-text']"), + MEMBERS("div[class^='expand-collapse-sub-title']"), + PROPERTIES("list-of-Properties"), + ARTIFACTS("list-of-Artifacts"), + BUTTON_PROPERTIES("div[data-tests-id='list-of-Properties'] span[class^='hand']"), + BUTTON_ARTIFACTS("div[data-tests-id='list-of-Artifacts'] span[class^='hand']"), + PROPERTY_NAMES("div[data-tests-id='selected-module-property-name'] span"), + PROPERTY_TYPES("selected-module-property-type"), + PROPERTY_SCHEMA_TYPE("selected-module-property-schema-type"), + ARTIFACT_NAME("selected-module-artifact-name"), + ARTIFACT_UUID("selected-module-artifact-uuid"), + ARTIFACT_VERSION("selected-module-artifact-version"), + PENCIL_ICON("edit-name-popover-icon"), + MODULE_NAME("selected-module-name"), + MODULE_ID("selected-module-group-uuid"), + RESOURCE_NAME_ON_POPOVER("popover-vfinstance-name"), + MODULE_NAME_ON_POPOVER("popover-module-name"), + NAME_INPUT("popover-heat-name"), + SAVE("popover-save-button"), + CANCEL("popover-close-button"), + X_BUTTON("popover-x-button"); + + private String value; + + public String getValue() { + return value; + } + + private DeploymentScreen(String value) { + this.value = value; + } + } + + public enum ImportVfRepository { + SEARCH("onboarding-search"), + IMPORT_VSP("import-csar"), + DOWNLOAD_CSAR("download-csar"), + UPDATE_VSP("update-csar"); + + private String value; + + public String getValue() { + return value; + } + + private ImportVfRepository(String value) { + this.value = value; + } + } + + public enum EnvParameterView { + SEARCH_ENV_PARAM_NAME("search-env-param-name"), + ENV_CURRENT_VALUE("value-field-of-"),//value-field-of-oam_volume_name_0 - parameter name + ENV_DEFAULT_VALUE("default-value-of-");// default-value-of-vnf_name + + private String value; + + public String getValue() { + return value; + } + + private EnvParameterView(String value) { + this.value = value; + } + } + + +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/LocalLoginFieldsIds.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/LocalLoginFieldsIds.java new file mode 100644 index 000000000..a3ede39cb --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/LocalLoginFieldsIds.java @@ -0,0 +1,30 @@ +package org.onap.sdc.ci.tests.datatypes; + +public class LocalLoginFieldsIds { + + private String userIdFieldName; + private String passwordFieldName; + + + public LocalLoginFieldsIds(String userIdFieldName, String passwordFieldName) { + super(); + this.userIdFieldName = userIdFieldName; + this.passwordFieldName = passwordFieldName; + } + + + public String getUserIdFieldName() { + return userIdFieldName; + } + public void setUserIdFieldName(String userIdFieldName) { + this.userIdFieldName = userIdFieldName; + } + public String getPasswordFieldName() { + return passwordFieldName; + } + public void setPasswordFieldName(String passwordFieldName) { + this.passwordFieldName = passwordFieldName; + } + + +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/PropertyHeatMetaDefinition.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/PropertyHeatMetaDefinition.java new file mode 100644 index 000000000..a39dffc13 --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/PropertyHeatMetaDefinition.java @@ -0,0 +1,63 @@ +/*- + * ============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.onap.sdc.ci.tests.datatypes; + +public class PropertyHeatMetaDefinition { + + String name; + boolean value; + + public PropertyHeatMetaDefinition() { + super(); + } + + + + public String getName() { + return name; + } + + + + public void setName(String name) { + this.name = name; + } + + + + public boolean getValue() { + return value; + } + + + + public void setValue(boolean value) { + this.value = value; + } + + + + @Override + public String toString() { + return "PropertyHeatMetaDefinition [name=" + name + ", value=" + value + "]"; + } + +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/ResourceAssetStructure.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/ResourceAssetStructure.java new file mode 100644 index 000000000..3fef99183 --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/ResourceAssetStructure.java @@ -0,0 +1,76 @@ +/*- + * ============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.onap.sdc.ci.tests.datatypes; + +public class ResourceAssetStructure extends AssetStructure { + + private String subCategory; + private String resourceType; + protected String lastUpdaterFullName; + protected String toscaResourceName; + + public ResourceAssetStructure() { + super(); + } + + public ResourceAssetStructure(String uuid, String invariantUUID, String name, String version, String toscaModelURL, + String category, String lifecycleState, String lastUpdaterUserId) { + super(uuid, invariantUUID, name, version, toscaModelURL, category, lifecycleState, lastUpdaterUserId); + } + + @Override + public String toString() { + return "ResourceAssetStructure [subCategory=" + subCategory + ", resourceType=" + resourceType + "]"; + } + + public String getLastUpdaterFullName() { + return lastUpdaterFullName; + } + + public void setLastUpdaterFullName(String lastUpdaterFullName) { + this.lastUpdaterFullName = lastUpdaterFullName; + } + + public String getToscaResourceName() { + return toscaResourceName; + } + + public void setToscaResourceName(String toscaResourceName) { + this.toscaResourceName = toscaResourceName; + } + + public String getSubCategory() { + return subCategory; + } + + public void setSubCategory(String subCategory) { + this.subCategory = subCategory; + } + + public String getResourceType() { + return resourceType; + } + + public void setResourceType(String resourceType) { + this.resourceType = resourceType; + } + +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/ResourceDetailedAssetStructure.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/ResourceDetailedAssetStructure.java new file mode 100644 index 000000000..7d5914b00 --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/ResourceDetailedAssetStructure.java @@ -0,0 +1,71 @@ +/*- + * ============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.onap.sdc.ci.tests.datatypes; + +import java.util.List; + +public class ResourceDetailedAssetStructure extends ResourceAssetStructure { + + private List resources; + private List artifacts; + + public ResourceDetailedAssetStructure() { + super(); + } + + public ResourceDetailedAssetStructure(String lastUpdaterFullName, String toscaResourceName, + List resources, List artifacts) { + super(); + this.lastUpdaterFullName = lastUpdaterFullName; + this.toscaResourceName = toscaResourceName; + this.resources = resources; + this.artifacts = artifacts; + } + + public List getResources() { + return resources; + } + + public void setResources(List resources) { + this.resources = resources; + } + + public List getArtifacts() { + return artifacts; + } + + public void setArtifacts(List artifacts) { + this.artifacts = artifacts; + } + + @Override + public String toString() { + return "ResourceDetailedAssetStructure [lastUpdaterFullName=" + lastUpdaterFullName + ", toscaResourceName=" + + toscaResourceName + ", resources=" + resources + ", artifacts=" + artifacts + ", toString()=" + + super.toString() + ", getSubCategory()=" + getSubCategory() + ", getResourceType()=" + + getResourceType() + ", getUuid()=" + getUuid() + ", getInvariantUUID()=" + getInvariantUUID() + + ", getName()=" + getName() + ", getVersion()=" + getVersion() + ", getToscaModelURL()=" + + getToscaModelURL() + ", getCategory()=" + getCategory() + ", getLifecycleState()=" + + getLifecycleState() + ", getLastUpdaterUserId()=" + getLastUpdaterUserId() + ", getClass()=" + + getClass() + ", hashCode()=" + hashCode() + "]"; + } + +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/ResourceExternalReqDetails.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/ResourceExternalReqDetails.java new file mode 100644 index 000000000..f6d354c1e --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/ResourceExternalReqDetails.java @@ -0,0 +1,104 @@ +/*- + * ============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.onap.sdc.ci.tests.datatypes; + +import java.util.List; + +import org.onap.sdc.ci.tests.devObjects.ResourceTypeEnum; + +public class ResourceExternalReqDetails extends ComponentReqDetails { + String vendorName; + String vendorRelease; + String category; + String subcategory; + + private String resourceType = ResourceTypeEnum.VFC.toString(); // Default + // value + public ResourceExternalReqDetails() { + super(); + } + + + public ResourceExternalReqDetails(String resourceName, String description, List tags, + String vendorName, String vendorRelease, String contactId, String icon, + String resourceType, String resourceCategory, String resourceSubcategory) { + super(); + this.resourceType = resourceType; + this.name = resourceName; + this.description = description; + this.tags = tags; + this.vendorName = vendorName; + this.vendorRelease = vendorRelease; + this.contactId = contactId; + this.icon = icon; + this.category = resourceCategory; + this.subcategory = resourceSubcategory; + } + + public String getVendorName() { + return vendorName; + } + + public void setVendorName(String vendorName) { + this.vendorName = vendorName; + } + + public String getVendorRelease() { + return vendorRelease; + } + + public void setVendorRelease(String vendorRelease) { + this.vendorRelease = vendorRelease; + } + + public String getResourceType() { + return resourceType; + } + + public void setResourceType(String resourceType) { + this.resourceType = resourceType; + } + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + public String getSubcategory() { + return subcategory; + } + + public void setSubcategory(String subcategory) { + this.subcategory = subcategory; + } + + + @Override + public String toString() { + return "ResourceReqDetails [name=" + name + ", vendorName=" + vendorName + + ", vendorRelease=" + vendorRelease + ", version=" + version + + ", resourceType=" + resourceType + ", category=" + category + ", subcategory=" + subcategory +"]"; + } + +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/ResourceInstanceAssetStructure.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/ResourceInstanceAssetStructure.java new file mode 100644 index 000000000..5019d19b7 --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/ResourceInstanceAssetStructure.java @@ -0,0 +1,116 @@ +/*- + * ============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.onap.sdc.ci.tests.datatypes; + +import java.util.List; + +public class ResourceInstanceAssetStructure { + + String resourceInstanceName; + String resourceName; + String resourceInvariantUUID; + String resourceVersion; + String resoucreType; + String resourceUUID; + List artifacts; + + public ResourceInstanceAssetStructure() { + super(); + } + + public ResourceInstanceAssetStructure(String resourceInstanceName, String resourceName, + String resourceInvariantUUID, String resourceVersion, String resoucreType, String resourceUUID, + List artifacts) { + super(); + this.resourceInstanceName = resourceInstanceName; + this.resourceName = resourceName; + this.resourceInvariantUUID = resourceInvariantUUID; + this.resourceVersion = resourceVersion; + this.resoucreType = resoucreType; + this.resourceUUID = resourceUUID; + this.artifacts = artifacts; + } + + public String getResourceInstanceName() { + return resourceInstanceName; + } + + public void setResourceInstanceName(String resourceInstanceName) { + this.resourceInstanceName = resourceInstanceName; + } + + public String getResourceName() { + return resourceName; + } + + public void setResourceName(String resourceName) { + this.resourceName = resourceName; + } + + public String getResourceInvariantUUID() { + return resourceInvariantUUID; + } + + public void setResourceInvariantUUID(String resourceInvariantUUID) { + this.resourceInvariantUUID = resourceInvariantUUID; + } + + public String getResourceVersion() { + return resourceVersion; + } + + public void setResourceVersion(String resourceVersion) { + this.resourceVersion = resourceVersion; + } + + public String getResoucreType() { + return resoucreType; + } + + public void setResoucreType(String resoucreType) { + this.resoucreType = resoucreType; + } + + public String getResourceUUID() { + return resourceUUID; + } + + public void setResourceUUID(String resourceUUID) { + this.resourceUUID = resourceUUID; + } + + public List getArtifacts() { + return artifacts; + } + + public void setArtifacts(List artifacts) { + this.artifacts = artifacts; + } + + @Override + public String toString() { + return "ResourceInstanceAssetStructure [resourceInstanceName=" + resourceInstanceName + ", resourceName=" + + resourceName + ", resourceInvariantUUID=" + resourceInvariantUUID + ", resourceVersion=" + + resourceVersion + ", resoucreType=" + resoucreType + ", resourceUUID=" + resourceUUID + ", artifacts=" + + artifacts + "]"; + } + +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/ResourceReqDetails.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/ResourceReqDetails.java new file mode 100644 index 000000000..7a3dbd469 --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/ResourceReqDetails.java @@ -0,0 +1,194 @@ +/*- + * ============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.onap.sdc.ci.tests.datatypes; + +import java.util.List; + +import org.onap.sdc.ci.tests.devObjects.ResourceTypeEnum; + +public class ResourceReqDetails extends ComponentReqDetails { + List derivedFrom; + String vendorName; + String vendorRelease; + + // Unsettable/unupdatable fields + + Boolean isAbstract; + Boolean isHighestVersion; + String cost; + String licenseType; + String toscaResourceName; + + private String resourceType = ResourceTypeEnum.VFC.toString(); // Default + // value + + public ResourceReqDetails() { + super(); + } + + + public ResourceReqDetails(String resourceName, String description, List tags, String category, + List derivedFrom, String vendorName, String vendorRelease, String contactId, String icon) { + this(resourceName, description, tags, category, derivedFrom, vendorName, vendorRelease, contactId, icon, + ResourceTypeEnum.VFC.toString()); + } + + // new + public ResourceReqDetails(String resourceName, String description, List tags, String category, + List derivedFrom, String vendorName, String vendorRelease, String contactId, String icon, + String resourceType) { + super(); + this.resourceType = resourceType; + this.name = resourceName; + this.description = description; + this.tags = tags; + // this.category = category; + this.derivedFrom = derivedFrom; + this.vendorName = vendorName; + this.vendorRelease = vendorRelease; + this.contactId = contactId; + this.icon = icon; + if (category != null) { + String[] arr = category.split("/"); + if (arr.length == 2) { + addCategoryChain(arr[0], arr[1]); + } + } + this.toscaResourceName = resourceName; + } + + public ResourceReqDetails(ResourceReqDetails originalResource, String version) { + super(); + this.name = originalResource.getName(); + this.description = originalResource.getDescription(); + this.tags = originalResource.getTags(); + // this.category = originalResource.getCategory(); + this.derivedFrom = originalResource.getDerivedFrom(); + this.vendorName = originalResource.getVendorName(); + this.vendorRelease = originalResource.getVendorRelease(); + this.contactId = originalResource.getContactId(); + this.icon = originalResource.getIcon(); + this.version = version; + this.uniqueId = originalResource.getUniqueId(); + this.categories = originalResource.getCategories(); + this.toscaResourceName = originalResource.getToscaResourceName(); + this.resourceType = originalResource.getResourceType(); + } + + public ResourceReqDetails(String resourceName, List derivedFrom, String vendorName, String vendorRelease, + String resourceVersion, Boolean isAbstract, Boolean isHighestVersion, String cost, String licenseType, + String resourceType) { + super(); + this.name = resourceName; + this.derivedFrom = derivedFrom; + this.vendorName = vendorName; + this.vendorRelease = vendorRelease; + this.version = resourceVersion; + this.isAbstract = isAbstract; + this.isHighestVersion = isHighestVersion; + this.cost = cost; + this.licenseType = licenseType; + this.resourceType = resourceType; + this.toscaResourceName = resourceName; + } + + public String getToscaResourceName() { + return toscaResourceName; + } + + public void setToscaResourceName(String toscaResourceName) { + this.toscaResourceName = toscaResourceName; + } + + public List getDerivedFrom() { + return derivedFrom; + } + + public void setDerivedFrom(List derivedFrom) { + this.derivedFrom = derivedFrom; + } + + public String getVendorName() { + return vendorName; + } + + public void setVendorName(String vendorName) { + this.vendorName = vendorName; + } + + public String getVendorRelease() { + return vendorRelease; + } + + public void setVendorRelease(String vendorRelease) { + this.vendorRelease = vendorRelease; + } + + public String getCost() { + return cost; + } + + public void setCost(String cost) { + this.cost = cost; + } + + public String getLicenseType() { + return licenseType; + } + + public void setLicenseType(String licenseType) { + this.licenseType = licenseType; + } + + // Unupdatable fields - to check that they are not updated + public void setIsAbstract(Boolean isAbstract) { + this.isAbstract = isAbstract; + } + + public void setIsHighestVersion(Boolean isHighestVersion) { + this.isHighestVersion = isHighestVersion; + } + + public Boolean getIsAbstract() { + return isAbstract; + } + + public Boolean getIsHighestVersion() { + return isHighestVersion; + } + + public String getResourceType() { + return resourceType; + } + + public void setResourceType(String resourceType) { + this.resourceType = resourceType; + } + + @Override + public String toString() { + return "ResourceReqDetails [name=" + name + ", derivedFrom=" + derivedFrom + ", vendorName=" + vendorName + + ", vendorRelease=" + vendorRelease + ", version=" + version + ", isAbstract=" + isAbstract + + ", isHighestVersion=" + isHighestVersion + ", cost=" + cost + ", licenseType=" + licenseType + + ", resourceType=" + resourceType + "]"; + } + +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/ResourceRespJavaObject.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/ResourceRespJavaObject.java new file mode 100644 index 000000000..525ca794c --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/ResourceRespJavaObject.java @@ -0,0 +1,369 @@ +/*- + * ============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.onap.sdc.ci.tests.datatypes; + +import java.util.List; + +import org.onap.sdc.ci.tests.devObjects.CategoryDefinition; + +public class ResourceRespJavaObject { + String uniqueId; + String name; + String version; + String creatorUserId; + String creatorFullName; + String lastUpdaterUserId; + String lastUpdaterFullName; + String description; + String icon; + List tags; + String isHighestVersion; + String creationDate; + String lastUpdateDate; + // String category; + String lifecycleState; + List derivedFrom; + String vendorName; + String vendorRelease; + String contactId; + String abstractt; + String highestVersion; + List artifacts; + List interfaces; + String uuid; + String cost; + String licenseType; + String resourceType; + List categories; + + public String getResourceType() { + return resourceType; + } + + public void setResourceType(String resourceType) { + this.resourceType = resourceType; + } + + public ResourceRespJavaObject(String uniqueId, String resourceName, String resourceVersion, String creatorUserId, + String creatorFullName, String lastUpdaterUserId, String lastUpdaterFullName, String description, + String icon, List tags, String isHighestVersion, String creationDate, String lastUpdateDate, + String category, String lifecycleState, List derivedFrom, String vendorName, String vendorRelease, + String contactId, String abstractt, String highestVersion, List artifacts, List interfaces, + String uuid, String cost, String licenseType, String resourceType) { + super(); + this.uniqueId = uniqueId; + this.name = resourceName; + this.version = resourceVersion; + this.creatorUserId = creatorUserId; + this.creatorFullName = creatorFullName; + this.lastUpdaterUserId = lastUpdaterUserId; + this.lastUpdaterFullName = lastUpdaterFullName; + this.description = description; + this.icon = icon; + this.tags = tags; + this.isHighestVersion = isHighestVersion; + this.creationDate = creationDate; + this.lastUpdateDate = lastUpdateDate; + // this.category = category; + this.lifecycleState = lifecycleState; + this.derivedFrom = derivedFrom; + this.vendorName = vendorName; + this.vendorRelease = vendorRelease; + this.contactId = contactId; + this.abstractt = abstractt; + this.highestVersion = highestVersion; + this.artifacts = artifacts; + this.interfaces = interfaces; + this.uuid = uuid; + this.cost = cost; + this.licenseType = licenseType; + this.resourceType = resourceType; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public String getCost() { + return cost; + } + + public void setCost(String cost) { + this.cost = cost; + } + + public String getLicenseType() { + return licenseType; + } + + public void setLicenseType(String licenseType) { + this.licenseType = licenseType; + } + + public String getUuid() { + return uuid; + } + + public String setUuid() { + return uuid; + } + + public List getInterfaces() { + return interfaces; + } + + public void setInterfaces(List interfaces) { + this.interfaces = interfaces; + } + + public List getArtifacts() { + return artifacts; + } + + public void setArtifacts(List artifacts) { + this.artifacts = artifacts; + } + + public ResourceRespJavaObject() { + super(); + // TODO Auto-generated constructor stub + } + + // public ResourceRespJavaObject(String uniqueId, String resourceName, + // String resourceVersion, String creatorUserId, + // String creatorFullName, String lastUpdaterUserId, + // String lastUpdaterFullName, String description, String icon, + // List tags, String isHighestVersion, String creationDate, + // String lastUpdateDate, String category, String lifecycleState, + // List derivedFrom, String vendorName, String vendorRelease, + // String contactId, String abstractt, String highestVersion) { + // super(); + // this.uniqueId = uniqueId; + // this.resourceName = resourceName; + // this.resourceVersion = resourceVersion; + // this.creatorUserId = creatorUserId; + // this.creatorFullName = creatorFullName; + // this.lastUpdaterUserId = lastUpdaterUserId; + // this.lastUpdaterFullName = lastUpdaterFullName; + // this.description = description; + // this.icon = icon; + // this.tags = tags; + // this.isHighestVersion = isHighestVersion; + // this.creationDate = creationDate; + // this.lastUpdateDate = lastUpdateDate; + // this.category = category; + // this.lifecycleState = lifecycleState; + // this.derivedFrom = derivedFrom; + // this.vendorName = vendorName; + // this.vendorRelease = vendorRelease; + // this.contactId = contactId; + // this.abstractt = abstractt; + // this.highestVersion = highestVersion; + // } + public String getUniqueId() { + return uniqueId; + } + + public void setUniqueId(String uniqueId) { + this.uniqueId = uniqueId; + } + + public String getName() { + return name; + } + + public void setName(String resourceName) { + this.name = resourceName; + } + + public String getVersion() { + return version; + } + + public void setVersion(String resourceVersion) { + this.version = resourceVersion; + } + + public String getCreatorUserId() { + return creatorUserId; + } + + public void setCreatorUserId(String creatorUserId) { + this.creatorUserId = creatorUserId; + } + + public String getCreatorFullName() { + return creatorFullName; + } + + public void setCreatorFullName(String creatorFullName) { + this.creatorFullName = creatorFullName; + } + + public String getLastUpdaterUserId() { + return lastUpdaterUserId; + } + + public void setLastUpdaterUserId(String lastUpdaterUserId) { + this.lastUpdaterUserId = lastUpdaterUserId; + } + + public String getLastUpdaterFullName() { + return lastUpdaterFullName; + } + + public void setLastUpdaterFullName(String lastUpdaterFullName) { + this.lastUpdaterFullName = lastUpdaterFullName; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getIcon() { + return icon; + } + + public void setIcon(String icon) { + this.icon = icon; + } + + public List getTags() { + return tags; + } + + public void setTags(List tags) { + this.tags = tags; + } + + public String getIsHighestVersion() { + return isHighestVersion; + } + + public void setIsHighestVersion(String isHighestVersion) { + this.isHighestVersion = isHighestVersion; + } + + public String getCreationDate() { + return creationDate; + } + + public void setCreationDate(String creationDate) { + this.creationDate = creationDate; + } + + public String getLastUpdateDate() { + return lastUpdateDate; + } + + public void setLastUpdateDate(String lastUpdateDate) { + this.lastUpdateDate = lastUpdateDate; + } + + // public String getCategory() { + // return category; + // } + // public void setCategory(String category) { + // this.category = category; + // } + public String getLifecycleState() { + return lifecycleState; + } + + public void setLifecycleState(String lifecycleState) { + this.lifecycleState = lifecycleState; + } + + public List getDerivedFrom() { + return derivedFrom; + } + + public void setDerivedFrom(List derivedFrom) { + this.derivedFrom = derivedFrom; + } + + public String getVendorName() { + return vendorName; + } + + public void setVendorName(String vendorName) { + this.vendorName = vendorName; + } + + public String getVendorRelease() { + return vendorRelease; + } + + public void setVendorRelease(String vendorRelease) { + this.vendorRelease = vendorRelease; + } + + public String getContactId() { + return contactId; + } + + public void setContactId(String contactId) { + this.contactId = contactId; + } + + public String getAbstractt() { + return abstractt; + } + + public void setAbstractt(String abstractt) { + this.abstractt = abstractt; + } + + public String getHighestVersion() { + return highestVersion; + } + + public void setHighestVersion(String highestVersion) { + this.highestVersion = highestVersion; + } + + public List getCategories() { + return categories; + } + + public void setCategories(List categories) { + this.categories = categories; + } + + @Override + public String toString() { + return "ResourceRespJavaObject [uniqueId=" + uniqueId + ", resourceName=" + name + ", resourceVersion=" + + version + ", creatorUserId=" + creatorUserId + ", creatorFullName=" + creatorFullName + + ", lastUpdaterUserId=" + lastUpdaterUserId + ", lastUpdaterFullName=" + lastUpdaterFullName + + ", description=" + description + ", icon=" + icon + ", tags=" + tags + ", isHighestVersion=" + + isHighestVersion + ", creationDate=" + creationDate + ", lastUpdateDate=" + lastUpdateDate + + ", lifecycleState=" + lifecycleState + ", derivedFrom=" + derivedFrom + ", vendorName=" + vendorName + + ", vendorRelease=" + vendorRelease + ", contactId=" + contactId + ", abstractt=" + abstractt + + ", highestVersion=" + highestVersion + ", artifacts=" + artifacts + ", interfaces=" + interfaces + + ", uuid=" + uuid + ", cost=" + cost + ", licenseType=" + licenseType + ", resourceType=" + + resourceType + "]"; + } + +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/ServiceAssetStructure.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/ServiceAssetStructure.java new file mode 100644 index 000000000..cfe7addbe --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/ServiceAssetStructure.java @@ -0,0 +1,49 @@ +/*- + * ============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.onap.sdc.ci.tests.datatypes; + +public class ServiceAssetStructure extends AssetStructure { + + private String distributionStatus; + + public ServiceAssetStructure() { + super(); + } + + public ServiceAssetStructure(String uuid, String invariantUUID, String name, String version, String toscaModelURL, + String category, String lifecycleState, String lastUpdaterUserId) { + super(uuid, invariantUUID, name, version, toscaModelURL, category, lifecycleState, lastUpdaterUserId); + } + + @Override + public String toString() { + return "ServiceAssetStructure [distributionStatus=" + distributionStatus + "]"; + } + + public String getDistributionStatus() { + return distributionStatus; + } + + public void setDistributionStatus(String distributionStatus) { + this.distributionStatus = distributionStatus; + } + +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/ServiceDetailedAssetStructure.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/ServiceDetailedAssetStructure.java new file mode 100644 index 000000000..f699aa3f0 --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/ServiceDetailedAssetStructure.java @@ -0,0 +1,78 @@ +/*- + * ============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.onap.sdc.ci.tests.datatypes; + +import java.util.List; + +public class ServiceDetailedAssetStructure extends ServiceAssetStructure { + + String lastUpdaterFullName; + List resources; + List artifacts; + + public ServiceDetailedAssetStructure() { + super(); + } + + public ServiceDetailedAssetStructure(String uuid, String invariantUUID, String name, String version, + String toscaModelURL, String category, String lifecycleState, String lastUpdaterUserId) { + super(uuid, invariantUUID, name, version, toscaModelURL, category, lifecycleState, lastUpdaterUserId); + } + + public ServiceDetailedAssetStructure(String lastUpdaterFullName, List resources, + List artifacts) { + super(); + this.lastUpdaterFullName = lastUpdaterFullName; + this.resources = resources; + this.artifacts = artifacts; + } + + public String getLastUpdaterFullName() { + return lastUpdaterFullName; + } + + public void setLastUpdaterFullName(String lastUpdaterFullName) { + this.lastUpdaterFullName = lastUpdaterFullName; + } + + public List getResources() { + return resources; + } + + public void setResources(List resources) { + this.resources = resources; + } + + public List getArtifacts() { + return artifacts; + } + + public void setArtifacts(List artifacts) { + this.artifacts = artifacts; + } + + @Override + public String toString() { + return "ServiceDetailedAssetStructure [lastUpdaterFullName=" + lastUpdaterFullName + ", resources=" + resources + + ", artifacts=" + artifacts + "]"; + } + +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/ServiceDistributionStatus.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/ServiceDistributionStatus.java new file mode 100644 index 000000000..783e0175d --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/ServiceDistributionStatus.java @@ -0,0 +1,80 @@ +/*- + * ============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.onap.sdc.ci.tests.datatypes; + +public class ServiceDistributionStatus { + + private String distributionID; + private String timestamp; + private String userId; + private String deployementStatus; + + public ServiceDistributionStatus() { + super(); + // TODO Auto-generated constructor stub + } + + public ServiceDistributionStatus(String distributionID, String timestamp, String userId, String deployementStatus) { + super(); + this.distributionID = distributionID; + this.timestamp = timestamp; + this.userId = userId; + this.deployementStatus = deployementStatus; + } + + @Override + public String toString() { + return "ServiceDistributionStatus [distributionID=" + distributionID + ", timestamp=" + timestamp + ", userId=" + userId + ", deployementStatus=" + deployementStatus + "]"; + } + + public String getDistributionID() { + return distributionID; + } + + public void setDistributionID(String distributionID) { + this.distributionID = distributionID; + } + + public String getTimestamp() { + return timestamp; + } + + public void setTimestamp(String timestamp) { + this.timestamp = timestamp; + } + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public String getDeployementStatus() { + return deployementStatus; + } + + public void setDeployementStatus(String deployementStatus) { + this.deployementStatus = deployementStatus; + } + +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/ServiceReqDetails.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/ServiceReqDetails.java new file mode 100644 index 000000000..6dc804987 --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/ServiceReqDetails.java @@ -0,0 +1,74 @@ +/*- + * ============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.onap.sdc.ci.tests.datatypes; + +import java.util.ArrayList; + +import org.onap.sdc.ci.tests.devObjects.CategoryDefinition; + +public class ServiceReqDetails extends ComponentReqDetails { + + public ServiceReqDetails(String serviceName, String category, ArrayList tags, String description, + String contactId, String icon) { + this.name = serviceName; + // this.category = category; + this.tags = tags; + this.description = description; + this.contactId = contactId; + this.icon = icon; + projectCode = "12345"; + CategoryDefinition categoryDefinition = new CategoryDefinition(); + categoryDefinition.setName(category); + categories = new ArrayList<>(); + categories.add(categoryDefinition); + + } + + public ServiceReqDetails() { + contactId = "aa1234"; + projectCode = "12345"; + } + + public ServiceReqDetails(ServiceReqDetails a, String newServiceName) { + a.setName(newServiceName); + } + + @Override + public String toString() { + return "ServiceDetails [name=" + name + ", category=" + getCategory() + ", tags=" + tags + ", description=" + + description + ", contactId=" + contactId + ", icon=" + icon + "]"; + } + + public ServiceReqDetails(ServiceReqDetails aService) { + this(aService.getName(), aService.getCategory(), (ArrayList) aService.getTags(), + aService.getDescription(), aService.getContactId(), aService.getIcon()); + uniqueId = aService.getUniqueId(); + version = aService.getVersion(); + } + + public String getCategory() { + if (categories != null && categories.size() >= 1) { + return categories.get(0).getName(); + } + return null; + } + +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/ServiceRespJavaObject.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/ServiceRespJavaObject.java new file mode 100644 index 000000000..c401c4ec0 --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/ServiceRespJavaObject.java @@ -0,0 +1,267 @@ +/*- + * ============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.onap.sdc.ci.tests.datatypes; + +import java.util.ArrayList; + +public class ServiceRespJavaObject { + + String category; + String creatorUserId; + String creatorFullName; + String lastUpdaterUserId; + String lastUpdaterFullName; + String serviceName; + String version; + String creationDate; + String icon; + String name; + String description; + ArrayList tags; + String uniqueId; + String lastUpdateDate; + String contactId; + String vendorName; + String vendorRelease; + String lifecycleState; + String highestVersion; + ArrayList artifacts; + ArrayList ResourceInstances; + ArrayList ResourceInstancesRelations; + + public ServiceRespJavaObject() { + super(); + // TODO Auto-generated constructor stub + } + + public ServiceRespJavaObject(String category, String creatorUserId, String creatorFullName, + String lastUpdaterUserId, String lastUpdaterFullName, String serviceName, String version, + String creationDate, String icon, String name, String description, ArrayList tags, String uniqueId, + String lastUpdateDate, String contactId, String vendorName, String vendorRelease, String lifecycleState, + String highestVersion, ArrayList artifacts, ArrayList resourceInstances, + ArrayList resourceInstancesRelations) { + super(); + this.category = category; + this.creatorUserId = creatorUserId; + this.creatorFullName = creatorFullName; + this.lastUpdaterUserId = lastUpdaterUserId; + this.lastUpdaterFullName = lastUpdaterFullName; + this.serviceName = serviceName; + this.version = version; + this.creationDate = creationDate; + this.icon = icon; + this.name = name; + this.description = description; + this.tags = tags; + this.uniqueId = uniqueId; + this.lastUpdateDate = lastUpdateDate; + this.contactId = contactId; + this.vendorName = vendorName; + this.vendorRelease = vendorRelease; + this.lifecycleState = lifecycleState; + this.highestVersion = highestVersion; + this.artifacts = artifacts; + ResourceInstances = resourceInstances; + ResourceInstancesRelations = resourceInstancesRelations; + } + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + public String getCreatorUserId() { + return creatorUserId; + } + + public void setCreatorUserId(String creatorUserId) { + this.creatorUserId = creatorUserId; + } + + public String getCreatorFullName() { + return creatorFullName; + } + + public void setCreatorFullName(String creatorFullName) { + this.creatorFullName = creatorFullName; + } + + public String getLastUpdaterUserId() { + return lastUpdaterUserId; + } + + public void setLastUpdaterUserId(String lastUpdaterUserId) { + this.lastUpdaterUserId = lastUpdaterUserId; + } + + public String getLastUpdaterFullName() { + return lastUpdaterFullName; + } + + public void setLastUpdaterFullName(String lastUpdaterFullName) { + this.lastUpdaterFullName = lastUpdaterFullName; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getCreationDate() { + return creationDate; + } + + public void setCreationDate(String creationDate) { + this.creationDate = creationDate; + } + + public String getIcon() { + return icon; + } + + public void setIcon(String icon) { + this.icon = icon; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public ArrayList getTags() { + return tags; + } + + public void setTags(ArrayList tags) { + this.tags = tags; + } + + public String getUniqueId() { + return uniqueId; + } + + public void setUniqueId(String uniqueId) { + this.uniqueId = uniqueId; + } + + public String getLastUpdateDate() { + return lastUpdateDate; + } + + public void setLastUpdateDate(String lastUpdateDate) { + this.lastUpdateDate = lastUpdateDate; + } + + public String getContactId() { + return contactId; + } + + public void setContactId(String contactId) { + this.contactId = contactId; + } + + public String getVendorName() { + return vendorName; + } + + public void setVendorName(String vendorName) { + this.vendorName = vendorName; + } + + public String getVendorRelease() { + return vendorRelease; + } + + public void setVendorRelease(String vendorRelease) { + this.vendorRelease = vendorRelease; + } + + public String getLifecycleState() { + return lifecycleState; + } + + public void setLifecycleState(String lifecycleState) { + this.lifecycleState = lifecycleState; + } + + public String getHighestVersion() { + return highestVersion; + } + + public void setHighestVersion(String highest) { + this.highestVersion = highest; + } + + public ArrayList getArtifacts() { + return artifacts; + } + + public void setArtifacts(ArrayList artifacts) { + this.artifacts = artifacts; + } + + public ArrayList getResourceInstances() { + return ResourceInstances; + } + + public void setResourceInstances(ArrayList resourceInstances) { + ResourceInstances = resourceInstances; + } + + public ArrayList getResourceInstancesRelations() { + return ResourceInstancesRelations; + } + + public void setResourceInstancesRelations(ArrayList resourceInstancesRelations) { + ResourceInstancesRelations = resourceInstancesRelations; + } + + @Override + public String toString() { + return "ServiceRespJavaObject [category=" + category + ", creatorUserId=" + creatorUserId + ", creatorFullName=" + + creatorFullName + ", lastUpdaterUserId=" + lastUpdaterUserId + ", lastUpdaterFullName=" + + lastUpdaterFullName + ", serviceName=" + serviceName + ", version=" + version + ", creationDate=" + + creationDate + ", icon=" + icon + ", name=" + name + ", description=" + description + ", tags=" + tags + + ", uniqueId=" + uniqueId + ", lastUpdateDate=" + lastUpdateDate + ", contactId=" + contactId + + ", vendorName=" + vendorName + ", vendorRelease=" + vendorRelease + ", lifecycleState=" + + lifecycleState + ", lifecycleState=" + lifecycleState + ", artifacts=" + artifacts + + ", ResourceInstances=" + ResourceInstances + ", ResourceInstancesRelations=" + + ResourceInstancesRelations + "]"; + } + +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/TopMenuButtonsEnum.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/TopMenuButtonsEnum.java new file mode 100644 index 000000000..f688d33b0 --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/TopMenuButtonsEnum.java @@ -0,0 +1,38 @@ +/*- + * ============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.onap.sdc.ci.tests.datatypes; + +public enum TopMenuButtonsEnum { + + HOME("main-menu-button-home"), CATALOG("main-menu-button-catalog"), ON_BOARDING("main-menu-button-onboard"); + + private String value; + private String value2; + + public String getButton() { + return value; + } + + private TopMenuButtonsEnum(String value) { + this.value = value; + } + +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/User.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/User.java new file mode 100644 index 000000000..5201de0f1 --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/User.java @@ -0,0 +1,189 @@ +/*- + * ============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.onap.sdc.ci.tests.datatypes; + +import org.joda.time.DateTime; +import org.joda.time.DateTimeZone; + +public class User { + public static final String FORCE_DELETE_HEADER_FLAG = "FORCE_DELETE"; + + private String firstName; + + private String lastName; + + private String userId; + + private String email; + + private String role; + + private Long lastLoginTime; + + + public User() { + } + + public User(String firstName, String lastName, String userId, String emailAddress, String role, + Long lastLoginTime) { + this.firstName = firstName; + this.lastName = lastName; + this.userId = userId; + this.email = emailAddress; + this.role = role; + this.lastLoginTime = lastLoginTime; + + } + + public void copyData(User other) { + this.firstName = other.getFirstName(); + this.lastName = other.getLastName(); + this.userId = other.getUserId(); + this.email = other.getEmail(); + this.role = other.getRole(); + this.lastLoginTime = other.getLastLoginTime(); + + } + + public User(User aUser) { + this(aUser.getFirstName(), aUser.getLastName(), aUser.getUserId(), aUser.getEmail(), aUser.getRole(), + aUser.getLastLoginTime()); + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getRole() { + return role; + } + + public void setRole(String role) { + this.role = role; + } + + public String getFullName() { + return this.getFirstName() + " " + this.getLastName(); + } + + public void setLastLoginTime() { + DateTime now = new DateTime(DateTimeZone.UTC); + this.lastLoginTime = now.getMillis(); + } + + public void setLastLoginTime(Long time) { + this.lastLoginTime = time; + } + + public Long getLastLoginTime() { + return this.lastLoginTime; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((userId == null) ? 0 : userId.hashCode()); + result = prime * result + ((email == null) ? 0 : email.hashCode()); + result = prime * result + ((firstName == null) ? 0 : firstName.hashCode()); + result = prime * result + ((lastName == null) ? 0 : lastName.hashCode()); + result = prime * result + ((role == null) ? 0 : role.hashCode()); + result = prime * result + ((lastLoginTime == null) ? 0 : lastLoginTime.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + User other = (User) obj; + if (userId == null) { + if (other.userId != null) + return false; + } else if (!userId.equals(other.userId)) + return false; + if (email == null) { + if (other.email != null) + return false; + } else if (!email.equals(other.email)) + return false; + if (firstName == null) { + if (other.firstName != null) + return false; + } else if (!firstName.equals(other.firstName)) + return false; + if (lastName == null) { + if (other.lastName != null) + return false; + } else if (!lastName.equals(other.lastName)) + return false; + if (role == null) { + if (other.role != null) + return false; + } else if (!role.equals(other.role)) + return false; + if (lastLoginTime == null) { + if (other.lastLoginTime != null) + return false; + } else if (!lastLoginTime.equals(other.lastLoginTime)) + return false; + return true; + } + + @Override + public String toString() { + return "User [firstName=" + firstName + ", lastName=" + lastName + ", userId=" + userId + ", email=" + email + + ", role=" + role + ", last login time=" + lastLoginTime + "]"; + } + +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/UserCredentials.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/UserCredentials.java new file mode 100644 index 000000000..5dec39541 --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/UserCredentials.java @@ -0,0 +1,53 @@ +/*- + * ============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.onap.sdc.ci.tests.datatypes; + +public class UserCredentials extends User { + + private String password; + + public UserCredentials(String userId, String password, String firstname, String lastname, String role) { + super(); + setUserId(userId); + this.password = password; + setFirstName(firstname); + setLastName(lastname); + setRole(role); + } + + public UserCredentials() { + super(); + } + + public UserCredentials(User user) { + super(); + this.copyData(user); + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/UserRoleEnum.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/UserRoleEnum.java new file mode 100644 index 000000000..793280aa0 --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/UserRoleEnum.java @@ -0,0 +1,77 @@ +/*- + * ============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.onap.sdc.ci.tests.datatypes; + +public enum UserRoleEnum { + + ADMIN("jh0003", "Jimmy", "Hendrix"), DESIGNER("cs0008", "Carlos", "Santana"), DESIGNER2("me0009", "Melissa","Etheridge"), TESTER("jm0007", "Joni", "Mitchell"), ADMIN4("km2000", "Kot", "May"), + GOVERNOR("gv0001","David", "Shadmi"), OPS("op0001", "Steve", "Regev"), PRODUCT_STRATEGIST1("ps0001", "Eden","Rozin"), PRODUCT_STRATEGIST2("ps0002", "Ella", "Kvetny"), PRODUCT_STRATEGIST3("ps0003", "Geva", "Alon"), + PRODUCT_MANAGER1("pm0001", "Teddy", "Isashar"), PRODUCT_MANAGER2("pm0002", "Sarah", "Bettens"); + private String userId; + private String firstName; + private String lastName; + private String userName; + + private UserRoleEnum(String userId, String userName) { + this.userId = userId; + this.userName = userName; + } + + private UserRoleEnum(String userId, String firstName, String lastName) { + this.userId = userId; + this.firstName = firstName; + this.lastName = lastName; + this.userName = firstName + " " + lastName; + } + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/http/HeaderData.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/http/HeaderData.java new file mode 100644 index 000000000..4dfdbad8b --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/http/HeaderData.java @@ -0,0 +1,114 @@ +/*- + * ============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.onap.sdc.ci.tests.datatypes.http; + +public class HeaderData { + String contentMd5; + String contentType; + String HttpCspUserId; + String HttpCspFirstName; + String HttpCspLastName; + String HttpCspWsType; + String HttpIvRemoteAddress; + String HttpIvUser; + + public HeaderData() { + super(); + } + + public HeaderData(String contentMd5, String contentType, String httpCspUserId, String httpCspFirstName, + String httpCspLastName, String httpCspWsType, String httpIvRemoteAddress, String httpIvUser) { + super(); + this.contentMd5 = contentMd5; + this.contentType = contentType; + HttpCspUserId = httpCspUserId; + HttpCspFirstName = httpCspFirstName; + HttpCspLastName = httpCspLastName; + HttpCspWsType = httpCspWsType; + HttpIvRemoteAddress = httpIvRemoteAddress; + HttpIvUser = httpIvUser; + } + + public String getContentMd5() { + return contentMd5; + } + + public void setContentMd5(String contentMd5) { + this.contentMd5 = contentMd5; + } + + public String getContentType() { + return contentType; + } + + public void setContentType(String contentType) { + this.contentType = contentType; + } + + public String getHttpCspUserId() { + return HttpCspUserId; + } + + public void setHttpCspUserId(String httpCspUserId) { + HttpCspUserId = httpCspUserId; + } + + public String getHttpCspFirstName() { + return HttpCspFirstName; + } + + public void setHttpCspFirstName(String httpCspFirstName) { + HttpCspFirstName = httpCspFirstName; + } + + public String getHttpCspLastName() { + return HttpCspLastName; + } + + public void setHttpCspLastName(String httpCspLastName) { + HttpCspLastName = httpCspLastName; + } + + public String getHttpCspWsType() { + return HttpCspWsType; + } + + public void setHttpCspWsType(String httpCspWsType) { + HttpCspWsType = httpCspWsType; + } + + public String getHttpIvRemoteAddress() { + return HttpIvRemoteAddress; + } + + public void setHttpIvRemoteAddress(String httpIvRemoteAddress) { + HttpIvRemoteAddress = httpIvRemoteAddress; + } + + public String getHttpIvUser() { + return HttpIvUser; + } + + public void setHttpIvUser(String httpIvUser) { + HttpIvUser = httpIvUser; + } + +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/http/HeaderValue.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/http/HeaderValue.java new file mode 100644 index 000000000..e09a97251 --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/http/HeaderValue.java @@ -0,0 +1,38 @@ +/*- + * ============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.onap.sdc.ci.tests.datatypes.http; + +public enum HeaderValue { + + APPLICATION_JSON("application/json"); + + String value; + + private HeaderValue(String value) { + this.value = value; + } + + public String getValue() { + + return value; + } + +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/http/HttpHeaderEnum.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/http/HttpHeaderEnum.java new file mode 100644 index 000000000..e57c5a449 --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/http/HttpHeaderEnum.java @@ -0,0 +1,58 @@ +/*- + * ============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.onap.sdc.ci.tests.datatypes.http; + +public enum HttpHeaderEnum { + + Content_MD5("Content-MD5"), + USER_ID("USER_ID"), + HTTP_CSP_FIRSTNAME("HTTP_CSP_FIRSTNAME"), + HTTP_CSP_LASTNAME("HTTP_CSP_LASTNAME"), + HTTP_CSP_WSTYPE("HTTP_CSP_WSTYPE"), + HTTP_IV_REMOTE_ADDRESS("HTTP_IV_REMOTE_ADDRESS"), + HTTP_IV_USER("HTTP_IV_USER"), + HTTP_CSP_EMAIL("HTTP_CSP_EMAIL"), + CONTENT_TYPE("Content-Type"), + ACCEPT("Accept"), + X_ECOMP_REQUEST_ID_HEADER("X-ECOMP-RequestID"), + CACHE_CONTROL("Cache-Control"), + X_ECOMP_INSTANCE_ID("X-ECOMP-InstanceID"), + AUTHORIZATION("Authorization"), + CONTENT_LENGTH("Content-Length"), + CONTENT_DISPOSITION("Content-Disposition"), + HOST("Host"), + X_ECOMP_SERVICE_ID_HEADER("X-ECOMP-ServiceID"), + WWW_AUTHENTICATE("WWW-Authenticate"), + ECOMP_PASSWORD("password"), + ECOMP_USERNAME("username"); + + String value; + + private HttpHeaderEnum(String value) { + this.value = value; + } + + public String getValue() { + + return value; + } + +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/http/HttpRequest.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/http/HttpRequest.java new file mode 100644 index 000000000..4f831b187 --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/http/HttpRequest.java @@ -0,0 +1,889 @@ +/*- + * ============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.onap.sdc.ci.tests.datatypes.http; + +import java.io.BufferedReader; +import java.io.DataOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.StringWriter; +import java.net.HttpURLConnection; +import java.net.URI; +import java.net.URL; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Scanner; + +import javax.net.ssl.HttpsURLConnection; + +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.io.IOUtils; +import org.apache.http.HttpEntity; +import org.apache.http.annotation.NotThreadSafe; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +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.apache.http.util.EntityUtils; +import org.onap.sdc.ci.tests.datatypes.http.RestResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.gson.Gson; + +public class HttpRequest { + static Logger logger = LoggerFactory.getLogger(HttpRequest.class.getName()); + + public RestResponse httpSendGet(String url, Map headers) throws IOException { + + RestResponse restResponse = new RestResponse(); + url = url.replaceAll("\\s", "%20"); + URL obj = new URL(url); + HttpURLConnection con = (HttpURLConnection) obj.openConnection(); + // optional default is GET + con.setRequestMethod("GET"); + // add request header + if (headers != null) { + for (Entry header : headers.entrySet()) { + String key = header.getKey(); + String value = header.getValue(); + con.setRequestProperty(key, value); + } + + } + + int responseCode = con.getResponseCode(); + logger.debug("Send GET http request, url: {}",url); + logger.debug("Response Code: {}",responseCode); + + StringBuffer response = new StringBuffer(); + String result; + + try { + + result = IOUtils.toString(con.getInputStream()); + response.append(result); + + } catch (Exception e) { + } + + try { + + result = IOUtils.toString(con.getErrorStream()); + response.append(result); + + } catch (Exception e) { + } + + logger.debug("Response body: {}" ,response); + + // print result + + restResponse.setStatusCode(responseCode); + + if (response != null) { + restResponse.setResponse(response.toString()); + } + + restResponse.setStatusCode(responseCode); + Map> headerFields = con.getHeaderFields(); + restResponse.setHeaderFields(headerFields); + String responseMessage = con.getResponseMessage(); + restResponse.setResponseMessage(responseMessage); + + con.disconnect(); + + return restResponse; + } + + public RestResponse httpsSendGet(String url, Map headers) throws IOException { + + RestResponse restResponse = new RestResponse(); + URL obj = new URL(url); + HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); + // optional default is GET + con.setRequestMethod("GET"); + // add request header + if (headers != null) { + for (Entry header : headers.entrySet()) { + String key = header.getKey(); + String value = header.getValue(); + con.setRequestProperty(key, value); + } + + } + + int responseCode = con.getResponseCode(); + logger.debug("Send GET http request, url: {}",url); + logger.debug("Response Code: {}",responseCode); + + StringBuffer response = new StringBuffer(); + try { + BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); + String inputLine; + while ((inputLine = in.readLine()) != null) { + response.append(inputLine); + } + in.close(); + } catch (Exception e) { + logger.debug("response body is null"); + } + + String result; + + try { + + result = IOUtils.toString(con.getErrorStream()); + response.append(result); + + } catch (Exception e2) { + // result = null; + } + logger.debug("Response body: {}",response); + + // print result + + restResponse.setStatusCode(responseCode); + + if (response != null) { + restResponse.setResponse(response.toString()); + } + + restResponse.setStatusCode(responseCode); + // restResponse.setResponse(result); + Map> headerFields = con.getHeaderFields(); + restResponse.setHeaderFields(headerFields); + String responseMessage = con.getResponseMessage(); + restResponse.setResponseMessage(responseMessage); + + con.disconnect(); + + return restResponse; + } + + public RestResponse httpSendByMethod(String url, String method, String body, Map headers) + throws IOException { + + RestResponse restResponse = new RestResponse(); + URL obj = new URL(url); + HttpURLConnection con = (HttpURLConnection) obj.openConnection(); + + // add request method + con.setRequestMethod(method); + + // add request headers + if (headers != null) { + for (Entry header : headers.entrySet()) { + String key = header.getKey(); + String value = header.getValue(); + con.setRequestProperty(key, value); + } + + } + if (body != null && !body.isEmpty() && !method.equals("DELETE")) { + // Send post request + con.setDoOutput(true); + DataOutputStream wr = new DataOutputStream(con.getOutputStream()); + wr.writeBytes(body); + wr.flush(); + wr.close(); + } + + // con.connect(); + + int responseCode = con.getResponseCode(); + logger.debug("Send {} http request, url: {}",method,url); + logger.debug("Response Code: {}",responseCode); + + StringBuffer response = new StringBuffer(); + + try { + BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); + String inputLine; + while ((inputLine = in.readLine()) != null) { + response.append(inputLine); + } + in.close(); + } catch (Exception e) { + // response = null; + logger.debug("response body is null"); + } + + String result; + try { + + result = IOUtils.toString(con.getErrorStream()); + response.append(result); + + } catch (Exception e2) { + result = null; + } + logger.debug("Response body: {}",response); + + // print result + + restResponse.setStatusCode(responseCode); + // if (response == null) { + // restResponse.setResponse(null); + // } else { + // restResponse.setResponse(response.toString()); + // } + + if (response != null) { + restResponse.setResponse(response.toString()); + } + Map> headerFields = con.getHeaderFields(); + restResponse.setHeaderFields(headerFields); + String responseMessage = con.getResponseMessage(); + restResponse.setResponseMessage(responseMessage); + + con.disconnect(); + return restResponse; + + } + + public RestResponse sendHttpPost(String url, String body, Map headers) throws IOException { + + RestResponse restResponse = new RestResponse(); + URL obj = new URL(url); + HttpURLConnection con = (HttpURLConnection) obj.openConnection(); + + // add request method + con.setRequestMethod("POST"); + + // add request headers + if (headers != null) { + for (Entry header : headers.entrySet()) { + String key = header.getKey(); + String value = header.getValue(); + con.setRequestProperty(key, value); + } + } + + // Send post request + if (body != null) { + con.setDoOutput(true); + DataOutputStream wr = new DataOutputStream(con.getOutputStream()); + wr.writeBytes(body); + wr.flush(); + wr.close(); + } + + // con.connect(); + + int responseCode = con.getResponseCode(); + logger.debug("Send POST http request, url: {}",url); + logger.debug("Response Code: {}",responseCode); + + StringBuffer response = new StringBuffer(); + try { + BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); + String inputLine; + while ((inputLine = in.readLine()) != null) { + response.append(inputLine); + } + in.close(); + } catch (Exception e) { + logger.debug("response body is null"); + } + + String result; + + try { + + result = IOUtils.toString(con.getErrorStream()); + response.append(result); + + } catch (Exception e2) { + result = null; + } + logger.debug("Response body: {}",response); + + // print result + + restResponse.setStatusCode(responseCode); + + if (response != null) { + restResponse.setResponse(response.toString()); + } + + Map> headerFields = con.getHeaderFields(); + restResponse.setHeaderFields(headerFields); + String responseMessage = con.getResponseMessage(); + restResponse.setResponseMessage(responseMessage); + + con.disconnect(); + return restResponse; + + } + + public RestResponse httpSendPost(String url, String body, Map headers) throws IOException { + return httpSendPost(url, body, headers, "POST"); + } + + public RestResponse httpSendPut(String url, String body, Map headers) throws IOException { + return httpSendPost(url, body, headers, "PUT"); + } + + public RestResponse httpSendPost(String url, String body, Map headers, String methodType) + throws IOException { + + RestResponse restResponse = new RestResponse(); + URL obj = new URL(url); + HttpURLConnection con = (HttpURLConnection) obj.openConnection(); + + // add request method + con.setRequestMethod(methodType); + + // add request headers + if (headers != null) { + for (Entry header : headers.entrySet()) { + String key = header.getKey(); + String value = header.getValue(); + con.setRequestProperty(key, value); + } + } + + // Send post request + if (body != null) { + con.setDoOutput(true); + DataOutputStream wr = new DataOutputStream(con.getOutputStream()); + wr.writeBytes(body); + wr.flush(); + wr.close(); + } + + // con.connect(); + + int responseCode = con.getResponseCode(); + logger.debug("Send POST http request, url: {}",url); + logger.debug("Response Code: {}",responseCode); + + StringBuffer response = new StringBuffer(); + try { + BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); + String inputLine; + while ((inputLine = in.readLine()) != null) { + response.append(inputLine); + } + in.close(); + } catch (Exception e) { + logger.debug("response body is null"); + } + + String result; + + try { + + result = IOUtils.toString(con.getErrorStream()); + response.append(result); + + } catch (Exception e2) { + result = null; + } + logger.debug("Response body: {}",response); + + // print result + + restResponse.setStatusCode(responseCode); + + if (response != null) { + restResponse.setResponse(response.toString()); + } + + Map> headerFields = con.getHeaderFields(); + restResponse.setHeaderFields(headerFields); + String responseMessage = con.getResponseMessage(); + restResponse.setResponseMessage(responseMessage); + + con.disconnect(); + return restResponse; + + } + + public RestResponse httpSendDeleteWithBody2(String url, String body, Map headers) + throws ClientProtocolException, IOException { + + CloseableHttpClient httpclient = HttpClients.createDefault(); + RestResponse restResponse = new RestResponse(); + HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(url); + + // add request headers + if (headers != null) { + for (Entry header : headers.entrySet()) { + String key = header.getKey(); + String value = header.getValue(); + httpDelete.addHeader(key, value); + } + } + + // add body to request + StringEntity input = new StringEntity(body, ContentType.APPLICATION_JSON); + httpDelete.setEntity(input); + + // execute request + CloseableHttpResponse response = httpclient.execute(httpDelete); + + restResponse.setStatusCode(response.getStatusLine().getStatusCode()); + + return restResponse; + } + + public RestResponse httpSendDeleteWithBody(String url, String body, Map headers) + throws IOException { + + RestResponse restResponse = new RestResponse(); + URL obj = new URL(url); + HttpURLConnection con = (HttpURLConnection) obj.openConnection(); + + // add request method + con.setRequestMethod("DELETE"); + + // add request headers + if (headers != null) { + for (Entry header : headers.entrySet()) { + String key = header.getKey(); + String value = header.getValue(); + con.setRequestProperty(key, value); + } + } + + // Send post request + con.setDoOutput(true); + DataOutputStream wr = new DataOutputStream(con.getOutputStream()); + wr.writeBytes(body); + wr.flush(); + wr.close(); + + // con.connect(); + + int responseCode = con.getResponseCode(); + logger.debug("Send DELETE http request, url: {}",url); + logger.debug("Response Code: {}",responseCode); + + StringBuffer response = new StringBuffer(); + try { + BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); + String inputLine; + while ((inputLine = in.readLine()) != null) { + response.append(inputLine); + } + in.close(); + } catch (Exception e) { + logger.debug("response body is null"); + } + + String result; + + try { + + result = IOUtils.toString(con.getErrorStream()); + response.append(result); + + } catch (Exception e2) { + result = null; + } + logger.debug("Response body: {}", response); + + // print result + + restResponse.setStatusCode(responseCode); + + if (response != null) { + restResponse.setResponse(response.toString()); + } + + Map> headerFields = con.getHeaderFields(); + restResponse.setHeaderFields(headerFields); + String responseMessage = con.getResponseMessage(); + restResponse.setResponseMessage(responseMessage); + + con.disconnect(); + return restResponse; + + } + + public RestResponse httpSendPostWithOutBody(String url, Map headers) throws IOException { + + RestResponse restResponse = new RestResponse(); + URL obj = new URL(url); + HttpURLConnection con = (HttpURLConnection) obj.openConnection(); + + // add request method + con.setRequestMethod("POST"); + + // add request headers + if (headers != null) { + for (Entry header : headers.entrySet()) { + String key = header.getKey(); + String value = header.getValue(); + con.setRequestProperty(key, value); + } + } + + // con.connect(); + + int responseCode = con.getResponseCode(); + logger.debug("Send POST http request, url: {}",url); + logger.debug("Response Code: {}",responseCode); + + StringBuffer response = new StringBuffer(); + + try { + BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); + String inputLine; + while ((inputLine = in.readLine()) != null) { + response.append(inputLine); + } + in.close(); + } catch (Exception e) { + // response = null; + logger.debug("response body is null"); + } + + String result; + try { + + result = IOUtils.toString(con.getErrorStream()); + response.append(result); + + } catch (Exception e2) { + result = null; + } + logger.debug("Response body: {}",response); + + // print result + + restResponse.setStatusCode(responseCode); + // if (response == null) { + // restResponse.setResponse(null); + // } else { + // restResponse.setResponse(response.toString()); + // } + + if (response != null) { + restResponse.setResponse(response.toString()); + } + + Map> headerFields = con.getHeaderFields(); + restResponse.setHeaderFields(headerFields); + String responseMessage = con.getResponseMessage(); + restResponse.setResponseMessage(responseMessage); + + con.disconnect(); + return restResponse; + + } + + public RestResponse httpSendPostMultipart(String url, Map headers, String jsonLocation, + String zipLocation) throws IOException { + + Gson gson = new Gson(); + String gsonToSend = null; + RestResponse restResponse = new RestResponse(); + BufferedReader br = null; + // + // + // + // + // try { + // + // String sCurrentLine; + // + // br = new BufferedReader(new FileReader(jsonLocation)); + // + // while ((sCurrentLine = br.readLine()) != null) { + // System.out.println(sCurrentLine); + // } + // + // } catch (IOException e) { + // e.printStackTrace(); + // } finally { + // try { + // if (br != null)br.close(); + // gsonToSend = br.toString(); + // } catch (IOException ex) { + // ex.printStackTrace(); + // } + // } + + gsonToSend = new Scanner(new File(jsonLocation)).useDelimiter("\\Z").next(); + logger.debug("gsonToSend: {}",gsonToSend); + + MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create(); + mpBuilder.addPart("resourceZip", new FileBody(new File(zipLocation))); + mpBuilder.addPart("resourceMetadata", new StringBody(gsonToSend, ContentType.APPLICATION_JSON)); + + HttpPost httpPost = new HttpPost(url); + httpPost.addHeader("USER_ID", "adminid"); + httpPost.setEntity(mpBuilder.build()); + + CloseableHttpClient client = HttpClients.createDefault(); + CloseableHttpResponse response = client.execute(httpPost); + try { + logger.debug("----------------------------------------"); + logger.debug("response.getStatusLine(): {}",response.getStatusLine()); + HttpEntity resEntity = response.getEntity(); + if (resEntity != null) { + logger.debug("Response content length: {}",resEntity.getContentLength()); + } + EntityUtils.consume(resEntity); + } finally { + + response.close(); + client.close(); + } + + restResponse.setStatusCode(response.getStatusLine().getStatusCode()); + restResponse.setResponse(response.getEntity().toString()); + + return restResponse; + + } + + public RestResponse httpSendPostWithAuth(String url, String body, Map headers, String username, + String password) throws IOException { + + String userPassword = username + ":" + password; + String encoding = Base64.encodeBase64String(userPassword.getBytes()); + RestResponse restResponse = new RestResponse(); + URL obj = new URL(url); + HttpURLConnection con = (HttpURLConnection) obj.openConnection(); + + // add request method + con.setRequestMethod("POST"); + + con.setRequestProperty("Authorization", "Basic " + encoding); + + // add request headers + if (headers != null) { + for (Entry header : headers.entrySet()) { + String key = header.getKey(); + String value = header.getValue(); + con.setRequestProperty(key, value); + } + + } + + // Send post request + con.setDoOutput(true); + DataOutputStream wr = new DataOutputStream(con.getOutputStream()); + wr.writeBytes(body); + wr.flush(); + wr.close(); + + // con.connect(); + + int responseCode = con.getResponseCode(); + logger.debug("Send POST http request, url: {}",url); + logger.debug("Response Code: {}",responseCode); + + StringBuffer response = new StringBuffer(); + try { + BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); + String inputLine; + while ((inputLine = in.readLine()) != null) { + response.append(inputLine); + } + in.close(); + } catch (Exception e) { + response = null; + + } + logger.debug("Response body: {}",response); + + // print result + + restResponse.setStatusCode(responseCode); + if (response == null) { + restResponse.setResponse(null); + } else { + restResponse.setResponse(response.toString()); + } + + Map> headerFields = con.getHeaderFields(); + restResponse.setHeaderFields(headerFields); + String responseMessage = con.getResponseMessage(); + restResponse.setResponseMessage(responseMessage); + + con.disconnect(); + return restResponse; + + } + + public RestResponse httpSendDelete(String url, Map headers) throws IOException { + + RestResponse restResponse = new RestResponse(); + URL obj = new URL(url); + HttpURLConnection con = (HttpURLConnection) obj.openConnection(); + + if (headers != null) { + for (Entry header : headers.entrySet()) { + String key = header.getKey(); + String value = header.getValue(); + con.setRequestProperty(key, value); + } + + } + + con.setDoOutput(true); + con.setRequestMethod("DELETE"); + int responseCode = con.getResponseCode(); + logger.debug("Send DELETE http request, url: {}",url); + logger.debug("Response Code: {}",responseCode); + + StringBuffer response = new StringBuffer(); + + try { + BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); + String inputLine; + while ((inputLine = in.readLine()) != null) { + response.append(inputLine); + } + in.close(); + } catch (Exception e) { + logger.debug("response body is null"); + } + + String result; + + try { + + result = IOUtils.toString(con.getErrorStream()); + response.append(result); + + } catch (Exception e2) { + result = null; + } + logger.debug("Response body: {}",response); + + // print result + + restResponse.setStatusCode(responseCode); + + if (response != null) { + restResponse.setResponse(response.toString()); + } + + restResponse.setStatusCode(con.getResponseCode()); + Map> headerFields = con.getHeaderFields(); + restResponse.setHeaderFields(headerFields); + String responseMessage = con.getResponseMessage(); + restResponse.setResponseMessage(responseMessage); + + con.disconnect(); + + return restResponse; + } + + public static RestResponse sendHttpPostWithEntity(HttpEntity requestEntity, String url, Map headers) + throws IOException, ClientProtocolException { + CloseableHttpResponse response = null; + CloseableHttpClient client = HttpClients.createDefault(); + try { + HttpPost httpPost = new HttpPost(url); + RestResponse restResponse = new RestResponse(); + for (Entry entry : headers.entrySet()) { + httpPost.addHeader(entry.getKey(), entry.getValue()); + } + + httpPost.setEntity(requestEntity); + response = client.execute(httpPost); + HttpEntity responseEntity = response.getEntity(); + String responseBody = null; + if (responseEntity != null) { + InputStream instream = responseEntity.getContent(); + StringWriter writer = new StringWriter(); + IOUtils.copy(instream, writer); + responseBody = writer.toString(); + try { + + } finally { + instream.close(); + } + } + + restResponse.setStatusCode(response.getStatusLine().getStatusCode()); + restResponse.setResponse(responseBody); + + return restResponse; + + } finally { + closeResponse(response); + closeHttpClient(client); + + } + } + + private static void closeHttpClient(CloseableHttpClient client) { + try { + if (client != null) { + client.close(); + } + } catch (IOException e) { + logger.debug("failed to close client or response: ", e); + } + } + + private static void closeResponse(CloseableHttpResponse response) { + try { + if (response != null) { + response.close(); + } + } catch (IOException e) { + logger.debug("failed to close client or response: ", e); + } + } + + @NotThreadSafe + class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase { + public static final String METHOD_NAME = "DELETE"; + + public String getMethod() { + return METHOD_NAME; + } + + public HttpDeleteWithBody(final String uri) { + super(); + setURI(URI.create(uri)); + } + + public HttpDeleteWithBody(final URI uri) { + super(); + setURI(uri); + } + + public HttpDeleteWithBody() { + super(); + } + } + +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/http/MustHeaders.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/http/MustHeaders.java new file mode 100644 index 000000000..e9a87ed1d --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/http/MustHeaders.java @@ -0,0 +1,53 @@ +/*- + * ============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.onap.sdc.ci.tests.datatypes.http; + +import java.util.HashMap; +import java.util.Map; + +public class MustHeaders { + + private Map headers = new HashMap(); + + public MustHeaders(HeaderData headerData) { + + super(); + headers.put(HttpHeaderEnum.Content_MD5.getValue(), headerData.getContentMd5()); + headers.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), headerData.getContentType()); + headers.put(HttpHeaderEnum.ACCEPT.getValue(), headerData.getContentType()); + headers.put(HttpHeaderEnum.USER_ID.getValue(), headerData.getHttpCspUserId()); + headers.put(HttpHeaderEnum.HTTP_CSP_FIRSTNAME.getValue(), headerData.getHttpCspFirstName()); + headers.put(HttpHeaderEnum.HTTP_CSP_LASTNAME.getValue(), headerData.getHttpCspLastName()); + headers.put(HttpHeaderEnum.HTTP_CSP_WSTYPE.getValue(), headerData.getHttpCspWsType()); + headers.put(HttpHeaderEnum.HTTP_IV_REMOTE_ADDRESS.getValue(), headerData.getHttpIvRemoteAddress()); + headers.put(HttpHeaderEnum.HTTP_IV_USER.getValue(), headerData.getHttpIvUser()); + + } + + public MustHeaders() { + super(); + } + + public Map getMap() { + return headers; + } + +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/http/RestResponse.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/http/RestResponse.java new file mode 100644 index 000000000..8974b74c1 --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/datatypes/http/RestResponse.java @@ -0,0 +1,84 @@ +/*- + * ============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.onap.sdc.ci.tests.datatypes.http; + +import java.util.List; +import java.util.Map; + +public class RestResponse { + + Integer statusCode; + String response; + Map> headerFields; + String responseMessage; + + public RestResponse() { + super(); + } + + public RestResponse(Integer errorCode, String response, Map> headerFields, + String responseMessage) { + super(); + this.statusCode = errorCode; + this.response = response; + this.headerFields = headerFields; + this.responseMessage = responseMessage; + } + + public Integer getStatusCode() { + return statusCode; + } + + public void setStatusCode(Integer errorCode) { + this.statusCode = errorCode; + } + + public String getResponse() { + return response; + } + + public void setResponse(String response) { + this.response = response; + } + + public Map> getHeaderFields() { + return headerFields; + } + + public void setHeaderFields(Map> headerFields) { + this.headerFields = headerFields; + } + + public String getResponseMessage() { + return responseMessage; + } + + public void setResponseMessage(String responseMessage) { + this.responseMessage = responseMessage; + } + + @Override + public String toString() { + return "RestResponse [errorCode=" + statusCode + ", response=" + response + ", headerFields=" + headerFields + + ", responseMessage=" + responseMessage + "]"; + } + +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/devObjects/CategoryDataDefinition.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/devObjects/CategoryDataDefinition.java new file mode 100644 index 000000000..0c673e62d --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/devObjects/CategoryDataDefinition.java @@ -0,0 +1,111 @@ +package org.onap.sdc.ci.tests.devObjects; + + +import java.io.Serializable; +import java.util.List; + +public class CategoryDataDefinition extends ToscaDataDefinition implements Serializable { + + /** + * + */ + private static final long serialVersionUID = 2882352060242714427L; + + private String name; + private String normalizedName; + private String uniqueId; + private List icons; + + public CategoryDataDefinition() { + + } + + public CategoryDataDefinition(CategoryDataDefinition c) { + this.name = c.name; + this.normalizedName = c.normalizedName; + this.uniqueId = c.uniqueId; + this.icons = c.icons; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getNormalizedName() { + return normalizedName; + } + + public void setNormalizedName(String normalizedName) { + this.normalizedName = normalizedName; + } + + public String getUniqueId() { + return uniqueId; + } + + public void setUniqueId(String uniqueId) { + this.uniqueId = uniqueId; + } + + public List getIcons() { + return icons; + } + + public void setIcons(List icons) { + this.icons = icons; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((name == null) ? 0 : name.hashCode()); + result = prime * result + ((normalizedName == null) ? 0 : normalizedName.hashCode()); + result = prime * result + ((uniqueId == null) ? 0 : uniqueId.hashCode()); + result = prime * result + ((icons == null) ? 0 : icons.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + CategoryDataDefinition other = (CategoryDataDefinition) obj; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + if (normalizedName == null) { + if (other.normalizedName != null) + return false; + } else if (!normalizedName.equals(other.normalizedName)) + return false; + if (uniqueId == null) { + if (other.uniqueId != null) + return false; + } else if (!uniqueId.equals(other.uniqueId)) + return false; + if (icons == null) { + if (other.icons != null) + return false; + } else if (!icons.equals(other.icons)) + return false; + return true; + } + + @Override + public String toString() { + return "CategoryDataDefinition [name=" + name + ", normalizedName=" + normalizedName + ", uniqueId=" + uniqueId + + ", icons=" + icons + "]"; + } + +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/devObjects/CategoryDefinition.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/devObjects/CategoryDefinition.java new file mode 100644 index 000000000..ef65a2de2 --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/devObjects/CategoryDefinition.java @@ -0,0 +1,64 @@ +/*- + * ============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.onap.sdc.ci.tests.devObjects; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +public class CategoryDefinition extends CategoryDataDefinition implements Serializable { + + /** + * + */ + private static final long serialVersionUID = 6552733796860992476L; + + List subcategories; + + public CategoryDefinition() { + super(); + } + + public CategoryDefinition(CategoryDataDefinition c) { + super(c); + } + + public List getSubcategories() { + return subcategories; + } + + public void setSubcategories(List subcategories) { + this.subcategories = subcategories; + } + + public void addSubCategory(SubCategoryDefinition subcategory) { + if (subcategories == null) { + subcategories = new ArrayList(); + } + subcategories.add(subcategory); + } + + @Override + public String toString() { + return super.toString() + " CategoryDefinition [subcategories=" + subcategories + "]"; + } + +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/devObjects/GraphPropertyEnum.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/devObjects/GraphPropertyEnum.java new file mode 100644 index 000000000..b393b9160 --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/devObjects/GraphPropertyEnum.java @@ -0,0 +1,103 @@ +package org.onap.sdc.ci.tests.devObjects; + +import java.util.ArrayList; +import java.util.List; + + + +public enum GraphPropertyEnum { +// field name class type unique indexed +// stored in graph index + UNIQUE_ID ("uid", String.class, true, true), + LABEL ("nodeLabel", String.class, false, true), + JSON ("json", String.class, false, false), + METADATA ("metadata", String.class, false, false), + VERSION ("version", String.class, false, true), + STATE ("state", String.class, false, true), + IS_HIGHEST_VERSION ("highestVersion", Boolean.class, false, true), + IS_DELETED ("deleted", Boolean.class, false, true), + NORMALIZED_NAME ("normalizedName", String.class, false, true), + NAME ("name", String.class, false, true), + TOSCA_RESOURCE_NAME ("toscaResourceName", String.class, false, true), + DISTRIBUTION_STATUS ("distributionStatus", String.class, false, false), + RESOURCE_TYPE ("resourceType", String.class, false, true), + COMPONENT_TYPE ("componentType", String.class, false, true), + UUID ("uuid", String.class, false, true), + SYSTEM_NAME ("systemName", String.class, false, true), + IS_ABSTRACT ("abstract", Boolean.class, false, true), + INVARIANT_UUID ("invariantUuid", String.class, false, true), + CSAR_UUID ("csarUuid", String.class, false, true), + //used for user (old format, no json for users) + USERID ("userId", String.class, true, true), + ROLE ("role", String.class, false, false), + FIRST_NAME ("firstName", String.class, false, false), + LAST_NAME ("lastName", String.class, false, false), + EMAIL ("email", String.class, false, false), + LAST_LOGIN_TIME ("lastLoginTime", Long.class, false, false), + //used for category (old format, no json for categories) + ICONS ("icons", String.class, false, false); + + private String property; + private Class clazz; + private boolean unique; + private boolean indexed; + + GraphPropertyEnum(String property, Class clazz, boolean unique, boolean indexed) { + this.property = property; + this.clazz = clazz; + this.unique = unique; + this.indexed = indexed; + } + + public static GraphPropertyEnum getByProperty(String property){ + for(GraphPropertyEnum currProperty :GraphPropertyEnum.values()){ + if(currProperty.getProperty().equals(property)){ + return currProperty; + } + } + return null; + } + + public String getProperty() { + return property; + } + + public void setProperty(String property) { + this.property = property; + } + + public Class getClazz() { + return clazz; + } + + public void setClazz(Class clazz) { + this.clazz = clazz; + } + + public boolean isUnique() { + return unique; + } + + public void setUnique(boolean unique) { + this.unique = unique; + } + + public boolean isIndexed() { + return indexed; + } + + public void setIndexed(boolean indexed) { + this.indexed = indexed; + } + + public static List getAllProperties() { + + List arrayList = new ArrayList(); + + for (GraphPropertyEnum graphProperty : GraphPropertyEnum.values()) { + arrayList.add(graphProperty.getProperty()); + } + + return arrayList; + } +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/devObjects/GroupingDataDefinition.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/devObjects/GroupingDataDefinition.java new file mode 100644 index 000000000..cdb45c5c6 --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/devObjects/GroupingDataDefinition.java @@ -0,0 +1,112 @@ +/*- + * ============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.onap.sdc.ci.tests.devObjects; + +import java.io.Serializable; + +public class GroupingDataDefinition extends ToscaDataDefinition implements Serializable { + /** + * + */ + private static final long serialVersionUID = 2641475929148843849L; + + private String name; + private String normalizedName; + private String uniqueId; + + public GroupingDataDefinition() { + + } + + public GroupingDataDefinition(GroupingDataDefinition c) { + this.name = c.name; + this.normalizedName = c.normalizedName; + this.uniqueId = c.uniqueId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getNormalizedName() { + return normalizedName; + } + + public void setNormalizedName(String normalizedName) { + this.normalizedName = normalizedName; + } + + public String getUniqueId() { + return uniqueId; + } + + public void setUniqueId(String uniqueId) { + this.uniqueId = uniqueId; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((name == null) ? 0 : name.hashCode()); + result = prime * result + ((normalizedName == null) ? 0 : normalizedName.hashCode()); + result = prime * result + ((uniqueId == null) ? 0 : uniqueId.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + GroupingDataDefinition other = (GroupingDataDefinition) obj; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + if (normalizedName == null) { + if (other.normalizedName != null) + return false; + } else if (!normalizedName.equals(other.normalizedName)) + return false; + if (uniqueId == null) { + if (other.uniqueId != null) + return false; + } else if (!uniqueId.equals(other.uniqueId)) + return false; + return true; + } + + @Override + public String toString() { + return "GroupingDataDefinition [name=" + name + ", normalizedName=" + normalizedName + ", uniqueId=" + uniqueId + + "]"; + } + +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/devObjects/GroupingDefinition.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/devObjects/GroupingDefinition.java new file mode 100644 index 000000000..7b04d2307 --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/devObjects/GroupingDefinition.java @@ -0,0 +1,33 @@ +/*- + * ============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.onap.sdc.ci.tests.devObjects; + +public class GroupingDefinition extends GroupingDataDefinition { + + public GroupingDefinition() { + super(); + } + + public GroupingDefinition(GroupingDataDefinition g) { + super(g); + } + +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/devObjects/JsonPresentationFields.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/devObjects/JsonPresentationFields.java new file mode 100644 index 000000000..d17755207 --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/devObjects/JsonPresentationFields.java @@ -0,0 +1,193 @@ +package org.onap.sdc.ci.tests.devObjects; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + + +//@JsonDeserialize(using = MyDeserializer.class) + +public enum JsonPresentationFields { + UNIQUE_ID ("uniqueId", GraphPropertyEnum.UNIQUE_ID), + HIGHEST_VERSION ("highestVersion", GraphPropertyEnum.IS_HIGHEST_VERSION), + LIFECYCLE_STATE ("lifecycleState", GraphPropertyEnum.STATE), + CREATION_DATE ("creationDate", null), + LAST_UPDATE_DATE ("lastUpdateDate", null), + SYSTEM_NAME ("systemName", GraphPropertyEnum.SYSTEM_NAME), + NAME ("name", GraphPropertyEnum.NAME), + VERSION ("version", GraphPropertyEnum.VERSION), + NORMALIZED_NAME ("normalizedName", GraphPropertyEnum.NORMALIZED_NAME), + UUID ("UUID", GraphPropertyEnum.UUID), + RESOURCE_TYPE ("resourceType", GraphPropertyEnum.RESOURCE_TYPE), + COMPONENT_TYPE ("componentType", GraphPropertyEnum.COMPONENT_TYPE), + IS_DELETED ("isDeleted", GraphPropertyEnum.IS_DELETED), + ECOMP_GENERATED_NAMING ("ecompGeneratedNaming", null), + NAMING_POLICY ("namingPolicy", null), + TOSCA_RESOURCE_NAME ("toscaResourceName", GraphPropertyEnum.TOSCA_RESOURCE_NAME), + DESCRIPTION ("description", null), + TYPE ("type", null), + DERIVED_FROM ("derivedFrom", null), + VENDOR_NAME ("vendorName", null), + VENDOR_RELEASE ("vendorRelease", null), + CONFORMANCE_LEVEL ("conformanceLevel", null), + ICON ("icon", null), + TAGS ("tags", null), + INVARIANT_UUID ("invariantUuid", GraphPropertyEnum.INVARIANT_UUID), + CSAR_UUID ("csarUuid", GraphPropertyEnum.CSAR_UUID), + CSAR_VERSION ("csarVersion", null), + IMPORTED_TOSCA_CHECKSUM ("importedToscaChecksum", null), + CONTACT_ID ("contactId", null), + PROJECT_CODE ("projectCode", null), + DISTRIBUTION_STATUS ("distributionStatus", GraphPropertyEnum.DISTRIBUTION_STATUS), + DERIVED_FROM_GENERIC_TYPE ("derivedFromGenericType", null), + DERIVED_FROM_GENERIC_VERSION ("derivedFromGenericVersion", null), + + ////Artifact + ARTIFACT_TYPE ("artifactType", null), + ARTIFACT_REF ("artifactRef", null), + ARTIFACT_REPOSITORY ("artifactRepository", null), + ARTIFACT_CHECKSUM ("artifactChecksum", null), + ARTIFACT_CREATOR ("artifactCreator", null), + USER_ID_CREATOR ("userIdCreator", null), + USER_ID_LAST_UPDATER ("userIdLastUpdater", null), + CREATOR_FULL_NAME ("creatorFullName", null), + UPDATER_FULL_NAME ("updaterFullName", null), + + ES_ID ("esId", null), + ARTIFACT_LABEL ("artifactLabel", null), + IS_ABSTRACT ("mandatory", null), + ARTIFACT_DISPLAY_NAME ("artifactDisplayName", null), + API_URL ("apiUrl", null), + SERVICE_API ("serviceApi", null), + ARTIFACT_VERSION ("artifactVersion", null), + ARTIFACT_UUID ("artifactUUID", null), + PAYLOAD_UPDATE_DATE ("payloadUpdateDate", null), + HEAT_PARAMS_UPDATE_DATE ("heatParamsUpdateDate", null), + GENERATED ("generated", null), + ARTIFACT_GROUP_TYPE ("artifactGroupType", null), + ARTIFACT_TIMEOUT ("timeout", null), + REQUIRED_ARTIFACTS ("requiredArtifacts", null), + DUPLICATED ("duplicated", null), + HEAT_PARAMETERS ("heatParameters", null), + GENERATED_FROM_ID ("generatedFromId", null), + + + // end artifacts + + + //property + DEFINITION ("definition", null), + DEFAULT_VALUE ("defaultValue", null), + REQUIRED ("required", null), + PASSWORD ("password", null), + CONSTRAINTS ("constraints", null), + PROPERTIES ("properties", null), + PROPERTY ("property", null), + SCHEMA ("schema", null), + VALUE ("value", null), + PARENT_UNIQUE_ID ("parentUniqueId", null), + + COMPONENT_INSTANCES ("componentInstances", null), + RELATIONS ("relations", null), + + //attribute + STATUS ("status", null), + //capability + VALID_SOURCE_TYPE ("validSourceTypes", null), + CREATION_TIME ("creationTime", null), + MODIFICATION_TIME ("modificationTime", null), + CAPABILITY_SOURCES ("capabilitySources", null), + MAX_OCCURRENCES ("maxOccurrences", null), + MIN_OCCURRENCES ("minOccurrences", null), + OWNER_NAME ("ownerName", null), + OWNER_ID ("ownerId", null), + LEFT_OCCURRENCES ("leftOccurences", null), + CAPABILITY_ID ("capabiltyId", null), + PATH ("path", null), + SOURCE ("source", null), + + //Requirement + CAPAPILITY ("capability", null), + NODE ("node", null), + RELATIONSHIP ("relationship", null), + VALID_SOURCE_TYPES ("validSourceTypes", null), + REQUIREMENT_ID ("requirementId", null), + + //Relation + CAPABILTY_OWNER_ID ("capabilityOwnerId", null), + REQUIREMENT_OWNER_ID ("requirementOwnerId", null), + FROM_ID ("fromId", null), + TO_ID ("toId", null), + REQUIREMENT ("requirement", null), + + //Groups + + GROUP_INVARIANT_UUID ("invariantUUID", null), + GROUP_UUID ("groupUUID", null), + GROUP_MEMBER ("members", null), + GROUP_ARTIFACTS ("artifacts", null), + GROUP_ARTIFACTS_UUID ("artifactsUuid", null), + GROUP_PROPERTIES ("properties", null), + GROUP_UNIQUE_ID ("groupUid", null), + POS_X ("posX", null), + POS_Y ("posY", null), + PROPERTY_VALUE_COUNTER ("propertyValueCounter", null), + CUSTOMIZATION_UUID ("customizationUUID", null), + GROUP_NAME ("groupName", null), + GROUP_INSTANCE_ARTIFACTS ("groupInstanceArtifacts", null), + GROUP_INSTANCE_ARTIFACTS_UUID ("groupInstanceArtifactsUuid", null), + GROUP_INSTANCE_PROPERTIES ("groupInstancesProperties", null), + + ; + + + private String presentation; + private GraphPropertyEnum storedAs; + + JsonPresentationFields(String presentation, GraphPropertyEnum storedAs) { + this.presentation = presentation; + this.storedAs = storedAs; + } + + @JsonValue + public String getPresentation() { + return presentation; + } + + public void setPresentation(String presentation) { + this.presentation = presentation; + } + + public GraphPropertyEnum getStoredAs() { + return storedAs; + } + + public void setStoredAs(GraphPropertyEnum storedAs) { + this.storedAs = storedAs; + } + + public static String getPresentationByGraphProperty(GraphPropertyEnum property) { + for(JsonPresentationFields currPresentation : JsonPresentationFields.values()){ + if(currPresentation.getStoredAs() == property){ + return currPresentation.getPresentation(); + } + } + return null; + } + + @Override + public String toString() { + // TODO Auto-generated method stub + return presentation; + } + + @JsonCreator + public static JsonPresentationFields getByPresentation(String presentation) { + for (JsonPresentationFields inst : JsonPresentationFields.values()) { + if (inst.getPresentation().equals(presentation)) { + return inst; + } + } + return null; + } + +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/devObjects/LifecycleStateEnum.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/devObjects/LifecycleStateEnum.java new file mode 100644 index 000000000..e17222cf2 --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/devObjects/LifecycleStateEnum.java @@ -0,0 +1,44 @@ +/*- + * ============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.onap.sdc.ci.tests.devObjects; + +public enum LifecycleStateEnum { + + READY_FOR_CERTIFICATION, + + CERTIFICATION_IN_PROGRESS, + + CERTIFIED, + + NOT_CERTIFIED_CHECKIN, + + NOT_CERTIFIED_CHECKOUT; + + public static LifecycleStateEnum findState(String state) { + + for (LifecycleStateEnum lifecycleStateEnum : LifecycleStateEnum.values()) { + if (lifecycleStateEnum.name().equals(state)) { + return lifecycleStateEnum; + } + } + return null; + } +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/devObjects/ResourceTypeEnum.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/devObjects/ResourceTypeEnum.java new file mode 100644 index 000000000..549968205 --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/devObjects/ResourceTypeEnum.java @@ -0,0 +1,101 @@ +/*- + * ============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.onap.sdc.ci.tests.devObjects; + +/** + * Resource Type Enum + * @author mshitrit + * + */ +public enum ResourceTypeEnum { + + VFC("VFC (Virtual Function Component)"), VF("VF"/* (Virtual Function)" */), CP("CP (Connection Point)"), + VL( "VL (Virtual Link)"), VFCMT("VFCMT (VFC Monitoring Template)"), ABSTRACT("Abstract (Generic VFC/VF/Service Type)"); + + private String value; + + private ResourceTypeEnum(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + public static ResourceTypeEnum getType(String type) { + for (ResourceTypeEnum e : ResourceTypeEnum.values()) { + if (e.name().equals(type)) { + return e; + } + } + return null; + } + + public static ResourceTypeEnum getTypeByName(String type) { + for (ResourceTypeEnum e : ResourceTypeEnum.values()) { + if (e.name().equalsIgnoreCase(type)) { + return e; + } + } + return null; + } +/** + * Returns ResourceTypeEnum matching to received String ignore case + * @param type + * @return + */ + public static ResourceTypeEnum getTypeIgnoreCase(String type) { + for (ResourceTypeEnum e : ResourceTypeEnum.values()) { + if (e.name().toLowerCase().equals(type.toLowerCase())) { + return e; + } + } + return null; + } + /** + * Checks if enum exist with given type + * @param type + * @return + */ + public static boolean containsName(String type) { + + for (ResourceTypeEnum e : ResourceTypeEnum.values()) { + if (e.name().equals(type)) { + return true; + } + } + return false; + } + /** + * Checks if enum exist with given type ignare case + * @param type + * @return + */ + public static boolean containsIgnoreCase(String type) { + + for (ResourceTypeEnum e : ResourceTypeEnum.values()) { + if (e.name().toLowerCase().equals(type.toLowerCase())) { + return true; + } + } + return false; + } +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/devObjects/SubCategoryDataDefinition.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/devObjects/SubCategoryDataDefinition.java new file mode 100644 index 000000000..0eb76014e --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/devObjects/SubCategoryDataDefinition.java @@ -0,0 +1,128 @@ +/*- + * ============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.onap.sdc.ci.tests.devObjects; + +import java.io.Serializable; +import java.util.List; + +public class SubCategoryDataDefinition extends ToscaDataDefinition implements Serializable { + /** + * + */ + private static final long serialVersionUID = 8279397988497086676L; + + private String name; + private String normalizedName; + private String uniqueId; + private List icons; + + public SubCategoryDataDefinition() { + + } + + public SubCategoryDataDefinition(SubCategoryDataDefinition c) { + this.name = c.name; + this.normalizedName = c.normalizedName; + this.uniqueId = c.uniqueId; + this.icons = c.icons; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getNormalizedName() { + return normalizedName; + } + + public void setNormalizedName(String normalizedName) { + this.normalizedName = normalizedName; + } + + public String getUniqueId() { + return uniqueId; + } + + public void setUniqueId(String uniqueId) { + this.uniqueId = uniqueId; + } + + public List getIcons() { + return icons; + } + + public void setIcons(List icons) { + this.icons = icons; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((name == null) ? 0 : name.hashCode()); + result = prime * result + ((normalizedName == null) ? 0 : normalizedName.hashCode()); + result = prime * result + ((uniqueId == null) ? 0 : uniqueId.hashCode()); + result = prime * result + ((icons == null) ? 0 : icons.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + SubCategoryDataDefinition other = (SubCategoryDataDefinition) obj; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + if (normalizedName == null) { + if (other.normalizedName != null) + return false; + } else if (!normalizedName.equals(other.normalizedName)) + return false; + if (uniqueId == null) { + if (other.uniqueId != null) + return false; + } else if (!uniqueId.equals(other.uniqueId)) + return false; + if (icons == null) { + if (other.icons != null) + return false; + } else if (!icons.equals(other.icons)) + return false; + return true; + } + + @Override + public String toString() { + return "SubCategoryDataDefinition [name=" + name + ", normalizedName=" + normalizedName + ", uniqueId=" + + uniqueId + ", icons=" + icons + "]"; + } +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/devObjects/SubCategoryDefinition.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/devObjects/SubCategoryDefinition.java new file mode 100644 index 000000000..b45ce4fa1 --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/devObjects/SubCategoryDefinition.java @@ -0,0 +1,58 @@ +/*- + * ============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.onap.sdc.ci.tests.devObjects; + +import java.util.ArrayList; +import java.util.List; + +public class SubCategoryDefinition extends SubCategoryDataDefinition { + + private List groupings; + + public SubCategoryDefinition() { + super(); + } + + public SubCategoryDefinition(SubCategoryDataDefinition subCategory) { + super(subCategory); + } + + public List getGroupings() { + return groupings; + } + + public void setGroupings(List groupingDefinitions) { + this.groupings = groupingDefinitions; + } + + public void addGrouping(GroupingDefinition groupingDefinition) { + if (groupings == null) { + groupings = new ArrayList(); + } + groupings.add(groupingDefinition); + } + + @Override + public String toString() { + return super.toString() + " SubCategoryDefinition [groupings=" + groupings + "]"; + } + +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/devObjects/ToscaDataDefinition.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/devObjects/ToscaDataDefinition.java new file mode 100644 index 000000000..c4fa53b5d --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/devObjects/ToscaDataDefinition.java @@ -0,0 +1,79 @@ +package org.onap.sdc.ci.tests.devObjects; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import fj.data.Either; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.stream.Collectors; + +public abstract class ToscaDataDefinition { + + protected Map toscaPresentation; + + + public ToscaDataDefinition(){ + toscaPresentation = new HashMap(); + } + @JsonCreator + public ToscaDataDefinition(Map art){ + toscaPresentation = art; + } + @JsonValue + public Object getToscaPresentationValue(JsonPresentationFields name) { + if (toscaPresentation != null && toscaPresentation.containsKey(name.getPresentation())) { + return toscaPresentation.get(name.getPresentation()); + } + return null; + } + + public void setToscaPresentationValue(JsonPresentationFields name, Object value) { + if (toscaPresentation == null && value !=null) { + toscaPresentation = new HashMap(); + } + toscaPresentation.put(name.getPresentation(), value); + + } + public void setOwnerIdIfEmpty(String ownerId){ + if ( getOwnerId() == null ){ + setOwnerId(ownerId); + } + } + public void setOwnerId(String ownerId){ + setToscaPresentationValue(JsonPresentationFields.OWNER_ID, ownerId); + } + + public String getOwnerId(){ + return (String) getToscaPresentationValue(JsonPresentationFields.OWNER_ID); + } + + + //default merge function for merging data maps - implement where needed and use mergeDataMaps method where applicable instead of map1.putAll(map2) + public T mergeFunction(T other, boolean allowDefaultValueOverride){ + other.setOwnerId(getOwnerId()); + return other; + } + + public static Either, String> mergeDataMaps(Map map1, Map map2){ + return mergeDataMaps(map1, map2, false); + } + + //return Either.right(item key) if an illegal merge was attempted (overriding data type is forbidden) + public static Either, String> mergeDataMaps(Map map1, Map map2, boolean allowDefaultValueOverride){ + for(Entry entry : map2.entrySet()){ + map1.merge(entry.getKey(), entry.getValue(), (item1, item2) -> item1.mergeFunction(item2, allowDefaultValueOverride)); + //validate merge success + if(!map1.containsKey(entry.getKey())) + return Either.right(entry.getKey()); + } + return Either.left(map1); + } + + public static Map listToMapByName(List dataList) { + return null == dataList? new HashMap<>() : dataList.stream() + .collect(Collectors.toMap(p -> (String)p.getToscaPresentationValue(JsonPresentationFields.NAME), p -> p)); + } +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/execute/setup/DriverFactory.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/execute/setup/DriverFactory.java new file mode 100644 index 000000000..e8c386bb2 --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/execute/setup/DriverFactory.java @@ -0,0 +1,132 @@ +/*- + * ============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.onap.sdc.ci.tests.execute.setup; + + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FilenameFilter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; + +import org.apache.commons.io.FileUtils; +import org.onap.sdc.ci.tests.datatypes.Configuration; +import org.onap.sdc.ci.tests.datatypes.UserCredentials; +import org.onap.sdc.ci.tests.utilities.FileHandling; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.firefox.FirefoxProfile; +import org.testng.annotations.AfterSuite; +import org.testng.annotations.BeforeSuite; + + +public abstract class DriverFactory { + + private static ThreadLocal driverThread; + private static List webDriverThreadPool = Collections.synchronizedList(new ArrayList()); + private static Configuration configuration; + private static final String GECKO_DRIVER_KEY = "webdriver.gecko.driver"; + + protected abstract UserCredentials getUserCredentials(); + protected abstract Configuration getEnvConfiguration(); + + public DriverFactory() { + + try { + configuration = getEnvConfiguration(); + + //Set geko driver path for firefox + if(configuration.getGeckoDriverPath() != null){ + System.setProperty(GECKO_DRIVER_KEY, configuration.getGeckoDriverPath()); + } else { + throw new RuntimeException("Gecko driver path is null. Make sure to provide path to the gecko driver executable"); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + @BeforeSuite(alwaysRun = true) + public static void instantiateDriverObject() { + + + File basePath = new File(FileHandling.getBasePath()); + File[] listFiles = basePath.listFiles(new FilenameFilter() { + + @Override + public boolean accept(File basePath, String name) { + return name.startsWith(WebDriverThread.AUTOMATION_DOWNLOAD_DIR); + } + }); + Arrays.asList(listFiles).forEach(e -> FileHandling.deleteDirectory(e.getAbsolutePath())); + + + + driverThread = new ThreadLocal() { + @Override + protected WebDriverThread initialValue() { + WebDriverThread webDriverThread = new WebDriverThread(configuration); + webDriverThreadPool.add(webDriverThread); + return webDriverThread; + } + }; + } + + public static WebDriver getDriver() throws Exception { + return driverThread.get().getDriver(); + } + + public static FirefoxProfile getDriverFirefoxProfile() throws Exception { + return driverThread.get().getFirefoxProfile(); + } + + @AfterSuite(alwaysRun = true) + public static void quitDriverAfterSuite() throws Exception { + for (WebDriverThread webDriverThread : webDriverThreadPool) { + if (webDriverThread.getDriver() != null) + webDriverThread.quitDriver(); + } + deleteDownloadDirs(); + } + + private static void deleteDownloadDirs() throws IOException { +// System.gc(); + HashMap windowMap = WindowTestManager.getWholeMap(); + for (WindowTest win : windowMap.values()){ + String downloadDirectory = win.getDownloadDirectory(); + FileUtils.deleteDirectory(new File(downloadDirectory)); + } + } + + public static void quitDriver() throws Exception{ + driverThread.get().quitDriver(); + driverThread.remove(); + WindowTestManager.removeWindowTest(); + } + public static Configuration getConfiguration() { + return configuration; + } + + +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/execute/setup/ExtentManager.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/execute/setup/ExtentManager.java new file mode 100644 index 000000000..c835648b5 --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/execute/setup/ExtentManager.java @@ -0,0 +1,177 @@ +/*- + * ============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.onap.sdc.ci.tests.execute.setup; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; + +import org.onap.sdc.ci.tests.datatypes.Configuration; +import org.onap.sdc.ci.tests.utilities.FileHandling; +import org.testng.ITestContext; + +import com.aventstack.extentreports.ExtentReports; +import com.aventstack.extentreports.reporter.ExtentHtmlReporter; +import com.aventstack.extentreports.reporter.ExtentXReporter; +import com.aventstack.extentreports.reporter.configuration.Protocol; +import com.aventstack.extentreports.reporter.configuration.Theme; + +public class ExtentManager { + + private static final String VERSIONS_INFO_FILE_NAME = "versions.info"; + private static ExtentReports extent; + private static ExtentHtmlReporter htmlReporter; + private static ExtentXReporter extentxReporter; + private static final String icon = "$(document).ready(function() {" +"\n"+ + "$('.brand-logo').html('').prepend(\"\").width(\"120px\").css(\"float\",\"left\").css(\"padding-left\",\"0\");$('.report-name').css(\"font-weight\",\"bold\");"+"\n"+ + "})"; + + public enum suiteNameXml { + + TESTNG_FAILED_XML_NAME("testng-failed.xml"); + + suiteNameXml(String value) { + this.value = value; + } + + private String value; + + public String getValue() { + return value; + } + + } + + public synchronized static ExtentReports setReporter(String filePath, String htmlFile, Boolean isAppend) throws Exception { + String dbIp = DriverFactory.getConfiguration().getReportDBhost(); + int dbPort = DriverFactory.getConfiguration().getReportDBport(); + + if (extent == null) { + extentxReporter = new ExtentXReporter(dbIp, dbPort); + extent = new ExtentReports(); + initAndSetExtentHtmlReporter(filePath, htmlFile, isAppend); + + if(extentxReporter.config().getReportObjectId() != null){ + setExtentXReporter(isAppend); + }else{ + extentxReporter.stop(); + } + } + return extent; + } + + public synchronized static void setExtentXReporter(Boolean isAppend){ + extentxReporter.setAppendExisting(isAppend); + extent.attachReporter(extentxReporter); + } + + public synchronized static void initAndSetExtentHtmlReporter(String filePath, String htmlFile, Boolean isAppend) throws Exception{ + htmlReporter = new ExtentHtmlReporter(filePath + htmlFile); + setConfiguration(htmlReporter); + htmlReporter.setAppendExisting(isAppend); + extent.attachReporter(htmlReporter); + } + + public synchronized static ExtentReports getReporter() { + return extent; + } + + public static void initReporter(Configuration config, ITestContext context) throws Exception { + String envData = config.getUrl(); + String suiteName = getSuiteName(context); + String filepath = config.getReportFolder(); + String htmlFile = config.getReportFileName(); + + if(suiteName.equals(suiteNameXml.TESTNG_FAILED_XML_NAME.getValue())){ + if (config.isUseBrowserMobProxy()){ + setTrafficCaptue(config); + } + + setReporter(filepath, htmlFile, true); + suiteName = FileHandling.getKeyByValueFromPropertyFormatFile(filepath + VERSIONS_INFO_FILE_NAME, "suiteName"); + }else{ + FileHandling.deleteDirectory(SetupCDTest.getReportFolder()); + FileHandling.createDirectory(filepath); + setReporter(filepath, htmlFile, false); + createVersionsInfoFile(filepath , VERSIONS_INFO_FILE_NAME, envData, suiteName); + } + reporterDataDefinition(envData, suiteName); + } + + private static void createVersionsInfoFile(String path, String file, String envData, String suiteName) throws FileNotFoundException, IOException { + File myFoo = new File(path + file); + FileOutputStream fooStream = new FileOutputStream(myFoo, false); // true to append + String versions = ("env=\""+ envData + "\"\n" + "suiteName=\""+ suiteName+ "\"\n"); + byte[] myBytes = versions.getBytes(); + fooStream.write(myBytes); + fooStream.close(); + } + + private static void reporterDataDefinition(String envData, String suiteNameFromVersionInfoFile) throws Exception { + extent.setSystemInfo("Host Name Address", FileHandling.getExecutionHostAddress()); + extent.setSystemInfo("ExecutedOn", envData); + extent.setSystemInfo("SuiteName", suiteNameFromVersionInfoFile); + } + + public static void reporterDataDefinition(HashMap addedSystemInfo){ + Iterator iterator = addedSystemInfo.keySet().iterator(); + while(iterator.hasNext()){ + String key = iterator.next(); + String value = addedSystemInfo.get(key); + extent.setSystemInfo(key, value); + } + } + + public static String getSuiteName(ITestContext context) { + String suitePath = context.getSuite().getXmlSuite().getFileName(); + if(suitePath != null){ + File file = new File(suitePath); + String suiteName = file.getName(); + return suiteName; + } + return null; + } + + public synchronized static ExtentHtmlReporter setConfiguration(ExtentHtmlReporter htmlReporter) throws Exception { + + htmlReporter.config().setTheme(Theme.STANDARD); + htmlReporter.config().setEncoding("UTF-8"); + htmlReporter.config().setProtocol(Protocol.HTTPS); + htmlReporter.config().setDocumentTitle("Automation Report"); + htmlReporter.config().setChartVisibilityOnOpen(true); + htmlReporter.config().setReportName("Automation Report"); + htmlReporter.config().setChartVisibilityOnOpen(false); + htmlReporter.config().setJS(icon); + return htmlReporter; + } + + public static void closeReporter(){ + extent.flush(); + } + + public static void setTrafficCaptue(Configuration config) { + config.setCaptureTraffic(true); + } +} + diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/execute/setup/ExtentTestActions.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/execute/setup/ExtentTestActions.java new file mode 100644 index 000000000..e5eac5e24 --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/execute/setup/ExtentTestActions.java @@ -0,0 +1,114 @@ +/*- + * ============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.onap.sdc.ci.tests.execute.setup; + +import java.io.File; +import java.io.IOException; +import java.util.UUID; + +import org.onap.sdc.ci.tests.utilities.GeneralUIUtils; + +import com.aventstack.extentreports.ExtentTest; +import com.aventstack.extentreports.MediaEntityBuilder; +import com.aventstack.extentreports.Status; +import com.aventstack.extentreports.markuputils.ExtentColor; +import com.aventstack.extentreports.markuputils.Markup; +import com.aventstack.extentreports.markuputils.MarkupHelper; + +public class ExtentTestActions { + + public static void log(Status logStatus, Markup mark){ + ExtentTest test = ExtentTestManager.getTest(); + test.log(logStatus, mark); + } + + public static void log(Status logStatus, String message){ + ExtentTest test = ExtentTestManager.getTest(); + test.log(logStatus, message); + } + + public static void log(Status logStatus, String message, String duration){ + log(logStatus, message + addDurationTag(duration)); + } + + public static void log(Status logStatus, Throwable throwabel){ + ExtentTest test = ExtentTestManager.getTest(); + test.log(logStatus, throwabel); + } + + public static void addTag(Status logStatus, String message){ + Markup m = null; + switch(logStatus){ + case PASS: + m = MarkupHelper.createLabel(message, ExtentColor.GREEN); + break; + case FAIL: + m = MarkupHelper.createLabel(message, ExtentColor.RED); + break; + case SKIP: + m = MarkupHelper.createLabel(message, ExtentColor.BLUE); + break; + case FATAL: + m = MarkupHelper.createLabel(message, ExtentColor.BROWN); + break; + default: + break; + } + + if (m != null){ + log(logStatus, m); + } + } + + public static String addScreenshot(Status logStatus, String screenshotName, String message) throws IOException{ + String imageFilePath = null; + String uuid = UUID.randomUUID().toString(); + String[] stringArray = uuid.split("-"); + screenshotName = screenshotName + "-" + stringArray[stringArray.length - 1]; + try { + File imageFile = GeneralUIUtils.takeScreenshot(screenshotName, SetupCDTest.getScreenshotFolder()); + imageFilePath = new File(SetupCDTest.getReportFolder()).toURI().relativize(imageFile.toURI()).getPath(); + } catch (IOException e) { + e.printStackTrace(); + } + + ExtentTest test = ExtentTestManager.getTest(); + test.log(logStatus, message, MediaEntityBuilder.createScreenCaptureFromPath(imageFilePath).build()); + return imageFilePath; + } + + private static String addDurationTag(String duration){ + return "" + duration + ""; + } + + public static String addLinkTag(String fileName, String pathToFile){ + return String.format("HAR file", fileName, pathToFile); + } + + public static void addFileToReportAsLink(File harFile, String pathToFileFromReportDirectory, String message) { + log(Status.INFO, message, addLinkTag(harFile.getName(), pathToFileFromReportDirectory)); + } + + + + + +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/execute/setup/ExtentTestManager.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/execute/setup/ExtentTestManager.java new file mode 100644 index 000000000..faecb815e --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/execute/setup/ExtentTestManager.java @@ -0,0 +1,60 @@ +/*- + * ============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.onap.sdc.ci.tests.execute.setup; + +import java.util.HashMap; + +import com.aventstack.extentreports.ExtentReports; +import com.aventstack.extentreports.ExtentTest; + +public class ExtentTestManager { + + private static HashMap extentTestMap = new HashMap(); + private static ExtentReports extent = ExtentManager.getReporter(); + + public static synchronized ExtentTest getTest() { + return extentTestMap.get(Thread.currentThread().getId()); + } + + public static synchronized void endTest() { +// extent.endTest(extentTestMap.get(Thread.currentThread().getId())); + extent.flush(); + } + + public static synchronized ExtentTest startTest(String testName) { + return startTest(testName, ""); + } + + public static synchronized ExtentTest startTest(String testName, String desc) { + ExtentTest test = extent.createTest(testName, desc); + extentTestMap.put(Thread.currentThread().getId(), test); + + return test; + } + + public static synchronized void assignCategory(Class clazz){ + String[] parts = clazz.getName().split("\\."); + String lastOne1 = parts[parts.length-1]; + String lastOne2 = parts[parts.length-2]; + getTest().assignCategory(lastOne2 + "-" + lastOne1); + } +} + diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/execute/setup/MobProxy.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/execute/setup/MobProxy.java new file mode 100644 index 000000000..a2d427bc6 --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/execute/setup/MobProxy.java @@ -0,0 +1,103 @@ +package org.onap.sdc.ci.tests.execute.setup; + +import java.net.InetSocketAddress; +import java.net.Proxy; +import java.net.ProxySelector; +import java.net.SocketAddress; +import java.net.URI; +import java.util.HashMap; +import java.util.List; +import java.util.stream.Collectors; + +import org.slf4j.LoggerFactory; + +import com.aventstack.extentreports.ExtentTest; +import com.github.markusbernhardt.proxy.ProxySearch; +import com.github.markusbernhardt.proxy.ProxySearch.Strategy; +import com.github.markusbernhardt.proxy.util.PlatformUtil; +import com.github.markusbernhardt.proxy.util.PlatformUtil.Platform; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.LoggerContext; +import net.lightbody.bmp.BrowserMobProxyServer; + +public class MobProxy { + + private static HashMap mobProxyServerMap = new HashMap(); + public static InetSocketAddress localProxyAddress = getProxy(); + + public static InetSocketAddress getProxy(){ + setLogger(); + + ProxySearch proxySearch = new ProxySearch(); +// proxySearch.addStrategy(Strategy.JAVA); +// proxySearch.addStrategy(Strategy.BROWSER); +// proxySearch.addStrategy(Strategy.OS_DEFAULT); +// proxySearch.addStrategy(Strategy.ENV_VAR); + if (PlatformUtil.getCurrentPlattform() == Platform.WIN) { + proxySearch.addStrategy(Strategy.IE); + proxySearch.addStrategy(Strategy.FIREFOX); + proxySearch.addStrategy(Strategy.JAVA); + } else if (PlatformUtil.getCurrentPlattform() == Platform.LINUX) { + proxySearch.addStrategy(Strategy.GNOME); + proxySearch.addStrategy(Strategy.KDE); + proxySearch.addStrategy(Strategy.FIREFOX); + proxySearch.addStrategy(Strategy.ENV_VAR); + return null; + } else { + proxySearch.addStrategy(Strategy.OS_DEFAULT); + } + ProxySelector proxySelector = proxySearch.getProxySelector(); + + ProxySelector.setDefault(proxySelector); + URI home = URI.create("http://www.google.com"); + System.out.println("ProxySelector: " + proxySelector); + System.out.println("URI: " + home); + List proxyList = proxySelector.select(home); + String host = null; + String port = null; + if (proxyList != null && !proxyList.isEmpty()) { + for (Proxy proxy : proxyList) { + System.out.println(proxy); + SocketAddress address = proxy.address(); + if (address instanceof InetSocketAddress) { + host = ((InetSocketAddress) address).getHostName(); + port = Integer.toString(((InetSocketAddress) address).getPort()); + System.setProperty("http.proxyHost", host); + System.setProperty("http.proxyPort", port); + } + } + } + InetSocketAddress address = new InetSocketAddress(host, Integer.parseInt(port)); + return address; + } + + // set logger for all classes connected to MobProxy + public static void setLogger() { + LoggerContext lc = (LoggerContext) LoggerFactory. getILoggerFactory(); +// lc.getLogger("ROOT").setLevel(Level.DEBUG); + for(Logger logger:lc.getLoggerList()){ + logger.setLevel(Level.INFO); + } + } + + public static synchronized void setProxyServer() { + BrowserMobProxyServer server = new BrowserMobProxyServer(); + server.setTrustAllServers(true); + if (localProxyAddress != null){ + server.setChainedProxy(localProxyAddress); + server.start(); + } else { + server.start(); + // filter firefox requests to mozilla when system proxy is absent + server.blacklistRequests(".*mozilla.*", 200); + } + mobProxyServerMap.put(Thread.currentThread().getId(), server); + } + + public static synchronized BrowserMobProxyServer getPoxyServer() { + return mobProxyServerMap.get(Thread.currentThread().getId()); + } + +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/execute/setup/OnboardCSVReport.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/execute/setup/OnboardCSVReport.java new file mode 100644 index 000000000..c64edff21 --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/execute/setup/OnboardCSVReport.java @@ -0,0 +1,63 @@ +/*- + * ============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.onap.sdc.ci.tests.execute.setup; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.PrintWriter; + +public class OnboardCSVReport { + + private StringBuilder sb; + private PrintWriter pw; + + public OnboardCSVReport(String filepath, String filename) { + sb = new StringBuilder(); + try { + File csvFile = new File(filepath + filename); + pw = new PrintWriter(csvFile); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + + } + + public StringBuilder appendStringToFile(String content) { + return sb.append(content + ","); + } + + public void openNewRow() { + sb.append("\n"); + } + + public void writeRow(String... content) { + for (String str : content) { + appendStringToFile(str); + } + openNewRow(); + } + + public void closeFile() { + pw.write(sb.toString()); + pw.close(); + } + +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/execute/setup/ReportAfterTestManager.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/execute/setup/ReportAfterTestManager.java new file mode 100644 index 000000000..ee16ddc76 --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/execute/setup/ReportAfterTestManager.java @@ -0,0 +1,129 @@ +/*- + * ============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.onap.sdc.ci.tests.execute.setup; + +import java.io.IOException; + +import org.onap.sdc.ci.tests.execute.setup.ExtentManager.suiteNameXml; +import org.testng.ITestContext; +import org.testng.ITestResult; + +import com.aventstack.extentreports.Status; + +public class ReportAfterTestManager extends ExtentTestActions { + + private static String testName; + private static Throwable throwable; + private static int status; + + private static void logSuccessAfterTest(){ + final Status logStatus = Status.PASS; + addTag(logStatus, "Success"); + try{ + String message = "Finished the test with the following screenshot : "; + addScreenshotToReport(logStatus, testName, message); + }catch(Exception e){ + log(logStatus, "SUCCESS - The following exepction occured : " + e.getMessage()); + } + } + + private static void logFailAfterTest(){ + addTag(Status.FAIL, "Failure"); + try{ + log(Status.ERROR, "ERROR - The following exepction occured : "); + log(Status.ERROR, throwable); + String message = "Failure is described in the following screenshot : "; + addScreenshotToReport(Status.FAIL, testName, message); + }catch(Exception e){ + log(Status.ERROR, "ERROR - The following exepction occured : " + e.getMessage()); + } + } + + private static void logSkipAfterTest(){ + final Status logStatus = Status.SKIP; + addTag(logStatus, "Skipped"); + try{ + log(logStatus, "SKIP - The following exepction occured : "); + log(logStatus, throwable); + String message = "Skip is described in the following screenshot : "; + addScreenshotToReport(logStatus, testName, message); + }catch(Exception e){ + log(logStatus, "SKIP - The following exepction occured : " + e.getMessage()); + } + } + private static void logFatalAfterTest(){ + final Status logStatus = Status.FATAL; + addTag(logStatus, "Fatal"); + try{ + log(logStatus, "FATAL - The following exepction occured : "); + log(logStatus, throwable); + String message = "Fatal is described in the following screenshot : "; + addScreenshotToReport(logStatus, testName, message); + }catch(Exception e){ + log(logStatus, "FATAL - The following exepction occured : " + e.getMessage()); + } + } + + private static String addScreenshotToReport(Status logStatus, String testName, String message) throws IOException{ + + String addedValueFromDataProvider = WindowTestManager.getWindowMap().getAddedValueFromDataProvider(); + if (addedValueFromDataProvider != null){ + addedValueFromDataProvider = addedValueFromDataProvider.replace(":", "-"); + testName = testName + "...." + addedValueFromDataProvider; + } + + return addScreenshot(logStatus, testName, message); + } + + public static void report(ITestResult result, ITestContext context){ + + testName = result.getName(); + throwable = result.getThrowable(); + status = result.getStatus(); + + String suiteName = ExtentManager.getSuiteName(context); + + switch(status){ + case ITestResult.SUCCESS: + logSuccessAfterTest(); + break; + + case ITestResult.FAILURE: + + if (suiteName.equals(suiteNameXml.TESTNG_FAILED_XML_NAME.getValue())) { + logFatalAfterTest(); + }else{ + logFailAfterTest(); + } + break; + + case ITestResult.SKIP: + logSkipAfterTest(); + break; + + default: + break; + } + + } + +} + diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/execute/setup/Retry.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/execute/setup/Retry.java new file mode 100644 index 000000000..b74ef14da --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/execute/setup/Retry.java @@ -0,0 +1,44 @@ +/*- + * ============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.onap.sdc.ci.tests.execute.setup; + +import org.testng.Assert; +import org.testng.IRetryAnalyzer; +import org.testng.ITestResult; +import org.testng.annotations.Test; + +public class Retry implements IRetryAnalyzer { + private int retryCount = 0; + private int maxRetryCount = 1; + + public boolean retry(ITestResult result) { + + if (retryCount < maxRetryCount) { + retryCount++; + return true; + } + return false; + } + + + + +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/execute/setup/SetupCDTest.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/execute/setup/SetupCDTest.java new file mode 100644 index 000000000..bb6a19a36 --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/execute/setup/SetupCDTest.java @@ -0,0 +1,356 @@ +/*- + * ============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.onap.sdc.ci.tests.execute.setup; + +import java.io.File; +import java.io.IOException; +import java.util.UUID; + +import org.onap.sdc.ci.tests.datatypes.Configuration; +import org.onap.sdc.ci.tests.datatypes.User; +import org.onap.sdc.ci.tests.datatypes.UserCredentials; +import org.onap.sdc.ci.tests.datatypes.UserRoleEnum; +import org.onap.sdc.ci.tests.execute.setup.ExtentManager.suiteNameXml; +import org.onap.sdc.ci.tests.run.StartTest; +import org.onap.sdc.ci.tests.utilities.FileHandling; +import org.onap.sdc.ci.tests.utilities.GeneralUIUtils; +import org.openqa.selenium.By; +import org.openqa.selenium.JavascriptExecutor; +import org.openqa.selenium.WebElement; +import org.testng.Assert; +import org.testng.ITestContext; +import org.testng.ITestResult; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.AfterSuite; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.BeforeSuite; +import org.testng.annotations.Test; + +import com.aventstack.extentreports.ExtentTest; +import com.aventstack.extentreports.Status; + +import net.lightbody.bmp.core.har.Har; + +public abstract class SetupCDTest extends DriverFactory { + + private static final String RE_RUN = "ReRun - "; + + /**************** PRIVATES ****************/ + private static String url; + + protected static ITestContext myContext; + + /**************** METHODS ****************/ + public static ExtentTest getExtendTest() { + return ExtentTestManager.getTest(); + } + + public static WindowTest getWindowTest() { + return WindowTestManager.getWindowMap(); + } + + public static String getScreenshotFolder() { + return getConfiguration().getScreenshotFolder(); + } + + public static String getHarFilesFolder() { + return getConfiguration().getHarFilesFolder(); + } + + public static String getReportFolder(){ + return getConfiguration().getReportFolder(); + } + + public static String getReportFilename(){ + return getConfiguration().getReportFileName(); + } + + protected abstract UserCredentials getUserCredentials(); + protected abstract Configuration getEnvConfiguration(); + protected abstract void loginToLocalSimulator(UserCredentials userCredentials); + + + + /**************** BEFORE ****************/ + + @BeforeSuite(alwaysRun = true) + public void setupBeforeSuite(ITestContext context) throws Exception { + setUrl(); + initReport(context); + } + + private void initReport(ITestContext context) throws Exception { + myContext = context; + ExtentManager.initReporter(getConfiguration(), context); + } + + @BeforeMethod(alwaysRun = true) + public void setBrowserBeforeTest(java.lang.reflect.Method method, ITestContext context) throws Exception { + boolean emptyDataProvider = isDataProviderEmpty(method); + if (emptyDataProvider) { + System.out.println("ExtentReport instance started from BeforeMethod..."); + String suiteName = ExtentManager.getSuiteName(context); + if (suiteName.equals(suiteNameXml.TESTNG_FAILED_XML_NAME.getValue())) { + ExtentTestManager.startTest(RE_RUN + method.getName()); + } else { + ExtentTestManager.startTest(method.getName()); + } + + ExtentTestManager.assignCategory(this.getClass()); + setBrowserBeforeTest(getUserCredentials()); + } else { + System.out.println("ExtentReport instance started from Test..."); + } + + getConfiguration().setWindowsDownloadDirectory(getWindowTest().getDownloadDirectory()); + + if (getConfiguration().isCaptureTraffic()) { + try { + MobProxy.getPoxyServer().newHar(method.getName() + ".har"); + } catch (Throwable e) { + e.printStackTrace(); + } + } + } + + private boolean isDataProviderEmpty(java.lang.reflect.Method method) { + return method.getAnnotation(Test.class).dataProvider().isEmpty(); + } + + /**************** AFTER ****************/ + @AfterMethod(alwaysRun = true) + public void quitAfterTest(ITestResult result, ITestContext context) throws Exception { + + try { + ReportAfterTestManager.report(result, context); + GeneralUIUtils.closeErrorMessage(); + } finally { + + if (getConfiguration().isCaptureTraffic()) { +// addTrafficFileToReport(result); + } + + ExtentTestManager.endTest(); + ExtentManager.closeReporter(); + FileHandling.cleanCurrentDownloadDir(); + } + + } + + @AfterSuite(alwaysRun = true) + public void afterSuite() throws Exception { + if (getConfiguration().isUseBrowserMobProxy()) { + MobProxy.getPoxyServer().stop(); + } + } + + protected static String setUrl() { + url = getConfiguration().getUrl(); + if (url == null) { + String message = "no URL found"; + System.out.println(message); + Assert.fail(message); + } + return url; + } + + public static void navigateToUrl(String url) throws Exception { + try { + System.out.println("Deleting cookies..."); + deleteCookies(); + + System.out.println("Navigating to URL : " + url); + getDriver().navigate().to(url); + GeneralUIUtils.waitForLoader(); + + System.out.println("Zooming out..."); + GeneralUIUtils.windowZoomOutUltimate(); + + } catch (Exception e) { + String msg = "Browser is unreachable"; + System.out.println(msg); + e.printStackTrace(); + getExtendTest().log(Status.ERROR, msg); + Assert.fail(msg); + } + } + + private static void deleteCookies() throws Exception { + getDriver().manage().deleteAllCookies(); + Thread.sleep(1000); + + int attempts = 0; + final int max_attempts = 3; + + while (!getDriver().manage().getCookies().isEmpty() && attempts < max_attempts) { + getExtendTest().log(Status.INFO, + "Trying to delete cookies one more time - " + (attempts + 1) + "/" + max_attempts + "attempts"); + String deleteCookiesJS = "document.cookie.split(';').forEach(function(c) { document.cookie = c.replace(/^ +/, '').replace(/=.*/, '=;expires=' + new Date().toUTCString() + ';path=/'); });"; + ((JavascriptExecutor) getDriver()).executeScript(deleteCookiesJS); + attempts++; + + if (attempts == max_attempts) { + String msg = "Did not delete cookies, can't login with the userId " + + WindowTestManager.getWindowMap().getUserCredentials().getUserId(); + System.out.println(msg); + getExtendTest().log(Status.ERROR, msg); + Assert.fail(msg); + } + } + } + + protected void loginToSystem(UserCredentials userCredentials) throws Exception { + if (getConfiguration().isUseCustomLogin()) { + loginToLocalSimulator(userCredentials); + } + else { + sendUserAndPasswordKeys(userCredentials); + WebElement submitButton = GeneralUIUtils.getWebElementBy(By.name("btnSubmit"), 30); + submitButton.click(); + WebElement buttonOK = GeneralUIUtils.getWebElementBy(By.name("successOK"), 30); + Assert.assertTrue(buttonOK.isDisplayed(), "OK button is not displayed."); + buttonOK.click(); + } + GeneralUIUtils.ultimateWait(); + getWindowTest().setUserCredentials(userCredentials); + } + + private void setRefreshAttempts(int refreshAttempts) { + getWindowTest().setRefreshAttempts(refreshAttempts); + } + + private void sendUserAndPasswordKeys(UserCredentials userCredentials) { + System.out.println("Login with the userId : " + userCredentials.getUserId()); + WebElement userNameTextbox = GeneralUIUtils.getWebElementBy(By.name("userid")); + userNameTextbox.sendKeys(userCredentials.getUserId()); + WebElement passwordTextbox = GeneralUIUtils.getWebElementBy(By.name("password")); + passwordTextbox.sendKeys(userCredentials.getPassword()); + } + + public void loginWithUser(UserCredentials userCredentials) { + try { + getExtendTest().log(Status.INFO, String.format("Login with the userId %s", userCredentials.getUserId())); + loginToSystem(userCredentials); + } catch (Exception e) { + throw new RuntimeException(e); + } finally { + getWindowTest().setPreviousUser(getWindowTest().getUserCredentials().getUserId()); + } + } + + private void setUser(UserCredentials userCredentials) { + User user = new User(); + user.setUserId(userCredentials.getUserId()); + user.setFirstName(userCredentials.getFirstName()); + user.setRole(userCredentials.getRole()); + user.setLastName(userCredentials.getLastName()); + getWindowTest().setUserCredentials(userCredentials); + } + + public User getUser() { + return getWindowTest().getUserCredentials(); + } + + private void setBrowserBeforeTest(UserCredentials userCredentials) { + System.out.println(String.format("Setup before test with the userId %s.", userCredentials.getUserId())); + try { + System.out.println("Previous userId is : " + getWindowTest().getPreviousUser() + " ; Current userId is : " + userCredentials.getUserId()); + if (!getWindowTest().getPreviousUser().toLowerCase().equals(userCredentials.getUserId())) { + System.out.println("User IDs are different. navigating and login."); + navigateAndLogin(userCredentials); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + public void navigateAndLogin(UserCredentials userCredentials) throws Exception { + int refreshAttempts = getWindowTest().getRefreshAttempts() != 0 ? getWindowTest().getRefreshAttempts() : 0; + setRefreshAttempts(refreshAttempts); + setUser(userCredentials); + navigateToUrl(url); + loginWithUser(userCredentials); + GeneralUIUtils.ultimateWait(); + } + + public User getUser(UserRoleEnum role) { + User user = new User(); + user.setUserId(role.getUserId()); + user.setFirstName(role.getFirstName()); + user.setLastName(role.getLastName()); + user.setRole(role.name()); + return user; + } + + protected void reloginWithNewRole(UserCredentials userCredentials) throws Exception { + System.out.println(String.format("Setup before relogin with the userId %s", userCredentials.getUserId())); + navigateAndLogin(userCredentials); + } + + public void addTrafficFileToReport(ITestResult result) { + try { + // Get the HAR data + Har har = MobProxy.getPoxyServer().getHar(); + String shortUUID = UUID.randomUUID().toString().split("-")[0]; + File harFile = new File(getHarFilesFolder() + result.getName() + shortUUID + ".har"); + new File(getHarFilesFolder()).mkdirs(); + + har.writeTo(harFile); + + String pathToFileFromReportDirectory = getReportFolder() + File.separator + harFile.getName(); + ExtentTestActions.addFileToReportAsLink(harFile, pathToFileFromReportDirectory, + "File with captured traffic"); + } catch (IOException ioe) { + ioe.printStackTrace(); + } + } + + /* + * * Start section of test in ExtentReport with DataProvider parameters, + * should be started from test method, see example in onboardVNFTest + */ + public void setLog(String fromDataProvider) { + + String suiteName = ExtentManager.getSuiteName(myContext); + if (suiteName.equals(suiteNameXml.TESTNG_FAILED_XML_NAME.getValue())) { + ExtentTestManager.startTest(RE_RUN + Thread.currentThread().getStackTrace()[2].getMethodName() + + "      " + fromDataProvider); + } else { + ExtentTestManager.startTest(Thread.currentThread().getStackTrace()[2].getMethodName() + + "      " + fromDataProvider); + } + + getWindowTest().setAddedValueFromDataProvider(fromDataProvider); + ExtentTestManager.assignCategory(this.getClass()); + setBrowserBeforeTest(getUserCredentials()); + } + + public static void main(String[] args) { + System.out.println("---------------------"); + System.out.println("running test from CLI"); + System.out.println("---------------------"); + + String testSuite = System.getProperty("testSuite"); + String[] testSuiteArr = {testSuite}; + StartTest.main(testSuiteArr); + } + +} \ No newline at end of file diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/execute/setup/WebDriverThread.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/execute/setup/WebDriverThread.java new file mode 100644 index 000000000..501faa8de --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/execute/setup/WebDriverThread.java @@ -0,0 +1,177 @@ +/*- + * ============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.onap.sdc.ci.tests.execute.setup; + +import java.io.File; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.UUID; +import net.lightbody.bmp.BrowserMobProxyServer; +import net.lightbody.bmp.client.ClientUtil; +import net.lightbody.bmp.proxy.CaptureType; +import org.onap.sdc.ci.tests.datatypes.Configuration; +import org.onap.sdc.ci.tests.utilities.FileHandling; +import org.openqa.selenium.Capabilities; +import org.openqa.selenium.Dimension; +import org.openqa.selenium.Platform; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.firefox.FirefoxDriver; +import org.openqa.selenium.firefox.FirefoxOptions; +import org.openqa.selenium.firefox.FirefoxProfile; +import org.openqa.selenium.remote.CapabilityType; +import org.openqa.selenium.remote.LocalFileDetector; +import org.openqa.selenium.remote.RemoteWebDriver; + +public class WebDriverThread { + + public static final String AUTOMATION_DOWNLOAD_DIR = "automationDownloadDir"; + private WebDriver webdriver; + private FirefoxProfile firefoxProfile; + public static final String SELENIUM_NODE_URL = "http://%s:%s/wd/hub"; + public static final String MARIONETTE_CAPABILITY= "marionette"; + + public WebDriverThread(Configuration config) { + initDriver(config); + if (isHeadless()) { + webdriver.manage().window().setSize(new Dimension(1920, 1080)); + } else { + webdriver.manage().window().maximize(); + } + } + + private boolean isHeadless() { + if (webdriver instanceof RemoteWebDriver) { + Capabilities capabilities = ((RemoteWebDriver) webdriver).getCapabilities(); + Object headless = capabilities.getCapability("moz:headless"); + return Boolean.TRUE == headless; + } else { + return false; + } + } + + public WebDriver getDriver() throws Exception { + return webdriver; + } + + public void quitDriver() { + if (webdriver != null) { + webdriver.quit(); + webdriver = null; + } + } + + + public void initDriver(Configuration config){ + try { + boolean remoteTesting = config.isRemoteTesting(); + if (!remoteTesting) { + boolean mobProxyStatus = config.isUseBrowserMobProxy(); + if (mobProxyStatus){ + setWebDriverWithMobProxy(); + } else { + System.out.println("Opening LOCAL browser"); + FirefoxOptions cap = new FirefoxOptions(); + + cap.setCapability("browserName","firefox"); + cap.setCapability(FirefoxDriver.PROFILE, initFirefoxProfile()); + cap.setCapability(MARIONETTE_CAPABILITY, true); + + firefoxProfile.setPreference("network.proxy.type", 2); + firefoxProfile.setPreference("network.proxy.autoconfig_url", "http://emea.onap.org:8001/"); + firefoxProfile.setPreference("network.proxy.no_proxies_on", "localhost"); + + webdriver = new FirefoxDriver(cap); + } + } else { + System.out.println("Opening REMOTE browser"); + String remoteEnvIP = config.getRemoteTestingMachineIP(); + int remoteEnvPort = config.getRemoteTestingMachinePort(); + + FirefoxOptions cap = new FirefoxOptions(); + cap.setCapability("platform",Platform.ANY); + cap.setCapability("browserName","firefox"); + cap.setCapability(MARIONETTE_CAPABILITY, true); + + String remoteNodeUrl = String.format(SELENIUM_NODE_URL, remoteEnvIP, remoteEnvPort); + RemoteWebDriver remoteWebDriver = new RemoteWebDriver(new URL(remoteNodeUrl), cap); + remoteWebDriver.setFileDetector(new LocalFileDetector()); + webdriver = remoteWebDriver; + } + + + } catch (MalformedURLException e) { + throw new RuntimeException(e); + } + } + + private FirefoxProfile initFirefoxProfile() { + firefoxProfile = new FirefoxProfile(); + firefoxProfile.setPreference("browser.download.folderList",2); + firefoxProfile.setPreference("browser.download.manager.showWhenStarting",false); + firefoxProfile.setPreference("browser.download.dir", getDownloadDirectory()); + firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk","application/octet-stream, application/xml, text/plain, text/xml, image/jpeg"); + return firefoxProfile; + } + + private String getDownloadDirectory() { + String downloadDirectory = FileHandling.getBasePath() + File.separator + AUTOMATION_DOWNLOAD_DIR + UUID.randomUUID().toString().split("-")[0] + File.separator; + File dir = new File(downloadDirectory); + if(!dir.exists()) { + dir.mkdirs(); + } + return dir.getAbsolutePath(); + } + + public FirefoxProfile getFirefoxProfile() { + return firefoxProfile; + } + + private void setWebDriverWithMobProxy(){ + MobProxy.setProxyServer(); + BrowserMobProxyServer proxyServer = MobProxy.getPoxyServer(); + + firefoxProfile = new FirefoxProfile(); + firefoxProfile.setPreference("browser.download.folderList",2); + firefoxProfile.setPreference("browser.download.manager.showWhenStarting",false); + firefoxProfile.setPreference("browser.download.dir", getDownloadDirectory()); + firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk","application/octet-stream, application/xml, text/plain, text/xml, image/jpeg"); + firefoxProfile.setAcceptUntrustedCertificates(true); + firefoxProfile.setAssumeUntrustedCertificateIssuer(true); +// firefoxProfile.setPreference("network.proxy.http", "localhost"); +// firefoxProfile.setPreference("network.proxy.http_port", proxyServer.getPort()); +// firefoxProfile.setPreference("network.proxy.ssl", "localhost"); +// firefoxProfile.setPreference("network.proxy.ssl_port", proxyServer.getPort()); +// firefoxProfile.setPreference("network.proxy.type", 1); +// firefoxProfile.setPreference("network.proxy.no_proxies_on", ""); + + FirefoxOptions capabilities = new FirefoxOptions(); + + capabilities.setCapability(FirefoxDriver.PROFILE, firefoxProfile); + capabilities.setCapability(CapabilityType.PROXY, ClientUtil.createSeleniumProxy(proxyServer)); + capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true); + capabilities.setCapability(MARIONETTE_CAPABILITY, true); + + webdriver = new FirefoxDriver(capabilities); + proxyServer.enableHarCaptureTypes(CaptureType.REQUEST_CONTENT, CaptureType.RESPONSE_CONTENT, CaptureType.REQUEST_COOKIES, CaptureType.REQUEST_BINARY_CONTENT, + CaptureType.REQUEST_HEADERS, CaptureType.RESPONSE_COOKIES, CaptureType.RESPONSE_HEADERS, CaptureType.RESPONSE_BINARY_CONTENT); + } + +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/execute/setup/WindowTest.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/execute/setup/WindowTest.java new file mode 100644 index 000000000..1fb3b188b --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/execute/setup/WindowTest.java @@ -0,0 +1,84 @@ +/*- + * ============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.onap.sdc.ci.tests.execute.setup; + +import java.io.File; + +import org.onap.sdc.ci.tests.datatypes.User; +import org.onap.sdc.ci.tests.datatypes.UserCredentials; + +public class WindowTest { + + + + public WindowTest(){ + refreshAttempts = 0; + previousUser = ""; + addedValueFromDataProvider = null; + try { + downloadDirectory = DriverFactory.getDriverFirefoxProfile().getStringPreference("browser.download.dir", null) + File.separator; + } catch (Exception e) { + e.printStackTrace(); + } + } + + private int refreshAttempts; + private String addedValueFromDataProvider; + private String downloadDirectory; + private UserCredentials userCredentials; + private String previousUser; + + public int getRefreshAttempts() { + return refreshAttempts; + } + public void setRefreshAttempts(int refreshAttempts) { + this.refreshAttempts = refreshAttempts; + } + public synchronized String getAddedValueFromDataProvider() { + return addedValueFromDataProvider; + } + public synchronized void setAddedValueFromDataProvider(String addedValueFromDataProvider) { + this.addedValueFromDataProvider = addedValueFromDataProvider; + } + public String getDownloadDirectory() { + return downloadDirectory; + } + public void setDownloadDirectory(String downloadDirectory) { + this.downloadDirectory = downloadDirectory; + } + public UserCredentials getUserCredentials() { + return userCredentials; + } + public void setUserCredentials(UserCredentials userCredentials) { + this.userCredentials = userCredentials; + } + + public void setUserCredentials(User user) { + this.userCredentials = new UserCredentials(user); + } + public String getPreviousUser() { + return previousUser; + } + public void setPreviousUser(String previousUser) { + this.previousUser = previousUser; + } + +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/execute/setup/WindowTestManager.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/execute/setup/WindowTestManager.java new file mode 100644 index 000000000..727876f27 --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/execute/setup/WindowTestManager.java @@ -0,0 +1,52 @@ +/*- + * ============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.onap.sdc.ci.tests.execute.setup; + +import java.util.HashMap; + +import com.aventstack.extentreports.ExtentTest; + +public class WindowTestManager { + + private static HashMap windowMap = new HashMap(); + + public static synchronized WindowTest getWindowMap() { + Long currentThreadId = Thread.currentThread().getId(); + boolean containsKey = windowMap.containsKey(currentThreadId); + if (!containsKey){ + setWindowMap(currentThreadId); + } + return windowMap.get(currentThreadId); + } + + private static synchronized void setWindowMap(Long currentThreadId) { + WindowTestManager.windowMap.put(currentThreadId, new WindowTest()); + } + + public static synchronized void removeWindowTest(){ + windowMap.remove(Thread.currentThread().getId()); + } + + public static synchronized HashMap getWholeMap(){ + return windowMap; + } + +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/run/RunTest.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/run/RunTest.java new file mode 100644 index 000000000..a3f88e23b --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/run/RunTest.java @@ -0,0 +1,25 @@ +package org.onap.sdc.ci.tests.run; + +import java.util.ArrayList; +import java.util.List; + +import org.testng.TestNG; + +public class RunTest { + + public static void runTestSuite() { + TestNG testng = new TestNG(); + List suites = new ArrayList(); + + String testSuite = System.getProperty("testSuite"); + if (testSuite == null){ + System.out.println("No test suite file was found, please provide test suite."); + System.exit(1); + } + suites.add(testSuite); + testng.setTestSuites(suites); + testng.setUseDefaultListeners(true); + testng.setOutputDirectory("target/"); + testng.run(); + } +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/run/StartTest.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/run/StartTest.java new file mode 100644 index 000000000..b314c44bb --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/run/StartTest.java @@ -0,0 +1,87 @@ +/*- + * ============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.onap.sdc.ci.tests.run; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; + +import org.apache.log4j.Logger; +import org.apache.log4j.PropertyConfigurator; +import org.testng.TestNG; + +public class StartTest { + + public static long timeOfTest = 0; + + public static boolean debug = false; + + public static AtomicBoolean loggerInitialized = new AtomicBoolean(false); + + protected static Logger logger = null; + + public static void main(String[] args) { + + String debugEnabled = System.getProperty("debug"); + if (debugEnabled != null && debugEnabled.equalsIgnoreCase("true")) { + debug = true; + } + System.out.println("Debug mode is " + (debug ? "enabled" : "disabled")); + + enableLogger(); + + TestNG testng = new TestNG(); + + List suites = new ArrayList(); + suites.add(args[0]); + testng.setTestSuites(suites); + testng.setUseDefaultListeners(true); + testng.setOutputDirectory("target/"); + + testng.run(); + + } + + public StartTest() { + logger = Logger.getLogger(StartTest.class.getName()); + } + + public static void enableLogger() { + + if (false == loggerInitialized.get()) { + + loggerInitialized.set(true); + + String log4jPropsFile = System.getProperty("log4j.configuration"); + if (System.getProperty("os.name").contains("Windows")) { + String logProps = "src/main/resources/ci/conf/log4j.properties"; + if (log4jPropsFile == null) { + System.setProperty("targetlog", "target/"); + log4jPropsFile = logProps; + } + + } + PropertyConfigurator.configureAndWatch(log4jPropsFile); + + } + } + +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/utilities/AdditionalConditions.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/utilities/AdditionalConditions.java new file mode 100644 index 000000000..9a070e2b0 --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/utilities/AdditionalConditions.java @@ -0,0 +1,133 @@ +/*- + * ============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.onap.sdc.ci.tests.utilities; + +import com.paulhammant.ngwebdriver.NgWebDriver; +import org.openqa.selenium.By; +import org.openqa.selenium.JavascriptExecutor; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.support.ui.ExpectedCondition; + +import java.util.List; + +public class AdditionalConditions { + + public static ExpectedCondition searchForOneElement(List ByList){ + return new ExpectedCondition() { + @Override + public WebElement apply(WebDriver driver) { + for (By by : ByList){ + WebElement findElement = driver.findElement(by); + if (findElement != null){ + return findElement; + } + } + return null; + } + }; + } + + public static ExpectedCondition jQueryAJAXCallsHaveCompleted() { + return new ExpectedCondition() { + @Override + public Boolean apply(WebDriver driver) { + return (Boolean) ((JavascriptExecutor)driver). + executeScript("return (window.jQuery!= null) && (jQuery.active === 0);"); + } + }; + } + + public static ExpectedCondition angularHasFinishedProcessing() { + return new ExpectedCondition() { + @Override + public Boolean apply(WebDriver driver) { +// String scriptJS = "return (window.angular !==undefined) &&" +// + " (angular.element(document).injector() !==undefined) &&" +// + " (angular.element(document).injector().get('$http').pendingRequests.length === 0)"; +// return Boolean.valueOf(( (JavascriptExecutor) driver).executeScript(scriptJS).toString()); + new NgWebDriver((JavascriptExecutor) driver).waitForAngularRequestsToFinish(); + return true; + } + }; + } + + public static ExpectedCondition angular2HasFinishedProcessing() { + return driver -> { + new NgWebDriver((JavascriptExecutor) driver).waitForAngular2RequestsToFinish(); + return true; + }; + } + + public static ExpectedCondition pageLoadWait() { + return new ExpectedCondition() { + @Override + public Boolean apply(WebDriver driver) { + String scriptJS = + "try {\r\n" + + " if (document.readyState !== 'complete') {\r\n" + + " return false; // Page not loaded yet\r\n" + + " }\r\n" + + " if (window.jQuery) {\r\n" + + " if (window.jQuery.active) {\r\n" + + " return false;\r\n" + + " } else if (window.jQuery.ajax && window.jQuery.ajax.active) {\r\n" + + " return false;\r\n" + + " }\r\n" + + " }\r\n" + + " if (window.angular) {\r\n" + + " if (!window.qa) {\r\n" + + " // Used to track the render cycle finish after loading is complete\r\n" + + " window.qa = {\r\n" + + " doneRendering: false\r\n" + + " };\r\n" + + " }\r\n" + + " // Get the angular injector for this app (change element if necessary)\r\n" + + " var injector = window.angular.element(document).find('body').injector();\r\n" + + " // Store providers to use for these checks\r\n" + + " var $rootScope = injector.get('$rootScope');\r\n" + + " var $http = injector.get('$http');\r\n" + + " var $timeout = injector.get('$timeout');\r\n" + + " // Check if digest\r\n" + + " if ($rootScope.$$phase === '$apply' || $rootScope.$$phase === '$digest' || $http.pendingRequests.length !== 0) {\r\n" + + " window.qa.doneRendering = false;\r\n" + + " return false; // Angular digesting or loading data\r\n" + + " }\r\n" + + " if (!window.qa.doneRendering) {\r\n" + + " // Set timeout to mark angular rendering as finished\r\n" + + " $timeout(function() {\r\n" + + " window.qa.doneRendering = true;\r\n" + + " }, 0);\r\n" + + " return false;\r\n" + + " }\r\n" + + " }\r\n" + + " return true;\r\n" + + "} catch (ex) {\r\n" + + " return false;\r\n" + + "}"; + return Boolean.valueOf(( (JavascriptExecutor) driver).executeScript(scriptJS).toString()); + } + }; + } + + + +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/utilities/CanvasElement.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/utilities/CanvasElement.java new file mode 100644 index 000000000..eb93a619e --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/utilities/CanvasElement.java @@ -0,0 +1,54 @@ +/*- + * ============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.onap.sdc.ci.tests.utilities; + +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.onap.sdc.ci.tests.datatypes.DataTestIdEnum.LeftPanelCanvasItems; +import org.openqa.selenium.WebElement; + +public final class CanvasElement { + private final String uniqueId; + private ImmutablePair location; + private WebElement elementType; + + CanvasElement(String name, ImmutablePair location, WebElement canvasItem) { + super(); + this.uniqueId = name; + this.location = location; + elementType = canvasItem; + } + + public String getUniqueId() { + return uniqueId; + } + + public ImmutablePair getLocation() { + return location; + } + + public void setLocation(ImmutablePair location) { + this.location = location; + } + + public WebElement getElementType() { + return elementType; + } +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/utilities/CanvasManager.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/utilities/CanvasManager.java new file mode 100644 index 000000000..91011f333 --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/utilities/CanvasManager.java @@ -0,0 +1,179 @@ +/*- + * ============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.onap.sdc.ci.tests.utilities; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Random; +import java.util.UUID; +import java.util.stream.Collectors; + +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.onap.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.interactions.Actions; + +public final class CanvasManager { + private Map canvasElements; + private Actions actions; + private WebElement canvas; + private int reduceCanvasWidthFactor; + // Offsets Are used to find upper right corner of canvas element in order to + // connect links + private static final int CANVAS_ELEMENT_Y_OFFSET = 40; + private static final int CANVAS_ELEMENT_X_OFFSET = 21; // 14 - 27 + + private CanvasManager() { + canvasElements = new HashMap<>(); + actions = new Actions(GeneralUIUtils.getDriver()); + canvas = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.GeneralCanvasItems.CANVAS.getValue()); + try { + WebElement webElement = GeneralUIUtils + .getWebElementByTestID(DataTestIdEnum.GeneralCanvasItems.CANVAS_RIGHT_PANEL.getValue()); + reduceCanvasWidthFactor = webElement.getSize().width; + } catch (Exception e) { + reduceCanvasWidthFactor = 0; + } + } + + public static CanvasManager getCanvasManager() { + return new CanvasManager(); + } + + public List getCanvasElements() { + return canvasElements.values().stream().collect(Collectors.toList()); + } + + private void addCanvasElement(CanvasElement element) { + canvasElements.put(element.getUniqueId(), element); + } + + private void moveElementOnCanvas(CanvasElement canvasElement, ImmutablePair newLocation) + throws Exception { + GeneralUIUtils.waitForLoader(); + Thread.sleep(500); + actions.moveToElement(canvas, canvasElement.getLocation().left, canvasElement.getLocation().right); + actions.clickAndHold(); + actions.moveToElement(canvas, newLocation.left, newLocation.right); + actions.release(); + actions.perform(); + canvasElement.setLocation(newLocation); + GeneralUIUtils.waitForLoader(); + + } + + public void moveElementOnCanvas(CanvasElement canvasElement) throws Exception { + moveElementOnCanvas(canvasElement, getFreePosition()); + } + + public void deleteElementFromCanvas(CanvasElement canvasElement) throws Exception { + GeneralUIUtils.waitForLoader(); + actions.moveToElement(canvas, canvasElement.getLocation().left, canvasElement.getLocation().right); + actions.click(); + actions.perform(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.GeneralCanvasItems.DELETE_INSTANCE_BUTTON.getValue()) + .click(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ModalItems.OK.getValue()).click(); + canvasElements.remove(canvasElement.getUniqueId()); + GeneralUIUtils.waitForLoader(); + } + + private String getItemName(WebElement canvasItem) { + String canvasItemName = canvasItem.getAttribute("data-tests-id"); + + return canvasItemName.substring(canvasItemName.lastIndexOf("-")); + } + + public CanvasElement createElementOnCanvas(WebElement canvasItem) throws Exception { + GeneralUIUtils.waitForLoader(); + ImmutablePair freePosition = getFreePosition(); + actions.moveToElement(canvasItem, 0, 0); + actions.clickAndHold(); + actions.moveToElement(canvas, freePosition.left, freePosition.right); + actions.release(); + actions.perform(); + + String uniqueId = getItemName(canvasItem) + "_" + UUID.randomUUID().toString(); + CanvasElement canvasElement = new CanvasElement(uniqueId, freePosition, canvasItem); + addCanvasElement(canvasElement); + GeneralUIUtils.waitForLoader(); + return canvasElement; + } + + private ImmutablePair getFreePosition() { + // TODO mshitrit use better method + ImmutablePair randomPosition = null; + boolean freePosition = false; + int minSpace = 150; + while (!freePosition) { + ImmutablePair tempRandomPosition = getRandomPosition(); + freePosition = !canvasElements.values().stream().map(e -> e.getLocation()) + .filter(e -> Math.abs(e.left - tempRandomPosition.left) < minSpace + && Math.abs(e.right - tempRandomPosition.right) < minSpace) + .findAny().isPresent(); + randomPosition = tempRandomPosition; + } + return randomPosition; + } + + private ImmutablePair getRandomPosition() { + int edgeBuffer = 50; + Random random = new Random(); + int xElement = random.nextInt(canvas.getSize().width - 2 * edgeBuffer - reduceCanvasWidthFactor) + edgeBuffer; + int yElement = random.nextInt(canvas.getSize().height - 2 * edgeBuffer) + edgeBuffer; + return new ImmutablePair(xElement, yElement); + } + + public void linkElements(CanvasElement firstElement, CanvasElement secondElement) throws Exception { + GeneralUIUtils.waitForLoader(); + drawSimpleLink(firstElement, secondElement); + + selectReqAndCapAndConnect(); + + GeneralUIUtils.waitForLoader(); + + } + + private void selectReqAndCapAndConnect() { + // Select First Cap + GeneralUIUtils.getWebElementsListByTestID(DataTestIdEnum.LinkMenuItems.LINK_ITEM_CAP.getValue()).get(0).click(); + // Select First Req + GeneralUIUtils.getWebElementsListByTestID(DataTestIdEnum.LinkMenuItems.LINK_ITEM_REQ.getValue()).get(0).click(); + // Connect + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.LinkMenuItems.CONNECT_BUTTON.getValue()).click(); + } + + private void drawSimpleLink(CanvasElement firstElement, CanvasElement secondElement) { + + int yOffset = CANVAS_ELEMENT_Y_OFFSET; + int xOffset = CANVAS_ELEMENT_X_OFFSET; + + actions.moveToElement(canvas, firstElement.getLocation().left + xOffset, + firstElement.getLocation().right - yOffset); + + actions.clickAndHold(); + actions.moveToElement(canvas, secondElement.getLocation().left + xOffset, + secondElement.getLocation().right - yOffset); + actions.release(); + actions.perform(); + } +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/utilities/Constants.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/utilities/Constants.java new file mode 100644 index 000000000..4be51fbfd --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/utilities/Constants.java @@ -0,0 +1,128 @@ +/*- + * ============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.onap.sdc.ci.tests.utilities; + +public interface Constants { + + public static final String APPLICATION_NAME = "application-name"; + public static final String APPLICATION_VERSION = "application-version"; + public static final String CONFIG_HOME = "config.home"; + public static final String LOG_HOME = "log.home"; + public static final String YAML_SUFFIX = ".yaml"; + public static final String CONFIGURATION_SOURCE_ATTR = "configuration-source"; + public static final String MDC_APP_NAME = "APP_NAME"; + public static final String CONFIGURATION_MANAGER_ATTR = "configuration-manager"; + public static final String HEALTH_CHECK_SERVICE_ATTR = "healthCheckService"; + public static final String REST_CLIENT_ATTR = "rest-client"; + public static final String ARTIFACT_DAO_ATTR = "artifact-dao"; + public static final String UPLOAD_VALIDATORR_ATTR = "upload-validator"; + public static final String THREAD_EXECUTOR_ATTR = "thread-executor"; + public static final String ERROR_LOG_FORMAT = "EVENT = ARTIFACT_UPLOAD USER_ID=%s USER_NAME=%s ACCESS_IP=%s ACCESS_TYPE=%s RURL=%s SC=%d"; + public static final String FIRST_NAME_HEADER = "HTTP_CSP_FIRSTNAME"; + public static final String LAST_NAME_HEADER = "HTTP_CSP_LASTNAME"; + public static final String USER_ID_HEADER = "USER_ID"; + public static final String MD5_HEADER = "Content-MD5"; + public static final String CONTENT_DISPOSITION_HEADER = "Content-Disposition"; + public static final String CONTENT_TYPE_HEADER = "Content-Type"; + public static final String ORIGIN_HEADER = "HTTP_IV_REMOTE_ADDRESS"; + public static final String ACCESS_HEADER = "HTTP_CSP_WSTYPE"; + public static final String X_ECOMP_REQUEST_ID_HEADER = "X-ECOMP-RequestID"; + public static final String X_ECOMP_INSTANCE_ID_HEADER = "X-ECOMP-InstanceID"; + public static final String X_ECOMP_SERVICE_ID_HEADER = "X-ECOMP-ServiceID"; + public static final String HTTP = "http"; + public static final String HTTPS = "https"; + public static final String HTTP_IV_USER = "HTTP_IV_USER"; + public static final String A4C_CSAR_CONTEXT = "/rest/csars/"; + public static final String WEB_APPLICATION_CONTEXT_WRAPPER_ATTR = "web-application-context-wrapper"; + public static final String CATALOG_BE = "catalog-be"; + public static final String HTTP_CSP_FIRSTNAME = "HTTP_CSP_FIRSTNAME"; + public static final String HTTP_CSP_LASTNAME = "HTTP_CSP_LASTNAME"; + public static final String HTTP_IV_REMOTE_ADDRESS = "HTTP_IV_REMOTE_ADDRESS"; + public static final String HTTP_CSP_TYPE = "HTTP_CSP_WSTYPE"; + public static final String RESOURCE_SUPPORTED_VERSION = "0.0.1"; + public static final String ARTIFACT_ID_FORMAT = "%s:%s:%s"; // resourceName:resourceVersion:artifactName + public static final String SERVICE_ARTIFACT_ID_FORMAT = "%s:%s:%s:%s"; // serviceName:serviceVersion:nodeTemplateName:artifactName + public static final String CONTENT_DISPOSITION = "content-disposition"; + public static final String DOWNLOAD_ARTIFACT_LOGIC_ATTR = "downloadArtifactLogic"; + public static final String ASDC_RELEASE_VERSION_ATTR = "ASDC-Version"; + // public static final String AUDITING_MANAGER = "auditingManager"; + // public static final String USER_ADMIN_MANAGER = "userAdminManager"; + public static final String YEAR = "year"; + public static final String MONTH = "month"; + public static final String DAY = "day"; + public static final String HOUR = "hour"; + public static final String MINUTE = "minute"; + public static final String NONE = "none"; + public static final String RESOURCE_OPERATION_MANAGER = "resourceOperationManager"; + public static final String PROPERTY_OPERATION_MANAGER = "propertyOperationManager"; + public static final String SERVICE_OPERATION_MANAGER = "serviceOperationManager"; + public static final String EMPTY_STRING = ""; + public static final String NULL_STRING = "null"; + public static final String DOUBLE_NULL_STRING = "null null"; + public static final String ECOMP_ERROR_MNGR_ATTR = "ecompErrorMngrAttr"; + public static final String AUTHORIZATION_HEADER = "Authorization"; + public static final String ACCEPT_HEADER = "Accept"; + public static final String STANDARD_INTERFACE_TYPE = "standard"; + public static final String MURANO_PKG_ARTIFACT_TYPE = "MURANO-PKG"; + public static final String ARTIFACT_GROUP_TYPE_FIELD = "artifactGroupType"; + + // TOSCA + public static final String TOSCA_META_PATH = "TOSCA-Metadata/TOSCA.meta"; + public static final String TOSCA_META_ENTRY_DEFINITIONS = "Entry-Definitions"; + public static final String USER_DEFINED_RESOURCE_NAMESPACE_PREFIX = "org.openecomp.resource."; + + public static final String IS_BASE = "isBase"; + public static final String HEAT_FILE_PROPS = "heat_file"; + public static final String MODULE_NAME_FORMAT = "%s..%s..module-%s"; + public static final String MODULE_DESC_PATTERN = "[\\_\\-\\.a-zA-Z0-9]+"; + public static final String MODULE_OLD_NAME_PATTERN = "([\\w\\_\\-\\.\\s]+)(::module-)(\\d+)"; + public static final String MODULE_NEW_NAME_PATTERN = "([\\w\\_\\-\\.\\s]+\\.\\.)([\\_\\-\\.a-zA-Z0-9]+)(..module-)(\\d+)"; + public static final String MODULE_NAME_DELIMITER = "module-"; + public static final String IMPORT_STRUCTURE = "importStructure"; + public static final String DEFAULT_GROUP_VF_MODULE = "org.openecomp.groups.VfModule"; + + public static final String ARTIFACT_GROUP_TYPE = "artifactGroupType"; + public static final String ARTIFACT_LABEL = "artifactLabel"; + public static final String ARTIFACT_PAYLOAD_DATA = "payloadData"; + public static final String ARTIFACT_DISPLAY_NAME = "artifactDisplayName"; + public static final String ARTIFACT_DESCRIPTION = "description"; + public static final String ARTIFACT_TYPE = "artifactType"; + public static final String ARTIFACT_NAME = "artifactName"; + public static final String ARTIFACT_ID = "uniqueId"; + public static final String REQUIRED_ARTIFACTS = "requiredArtifacts"; + + public static final String ABSTRACT = "abstract"; + public static final String GLOBAL_SUBSTITUTION_TYPES_SERVICE_TEMPLATE = "Definitions/GlobalSubstitutionTypesServiceTemplate.yaml"; + public static final String ABSTRACT_SUBSTITUTE_GLOBAL_TYPES_SERVICE_TEMPLATE = "Definitions/AbstractSubstituteGlobalTypesServiceTemplate.yaml"; + + public static final String VENDOR_LICENSE_MODEL = "vendor-license-model.xml"; + public static final String VENDOR_LICENSE_LABEL = "vendorlicense"; + public static final String VENDOR_LICENSE_DISPLAY_NAME = "Vendor License"; + public static final String VENDOR_LICENSE_DESCRIPTION = " Vendor license file"; + + public static final String VF_LICENSE_MODEL = "vf-license-model.xml"; + public static final String VF_LICENSE_LABEL = "vflicense"; + public static final String VF_LICENSE_DISPLAY_NAME = "VF License"; + public static final String VF_LICENSE_DESCRIPTION = "VF license file"; + public static final String GET_INPUT = "get_input"; + public static final String SERVICE_TEMPLATE_FILE_POSTFIX = "ServiceTemplate.yaml"; + public static final String UNBOUNDED = "unbounded"; +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/utilities/Decoder.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/utilities/Decoder.java new file mode 100644 index 000000000..049302e54 --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/utilities/Decoder.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.onap.sdc.ci.tests.utilities; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; + +import org.apache.commons.codec.binary.Base64; + +public class Decoder { + + public static String encode(byte[] byteArrayToEncode) { + + byte[] bytesEncoded = Base64.encodeBase64(byteArrayToEncode); + String strEncoded = new String(bytesEncoded); + return strEncoded; + } + + public static String decode(String strEncoded) throws IOException { + + byte[] byteDecoded = Base64.decodeBase64(strEncoded); + String decoded = new String(byteDecoded); + + return decoded; + + } + + public static String readFileToString(String file) throws IOException { + + BufferedReader reader = new BufferedReader(new FileReader(file)); + String line = null; + StringBuilder stringBuilder = new StringBuilder(); + String ls = System.getProperty("line.separator"); + + while ((line = reader.readLine()) != null) { + stringBuilder.append(line); + stringBuilder.append(ls); + } + reader.close(); + return stringBuilder.toString(); + } + +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/utilities/EcompPortalUtilities.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/utilities/EcompPortalUtilities.java new file mode 100644 index 000000000..bded65be8 --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/utilities/EcompPortalUtilities.java @@ -0,0 +1,17 @@ +package org.onap.sdc.ci.tests.utilities; + +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; + +public class EcompPortalUtilities { + + public static void swichFrames(By by){ + WebElement appImage = GeneralUIUtils.getClickableButtonBy(by, 3 * 60); + appImage.click(); + GeneralUIUtils.getDriver().switchTo().frame(1); + GeneralUIUtils.waitForBackLoader(); + GeneralUIUtils.waitForAngular(); + GeneralUIUtils.getWebElementByClassName("applicationWindow"); + } + +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/utilities/FileHandling.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/utilities/FileHandling.java new file mode 100644 index 000000000..d5d5540a9 --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/utilities/FileHandling.java @@ -0,0 +1,489 @@ +/*- + * ============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.onap.sdc.ci.tests.utilities; + +import static org.testng.AssertJUnit.assertTrue; + +import java.io.BufferedOutputStream; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.FileWriter; +import java.io.FilenameFilter; +import java.io.IOException; +import java.io.InputStream; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.zip.ZipEntry; +import java.util.zip.ZipException; +import java.util.zip.ZipFile; +import java.util.zip.ZipInputStream; + +import org.apache.commons.io.FileUtils; +import org.onap.sdc.ci.tests.datatypes.UserCredentials; +import org.onap.sdc.ci.tests.execute.setup.ExtentTestActions; +import org.onap.sdc.ci.tests.execute.setup.SetupCDTest; +import org.yaml.snakeyaml.Yaml; + +import com.aventstack.extentreports.Status; + +public class FileHandling { + +// ------------------yaml parser methods---------------------------- + public static Map parseYamlFile(String filePath) throws Exception { + Yaml yaml = new Yaml(); + File file = new File(filePath); + InputStream inputStream = new FileInputStream(file); + Map map = (Map) yaml.load(inputStream); + return map; + } + + /** + * The method return map fetched objects by pattern from yaml file + * @param yamlFile + * @param pattern + * @return + * @throws Exception + */ + public static Map parseYamlFileToMapByPattern(File yamlFile, String pattern) throws Exception { + Map yamlFileToMap = FileHandling.parseYamlFile(yamlFile.toString()); + Map objectMap = getObjectMapByPattern(yamlFileToMap, pattern); + return objectMap; + } + + @SuppressWarnings("unchecked") + public static Map getObjectMapByPattern(Map parseUpdetedEnvFile, String pattern) { + Map objectMap = null; + + Object objectUpdetedEnvFile = parseUpdetedEnvFile.get(pattern); + if(objectUpdetedEnvFile instanceof HashMap){ + objectMap = (Map) objectUpdetedEnvFile; + } + return objectMap; + } + +// ------------------------------------------------------------------------------------------------- + + public static String getFilePath(String folder) { + String filepath = System.getProperty("filepath"); + if (filepath == null && System.getProperty("os.name").contains("Windows")) { + filepath = FileHandling.getResourcesFilesPath() + folder + File.separator; + } + + else if(filepath.isEmpty() && !System.getProperty("os.name").contains("Windows")){ + filepath = FileHandling.getBasePath() + "Files" + File.separator + folder + File.separator; + } + + System.out.println(filepath); + + return filepath; + } + + public static String getBasePath() { + return System.getProperty("user.dir") + File.separator; + } + + public static String getDriversPath() { + return getBasePath() + "src" + File.separator + "main" + File.separator + "resources" + + File.separator + "ci" + File.separator + "drivers" + File.separator; + } + + public static String getResourcesFilesPath() { + return getBasePath() + "src" + File.separator + "main" + File.separator + "resources" + + File.separator + "Files" + File.separator; + } + + public static String getResourcesEnvFilesPath() { + return getBasePath() + File.separator + "src" + File.separator + "main" + File.separator + "resources" + + File.separator + "Files" + File.separator + "ResourcesEnvFiles" +File.separator; + } + + public static String getCiFilesPath() { + return getBasePath() + "src" + File.separator + "main" + File.separator + "resources" + + File.separator + "ci"; + } + + public static String getConfFilesPath() { + return getCiFilesPath() + File.separator + "conf" + File.separator; + } + + public static String getTestSuitesFilesPath() { + return getCiFilesPath() + File.separator + "testSuites" + File.separator; + } + + public static File getConfigFile(String configFileName) throws Exception { + File configFile = new File(FileHandling.getBasePath() + File.separator + "conf" + File.separator + configFileName); + if (!configFile.exists()) { + configFile = new File(FileHandling.getConfFilesPath() + configFileName); + } + return configFile; + } + + public static Object[] filterFileNamesFromFolder(String filepath, String extension) { + try { + File dir = new File(filepath); + List filenames = new ArrayList(); + + FilenameFilter extensionFilter = new FilenameFilter() { + public boolean accept(File dir, String name) { + return name.endsWith(extension); + } + }; + + if (dir.isDirectory()) { + for (File file : dir.listFiles(extensionFilter)) { + filenames.add(file.getName()); + } + return filenames.toArray(); + } + + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public static String[] getArtifactsFromZip(String filepath, String zipFilename){ + try{ + ZipFile zipFile = new ZipFile(filepath + File.separator + zipFilename); + Enumeration entries = zipFile.entries(); + + String[] artifactNames = new String[zipFile.size() - 1]; + + int i = 0; + while(entries.hasMoreElements()){ + ZipEntry nextElement = entries.nextElement(); + if (!nextElement.isDirectory()){ + if (!nextElement.getName().equals("MANIFEST.json")){ + String name = nextElement.getName(); + artifactNames[i++] = name; + } + } + } + zipFile.close(); + return artifactNames; + } + catch(ZipException zipEx){ + System.err.println("Error in zip file named : " + zipFilename); + zipEx.printStackTrace(); + } catch (IOException e) { + System.err.println("Unhandled exception : "); + e.printStackTrace(); + } + + return null; + + } + + public static Object[] getZipFileNamesFromFolder(String filepath) { + return filterFileNamesFromFolder(filepath, ".zip"); + } + + public static int countFilesInZipFile(String[] artifactsArr, String reqExtension){ + int fileCounter = 0; + for (String artifact : artifactsArr){ + String extensionFile = artifact.substring(artifact.lastIndexOf(".") + 1 , artifact.length()); + if (extensionFile.equals(reqExtension)){ + fileCounter++; + } + } + return fileCounter; + } + + + public static synchronized File getLastModifiedFileFromDir() throws Exception{ + return getLastModifiedFileFromDir(SetupCDTest.getWindowTest().getDownloadDirectory()); + } + + public static synchronized File getLastModifiedFileFromDir(String dirPath){ + File dir = new File(dirPath); + File[] files = dir.listFiles(); + if (files == null) { + assertTrue("File not found under directory " + dirPath, false); + return null; + } + + File lastModifiedFile = files[0]; + for (int i = 1; i < files.length; i++) { + if(files[i].isDirectory()) { + continue; + } + if (lastModifiedFile.lastModified() < files[i].lastModified()) { + lastModifiedFile = files[i]; + } + } + return lastModifiedFile; + } + + public static void deleteDirectory(String directoryPath) { + File dir = new File(directoryPath); + try { + FileUtils.deleteDirectory(dir); + } catch (IOException e) { + System.out.println("Failed to delete " + dir); + SetupCDTest.getExtendTest().log(Status.INFO, "Failed to delete " + dir); + } + } + + public static void createDirectory(String directoryPath) { + File directory = new File(String.valueOf(directoryPath)); + if (! directory.exists()){ + directory.mkdir(); + } + } + + + /** + * The method append data to existing file, if file not exists - create it + * @param pathToFile + * @param text + * @param leftSpaceCount + * @throws IOException + */ + public static synchronized void writeToFile(File pathToFile, Object text, Integer leftSpaceCount) throws IOException{ + + BufferedWriter bw = null; + FileWriter fw = null; + if(!pathToFile.exists()){ + createEmptyFile(pathToFile); + } + try { + fw = new FileWriter(pathToFile, true); + bw = new BufferedWriter(fw); + StringBuilder sb = new StringBuilder(); + if(leftSpaceCount > 0 ){ + for(int i = 0; i < leftSpaceCount; i++){ + sb.append(" "); + } + } + bw.write(sb.toString() + text); + bw.newLine(); + bw.close(); + fw.close(); + } catch (Exception e) { + SetupCDTest.getExtendTest().log(Status.INFO, "Unable to write to flie " + pathToFile); + } + } + + + public static void cleanCurrentDownloadDir() throws IOException { + try{ + ExtentTestActions.log(Status.INFO, "Cleaning directory " + SetupCDTest.getWindowTest().getDownloadDirectory()); + System.gc(); + FileUtils.cleanDirectory(new File(SetupCDTest.getWindowTest().getDownloadDirectory())); + } + catch(Exception e){ + + } + } + + public static boolean isFileDownloaded(String downloadPath, String fileName) { + boolean flag = false; + File dir = new File(downloadPath); + File[] dir_contents = dir.listFiles(); + for (int i = 0; i < dir_contents.length; i++) { + if (dir_contents[i].getName().equals(fileName)) + return flag = true; + } + return flag; + } + + public static String getMD5OfFile(File file) throws IOException { + String content = FileUtils.readFileToString(file); + String md5 = GeneralUtility.calculateMD5ByString(content); + return md5; + } + + public static File createEmptyFile(String fileToCreate) { + File file= new File(fileToCreate); + try { + if(file.exists()){ + deleteFile(file); + } + file.createNewFile(); + SetupCDTest.getExtendTest().log(Status.INFO, "Create file " + fileToCreate); + } catch (IOException e) { + SetupCDTest.getExtendTest().log(Status.INFO, "Failed to create file " + fileToCreate); + e.printStackTrace(); + } + return file; + } + + public static File createEmptyFile(File fileToCreate) { + try { + if(fileToCreate.exists()){ + deleteFile(fileToCreate); + } + fileToCreate.createNewFile(); + SetupCDTest.getExtendTest().log(Status.INFO, "Create file " + fileToCreate); + } catch (IOException e) { + SetupCDTest.getExtendTest().log(Status.INFO, "Failed to create file " + fileToCreate); + e.printStackTrace(); + } + return fileToCreate; + } + + public static void deleteFile(File file){ + + try{ + if(file.exists()){ + file.deleteOnExit(); + SetupCDTest.getExtendTest().log(Status.INFO, "File " + file.getName() + "has been deleted"); + }else{ + SetupCDTest.getExtendTest().log(Status.INFO, "Failed to delete file " + file.getName()); + } + }catch(Exception e){ + e.printStackTrace(); + } + + } + + + /** + * get file list from directory by extension array + * @param directory + * @param okFileExtensions + * @return + */ + public static List getHeatAndHeatEnvArtifactsFromZip(File directory, String[] okFileExtensions){ + + List fileList = new ArrayList<>(); + File[] files = directory.listFiles(); + + for (String extension : okFileExtensions){ + for(File file : files){ + if (file.getName().toLowerCase().endsWith(extension)){ + fileList.add(file); + } + } + } + return fileList; + } + + private static final int BUFFER_SIZE = 4096; + public static void unzip(String zipFilePath, String destDirectory) throws IOException { + File destDir = new File(destDirectory); + if (!destDir.exists()) { + destDir.mkdir(); + } + ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath)); + ZipEntry entry = zipIn.getNextEntry(); +// iterates over entries in the zip file + while (entry != null) { + String entryName; + if(System.getProperty("os.name").contains("Windows")){ + entryName = entry.getName().replaceAll("/", "\\"+File.separator); + }else{ + entryName = entry.getName(); + } + String filePath = destDirectory + entryName; + String currPath = destDirectory; + String[] dirs = entryName.split("\\"+File.separator); + String currToken; + for(int i = 0; i -1) + computerName = computerName.substring(0, + computerName.indexOf(".")).toUpperCase(); + } catch (UnknownHostException e) { + System.out.println("Uknown hostAddress"); + } + return computerName != null ? computerName : "Uknown hostAddress"; + } + + public static Map loadCredentialsFile(String path, String filename) throws Exception { + File credentialsFileRemote = new File(path + filename); + Map yamlFile = FileHandling.parseYamlFile(credentialsFileRemote.getAbsolutePath()); + return yamlFile; + } + +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/utilities/FindUtils.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/utilities/FindUtils.java new file mode 100644 index 000000000..2b0ca66da --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/utilities/FindUtils.java @@ -0,0 +1,52 @@ +/*- + * ============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.onap.sdc.ci.tests.utilities; + +import org.onap.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openqa.selenium.WebElement; +import org.testng.Assert; + +import com.aventstack.extentreports.Status; + +public final class FindUtils { + + + public static void findComponentAndClick(String componentName) throws Exception { + SetupCDTest.getExtendTest().log(Status.INFO, "finding component " + componentName); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtons.SEARCH_BOX.getValue()).sendKeys(componentName); + WebElement foundComp = null; + try { + foundComp = GeneralUIUtils.getWebElementByTestID(componentName); + foundComp.click(); + GeneralUIUtils.waitForLoader(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.GeneralElementsEnum.LIFECYCLE_STATE.getValue()); + } catch (Exception e) { + String msg = String.format("DID NOT FIND A COMPONENT NAMED %s", componentName); + SetupCDTest.getExtendTest().log(Status.FAIL, msg); + System.out.println(msg); + Assert.fail(msg); + } + } + + + +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/utilities/GeneralUIUtils.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/utilities/GeneralUIUtils.java new file mode 100644 index 000000000..8885e1c3f --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/utilities/GeneralUIUtils.java @@ -0,0 +1,803 @@ +/*- + * ============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.onap.sdc.ci.tests.utilities; + +import com.aventstack.extentreports.Status; +import org.apache.commons.io.FileUtils; +import org.junit.Assert; +import org.onap.sdc.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.ci.tests.datatypes.DataTestIdEnum.DashboardCardEnum; +import org.onap.sdc.ci.tests.execute.setup.DriverFactory; +import org.onap.sdc.ci.tests.execute.setup.SetupCDTest; +import org.openqa.selenium.*; +import org.openqa.selenium.firefox.FirefoxDriver; +import org.openqa.selenium.interactions.Actions; +import org.openqa.selenium.support.ui.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.awt.*; +import java.awt.event.KeyEvent; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; + +import static org.hamcrest.Matchers.is; + + +public final class GeneralUIUtils { + + public static final String FILE_NAME = "Valid_tosca_Mycompute.yml"; + static final Logger logger = LoggerFactory.getLogger(GeneralUIUtils.class); + + private static int timeOut=90; + +// public static void setTimeOut(int time) { +// if (time>0) { +// timeOut=time; +// } +// else { +// timeOut=timeOut; +// } +// } + + /**************** DRIVER ****************/ + + public static WebDriver getDriver() { + try{ + return DriverFactory.getDriver(); + } + catch(Exception e){ + e.printStackTrace(); + } + return null; + } + /****************************************/ + + public static List getElemenetsFromTable(By by) { + return getDriver().findElements(by); + } + + public static File takeScreenshot(String screenshotFilename, String dir, String testName) throws IOException { + if (screenshotFilename == null) { + if (testName != null){ + screenshotFilename = testName; + } + else + { + screenshotFilename = UUID.randomUUID().toString(); + } + } + try { + File scrFile = ((TakesScreenshot) getDriver()).getScreenshotAs(OutputType.FILE); + File filePath = new File(String.format("%s/%s.png", dir, screenshotFilename)); + new File(dir).mkdirs(); + FileUtils.copyFile(scrFile, filePath); + return filePath; + } catch (IOException e1) { + e1.printStackTrace(); + } + return null; + } + + public static File takeScreenshot(String screenshotFilename, String dir) throws IOException{ + return takeScreenshot(screenshotFilename, dir, null); + } + + + public static void scrollDown() { + try{ + Robot robot = new Robot(); + robot.keyPress(KeyEvent.VK_DOWN); + robot.keyRelease(KeyEvent.VK_DOWN); + GeneralUIUtils.waitForLoader(); + } + catch(Exception e){ + e.printStackTrace(); + } + } + + + public static WebElement getWebElementByTestID(String dataTestId) { + return getWebElementByTestID(dataTestId, timeOut); + } + + public static WebElement getWebElementByTestID(String dataTestId, int timeout) { + WebDriverWait wait = newWait(timeout); + return wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@data-tests-id='" + dataTestId + "']"))); + } + + public static boolean isWebElementExistByTestId(String dataTestId) { + if(getDriver().findElements(By.xpath("//*[@data-tests-id='" + dataTestId + "']")).size() == 0) { + return false; + } + return true; + } + + public static WebElement getInputElement(String dataTestId) { + try{ + ultimateWait(); + return getDriver().findElement(By.xpath("//*[@data-tests-id='" + dataTestId + "']")); + } + catch(Exception e){ + return null; + } + } + + public static List getInputElements(String dataTestId) { + ultimateWait(); + return getDriver().findElements(By.xpath("//*[@data-tests-id='" + dataTestId + "']")); + + } + + public static WebElement getWebElementBy(By by) { + return getWebElementBy(by, timeOut); + } + + public static WebElement getWebElementBy(By by, int timeoutInSeconds) { + WebDriverWait wait = newWait(timeoutInSeconds); + return wait.until(ExpectedConditions.visibilityOfElementLocated(by)); + } + + public static List getWebElementListText(Listelements) { + ListText=new ArrayList<>(); + for (WebElement webElement : elements) { + Text.add(webElement.getText()); + } + return Text; + } + + + public static List getWebElementsListBy(By by) { + return getWebElementsListBy(by, timeOut); + } + + public static List getWebElementsListBy(By by, int timeOut) { + WebDriverWait wait = newWait(timeOut); + return wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(by)); + } + + public static List getWebElementsListByContainTestID(String dataTestId) { + try{ + WebDriverWait wait = newWait(10); + return wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.xpath("//*[contains(@data-tests-id, '"+dataTestId+"')]"))); + } + catch(Exception e){ + return new ArrayList(); + } + } + + public static List getWebElementsListByContainsClassName(String containedText) { + return getWebElementsListByContainsClassName(containedText, timeOut); + } + + public static List getWebElementsListByContainsClassName(String containedText, int timeoutInSeconds) { + WebDriverWait wait = newWait(timeoutInSeconds); + return wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.xpath("//*[contains(@class, '"+containedText+"')]"))); + } + + public static WebElement getWebElementByContainsClassName(String containedText) { + return getWebElementByContainsClassName(containedText, timeOut); + } + + public static WebElement getWebElementByContainsClassName(String containedText, int timeoutInSeconds) { + return getWebElementBy(By.xpath("//*[contains(@class, '"+containedText+"')]"), timeoutInSeconds); + } + + public static WebElement getWebElementByClassName(String className) { + return getWebElementByClassName(className, timeOut); + } + + public static WebElement getWebElementByClassName(String className, int timeoutInSeconds) { + WebDriverWait wait = newWait(timeoutInSeconds); + return wait.until(ExpectedConditions.visibilityOfElementLocated(By.className(className))); + } + + public static List getWebElementsListByContainsClassNameAndText(String cssName, String text, int timeoutInSeconds) { + WebDriverWait wait = newWait(timeoutInSeconds); + String xpath = String.format("//*[contains(@class, '%s') and contains(text(),'%s')]", cssName, text); + return wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy( + By.xpath(xpath))); + } + + public static WebElement getWebElementByLinkText(String linkText) { + WebDriverWait wait = newWait(timeOut); + return wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@text='" + linkText + "']"))); + } + + + public static List getWebElementsListByTestID(String dataTestId) { + WebDriverWait wait = newWait(timeOut); + return wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//*[@data-tests-id='" + dataTestId + "']"))); + } + + public static List getWebElementsListByClassName(String className) { + WebDriverWait wait = newWait(timeOut); + return wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.className(className))); + } + + + + + public static Boolean isElementInvisibleByTestId(String dataTestId) { + WebDriverWait wait = newWait(timeOut); + return wait.until( + ExpectedConditions.invisibilityOfElementLocated(By.xpath("//*[@data-tests-id='" + dataTestId + "']"))); + } + + public static Boolean isElementVisibleByTestId(String dataTestId) { + try{ + WebDriverWait wait = newWait(timeOut); + if(wait.until(ExpectedConditions.visibilityOfElementLocated((By.xpath("//*[@data-tests-id='" + dataTestId + "']")))).isDisplayed()){ + return true; + }else { + return false; + } + } + catch(Exception e){ + return false; + } + } + + public static void clickOnElementByTestId(String dataTestId) { + clickOnElementByTestIdWithoutWait(dataTestId); + ultimateWait(); + } + + public static void clickOnElementByTestIdWithoutWait(String dataTestId) { + WebDriverWait wait = newWait(timeOut); + wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@data-tests-id='" + dataTestId + "']"))).click(); + } + + public static void clickOnElementByTestId(String dataTestId, int customTimeout) { + WebDriverWait wait = newWait(customTimeout); + wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@data-tests-id='" + dataTestId + "']"))).click(); + } + + public static WebElement waitForElementVisibilityByTestId(String dataTestId) { + WebDriverWait wait = newWait(timeOut); + return wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@data-tests-id='" + dataTestId + "']"))); + } + + public static Boolean waitForElementInVisibilityByTestId(String dataTestId) { + return waitForElementInVisibilityByTestId(dataTestId, timeOut); + } + + public static Boolean waitForElementInVisibilityByTestId(String dataTestId, int timeOut) { + WebDriverWait wait = newWait(timeOut); + boolean displayed = getDriver().findElements(By.xpath("//*[@data-tests-id='" + dataTestId + "']")).isEmpty(); + if (!displayed){ + Boolean until = wait.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("//*[@data-tests-id='" + dataTestId + "'])"))); + ultimateWait(); + return until; + } + return false; + } + + public static Boolean waitForElementInVisibilityByTestId(By by) { + return waitForElementInVisibilityBy(by, timeOut); + } + + + public static Boolean waitForElementInVisibilityBy(By by, int timeOut) { + WebDriverWait wait = newWait(timeOut); + boolean displayed = getDriver().findElements(by).isEmpty(); + if (!displayed){ + Boolean until = wait.until(ExpectedConditions.invisibilityOfElementLocated(by)); + sleep(1); + return until; + } + return false; + } + + + public static void setWebElementByTestId(String elementID, String value) { + WebElement resourceDescriptionTextbox = GeneralUIUtils.getWebElementByTestID(elementID); + resourceDescriptionTextbox.clear(); + resourceDescriptionTextbox.sendKeys(value); + + } + + public static WebElement hoverOnAreaByTestId(String areaId) { + Actions actions = new Actions(getDriver()); + WebElement area = getWebElementByTestID(areaId); + actions.moveToElement(area).perform(); + ultimateWait(); + return area; + } + + public static WebElement hoverOnAreaByClassName(String className) { + Actions actions = new Actions(getDriver()); + WebElement area = getWebElementByClassName(className); + actions.moveToElement(area).perform(); + GeneralUIUtils.ultimateWait(); + return area; + } + + public static void clickElementUsingActions(WebElement element){ + Actions actions = new Actions(getDriver()); + + actions.moveToElement(element); + actions.perform(); + + actions.click(); + actions.perform(); + + ultimateWait(); + } + + public static void waitForLoader() { + waitForLoader(timeOut); + } + + public static void waitForLoader(int timeOut) { + sleep(1); + waitForElementInVisibilityBy(By.className("tlv-loader"), timeOut); + } + + public static void findComponentAndClick(String resourceName) throws Exception { + SetupCDTest.getExtendTest().log(Status.INFO, "Searching for " + resourceName + " in homepage"); + WebElement searchTextbox = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtons.SEARCH_BOX.getValue()); + try{ + searchTextbox.clear(); + searchTextbox.sendKeys(resourceName); + ultimateWait(); + } + catch(Exception e){ + SetupCDTest.getExtendTest().log(Status.INFO, "Can't interact with search bar"); + e.printStackTrace(); + } + + + try{ + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on the %s component from home screen", resourceName)); + clickOnElementByTestId(resourceName); + GeneralUIUtils.ultimateWait(); + getWebElementByTestID(DataTestIdEnum.GeneralElementsEnum.LIFECYCLE_STATE.getValue()); + } + catch(Exception e){ + SetupCDTest.getExtendTest().log(Status.INFO, "Can't click on component named " + resourceName); + e.printStackTrace(); + } + } + + + public static String getComponentVersion(String componentName) { + return GeneralUIUtils.getWebElementByTestID(componentName + "Version").getText(); + } + + public static void windowZoomOut() { + final int zoomOutFactor = 3; + for (int i = 0; i < zoomOutFactor; i++) { + if(getDriver() instanceof FirefoxDriver) { + getDriver().findElement(By.tagName("html")).sendKeys(Keys.chord(Keys.CONTROL, Keys.SUBTRACT)); + } + } + } + + public static void resetZoom(){ + getDriver().findElement(By.tagName("html")).sendKeys(Keys.chord(Keys.CONTROL, "0")); + } + + public static void windowZoomOutUltimate(){ + resetZoom(); + windowZoomOut(); +// JavascriptExecutor js = (JavascriptExecutor) driver; +// js.executeScript("document.body.style.zoom='90%'"); + } + + public static void clickASDCLogo() { + WebDriverWait wait = newWait(15); + wait.until(ExpectedConditions.visibilityOfElementLocated(By.linkText("ASDC"))); + WebElement ClickASDCLogo = getDriver().findElement(By.linkText("ASDC")); + ClickASDCLogo.click(); + GeneralUIUtils.waitForLoader(); + } + + public static void sleep(int millis) { + try { + Thread.sleep(millis); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + } + + public static void moveToStep(DataTestIdEnum.StepsEnum Stepname) { + moveToStep(Stepname.getValue()); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Going to %s page ", Stepname.toString())); + } + + public static void moveToStep(String dataTestId) { + clickOnElementByTestId(dataTestId); + ultimateWait(); + } + + + public static Select getSelectList(String item, String datatestsid) { + Select selectlist = new Select(getWebElementByTestID(datatestsid)); + if (item != null) { + selectlist.selectByVisibleText(item); + Assert.assertThat(selectlist.getFirstSelectedOption().getText(), is(item)); + } + return selectlist; + } + + public static List waitForElementsListVisibilityTestMethod(DashboardCardEnum dataTestId) { + GeneralUIUtils.waitForLoader(); + return getDriver().findElements(By.xpath("//*[@data-tests-id='" + dataTestId.getValue() + "']")); + } + + public static List getElementsByCSS(String cssString) throws InterruptedException { + GeneralUIUtils.waitForLoader(); + List assets = getDriver().findElements(By.cssSelector(cssString)); + return assets; + } + + public static WebElement getElementfromElementByCSS(WebElement parentElement, String cssString){ + WebDriverWait wait = newWait(timeOut); + GeneralUIUtils.waitForLoader(); + return parentElement.findElement(By.cssSelector(cssString)); + } + + public static WebElement getElementfromElementByXPATH(WebElement parentElement, DashboardCardEnum dataTestId){ + WebDriverWait wait = newWait(timeOut); + GeneralUIUtils.waitForLoader(); + return HighlightMyElement( parentElement.findElement(By.xpath("//*[@data-tests-id='" + dataTestId.getValue() + "']"))); + } + + public static WebElement HighlightMyElement(WebElement element) { + JavascriptExecutor javascript = (JavascriptExecutor) getDriver(); + javascript.executeScript("arguments[0].setAttribute('style', arguments[1]);", element, "color: yellow; border: 4px solid yellow;"); + return element; + } + + public static WebElement getSelectedElementFromDropDown(String dataTestId){ + GeneralUIUtils.ultimateWait();; + WebElement selectedElement = new Select (getDriver().findElement(By.xpath("//*[@data-tests-id='" + dataTestId + "']"))).getFirstSelectedOption(); + return selectedElement; + } + + + public static void waitForPageLoadByReadyState() { + newWait(30).until((ExpectedCondition) wd -> + ((JavascriptExecutor) wd).executeScript("return document.readyState").equals("complete")); + } + + + public static boolean checkElementsCountInTable(int expectedElementsCount, Supplier> func) { + int maxWaitingPeriodMS = 10 * 1000; + int napPeriodMS = 100; + int sumOfWaiting = 0; + List elements = null; + boolean isKeepWaiting = false; + while (!isKeepWaiting) { + elements = func.get(); + isKeepWaiting = (expectedElementsCount == elements.size()); + sleep(isKeepWaiting ? napPeriodMS : 0); + sumOfWaiting += napPeriodMS; + if (sumOfWaiting > maxWaitingPeriodMS) + return false; + } + return true; + } + + public static String getActionDuration(Runnable func) throws Exception{ + long startTime = System.nanoTime(); + func.run(); + long estimateTime = System.nanoTime(); + long duration = TimeUnit.NANOSECONDS.toSeconds(estimateTime - startTime); + String durationString = String.format("%02d:%02d", duration / 60, duration % 60); + return durationString; + } + + public static WebElement clickOnAreaJS(String areaId) { + return clickOnAreaJS(areaId, timeOut); + } + + + public static WebElement clickOnAreaJS(String areaId, int timeout) { + try{ + ultimateWait(); + WebElement area = getWebElementByTestID(areaId); + JavascriptExecutor javascript = (JavascriptExecutor) getDriver(); + //HighlightMyElement(area); + Object executeScript = javascript.executeScript("arguments[0].click();", area, "color: yellow; border: 4px solid yellow;"); + waitForLoader(timeout); + return area; + } + catch (Exception e){ + e.printStackTrace(); + } + return null; + } + + + + public static WebElement clickOnAreaJS(WebElement areaId) throws InterruptedException { + JavascriptExecutor javascript = (JavascriptExecutor) getDriver(); + //HighlightMyElement(area); + javascript.executeScript("arguments[0].click();", areaId, "color: yellow; border: 4px solid yellow;"); + return areaId; + } + + + + public static void clickSomewhereOnPage() { + getDriver().findElement(By.cssSelector(".asdc-app-title")).click(); + } + + public static void findComponentAndClickInCatalog(String resourceName) throws Exception { + // This method will find element by element name, don't use data-tests-id argument + WebElement searchTextbox = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtons.SEARCH_BOX.getValue()); + searchTextbox.clear(); + searchTextbox.sendKeys(resourceName); + ultimateWait(); + clickOnElementByText(resourceName); + ultimateWait(); + } + + public static void clickOnElementByText(String textInElement) { + logger.info("clickOnElementByText: {}", textInElement); + WebDriverWait wait = newWait(timeOut); + HighlightMyElement(wait.until( + ExpectedConditions.elementToBeClickable(findByText(textInElement)))).click(); + } + + public static void clickOnElementByText(String textInElement, int customTimeout) { + logger.info("clickOnElementByText: {}", textInElement); + WebDriverWait wait = newWait(customTimeout); + HighlightMyElement(wait.until(ExpectedConditions.elementToBeClickable(searchByTextContaining(textInElement)))).click(); + } + + private static WebDriverWait newWait(int timeoutInSeconds) { + final WebDriver driver = getDriver(); + driver.manage().timeouts().setScriptTimeout(timeoutInSeconds, TimeUnit.SECONDS); + return new WebDriverWait(driver, timeoutInSeconds, 120); + } + + public static void clickJSOnElementByText(String textInElement) throws Exception { + WebDriverWait wait = newWait(timeOut); + clickOnAreaJS(wait.until( + ExpectedConditions.elementToBeClickable(findByText(textInElement)))); + } + + public static void fluentWaitTestID(String dataTestId, String text) { + FluentWait fluentWait = new FluentWait(getDriver()) + .withTimeout(30, TimeUnit.SECONDS) + .pollingEvery(50, TimeUnit.MILLISECONDS) + .ignoring(NoSuchElementException.class); + + fluentWait.until(ExpectedConditions.refreshed( + ExpectedConditions.textToBePresentInElementValue(By.xpath("//*[@data-tests-id='" + dataTestId + "']"), text))); + } + + public static void regularWait(WebElement element, String text){ + WebDriverWait wait = newWait(timeOut); + + wait.until(ExpectedConditions.textToBePresentInElementValue(element, text)); + } + + public static void waitForAngular(){ + WebDriverWait wait = newWait(90); + wait.until(AdditionalConditions.pageLoadWait()); + wait.until(AdditionalConditions.angularHasFinishedProcessing()); + } + + public static void waitForAngular2(){ + WebDriverWait wait = newWait(90); + wait.until(AdditionalConditions.pageLoadWait()); + try { + WebDriverWait briefWait = newWait(2); + briefWait.until(AdditionalConditions.angular2HasFinishedProcessing()); + } catch (TimeoutException | org.openqa.selenium.ScriptTimeoutException e) { + logger.info("Ignoring TimeoutException while waiting for angular2: {}", e, e); + } + } + + public static Object getAllElementAttributes(WebElement element) { + return ((JavascriptExecutor)getDriver()).executeScript("var s = []; var attrs = arguments[0].attributes; for (var l = 0; l < attrs.length; ++l) { var a = attrs[l]; s.push(a.name + ':' + a.value); } ; return s;", element); + } + + public static boolean isElementReadOnly(WebElement element){ + try { + HighlightMyElement(element).clear(); + return false; + } catch (Exception e) { + return true; + } + } + + public static boolean isElementReadOnly(String dataTestId){ + return isElementReadOnly( + waitForElementVisibilityByTestId(dataTestId)); + } + + public static boolean isElementDisabled(WebElement element){ + return HighlightMyElement(element).getAttribute("class").contains("view-mode") || + element.getAttribute("class").contains("disabled"); + } + + public static boolean isElementDisabled(String dataTestId){ + return isElementDisabled( + waitForElementVisibilityByTestId(dataTestId)); + } + + public static void ultimateWait(){ + logger.info("ultimateWait: starting"); + long startTime = System.nanoTime(); + + GeneralUIUtils.waitForAngular(); + logger.info("ultimateWait: waited for angular: {} ms", TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime)); + + GeneralUIUtils.waitForAngular2(); + logger.info("ultimateWait: waited for angular2: {} ms", TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime)); + + long estimateTime = System.nanoTime(); + long duration = TimeUnit.NANOSECONDS.toSeconds(estimateTime - startTime); + if(duration > timeOut){ + SetupCDTest.getExtendTest().log(Status.WARNING, String.format("Delays on page, %d seconds", duration)); + } + + logger.info("ultimateWait: done"); + } + + public static WebElement makeElementVisibleWithJS(WebElement element){ + String js = "arguments[0].style.height='auto'; arguments[0].style.visibility='visible';"; + ((JavascriptExecutor) getDriver()).executeScript(js, element); + return element; + } + + public static WebElement unhideElement(WebElement element, String attributeValue){ + String js = "arguments[0].setAttribute('class','" + attributeValue + "');"; + ((JavascriptExecutor) getDriver()).executeScript(js, element); + return element; + } + + public static WebElement findByText(String textInElement){ + return getDriver().findElement(searchByTextContaining(textInElement)); + } + + public static List findElementsByText(String textInElement){ + return getDriver().findElements(searchByTextContaining(textInElement)); + } + + public static By searchByTextContaining(String textInElement) { + return By.xpath("//*[contains(text(),'" + textInElement + "')]"); + } + + + public static boolean findAndWaitByText(String textInElement, int timeout){ + logger.info("findAndWaitByText: {}", textInElement); + try{ + WebDriverWait wait = newWait(timeout); + wait.until(ExpectedConditions.presenceOfElementLocated(searchByTextContaining(textInElement))); + return true; + } + catch(Exception e){ + return false; + } + } + + public static WebElement getClickableButtonBy(By by, int timout){ + try{ + WebDriverWait wait = newWait(timout); + WebElement element = wait.until(ExpectedConditions.elementToBeClickable(by)); + return element; + } + catch(Exception e){ + return null; + } + } + + + + public static WebElement getButtonWithText(String textInButton){ + try{ + return getDriver().findElement(By.xpath("//button[contains(text(),'" + textInButton + "')]")); + } + catch(Exception e) + { + return null; + } + } + + + public static List getElementsByDataTestsIdStartWith(String startWithString){ + ultimateWait(); + return getDriver().findElements(By.xpath("//*[starts-with(@data-tests-id,'" + startWithString + "')]")); + } + + public static void closeErrorMessage() { + WebElement okWebElement = getButtonWithText("OK"); + if (okWebElement != null){ + okWebElement.click(); + ultimateWait(); + } + } + + public static WebElement getElementByCSS(String cssString) throws InterruptedException { + ultimateWait(); + return getDriver().findElement(By.cssSelector(cssString)); + } + + public static String getDataTestIdAttributeValue(WebElement element) { + return element.getAttribute("data-tests-id"); + } + + public static String getTextContentAttributeValue(WebElement element) { + return element.getAttribute("textContent"); + } + + public static WebElement getElementInsideElementByDataTestsId(WebElement element, String dataTestId) { + try{ + return element.findElement(By.xpath("//*[@data-tests-id='" + dataTestId + "']")); + } + catch(Exception e){ + return null; + } + } + + public static void clickOnElementByCSS(String cssString) throws Exception { + WebDriverWait wait = newWait(timeOut); + wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(cssString))).click(); + ultimateWait(); + } + public static String getRandomComponentName(String prefix) { + return prefix + GeneralUIUtils.randomNumber(); + } + public static int randomNumber() { + Random r = new Random(); + return r.nextInt(10000); + } + + public static void waitForUINotification() { + List notificationElements = getDriver().findElements(By.className("ui-notification")); + if (!notificationElements.isEmpty()){ + notificationElements.forEach(WebElement::click); + } + } + + public static boolean checkForDisabledAttribute(String dataTestId){ + Object elementAttributes = getAllElementAttributes(waitForElementVisibilityByTestId(dataTestId)); + return elementAttributes.toString().contains("disabled"); + } + + public static void dragAndDropElementByY(WebElement area, int yOffset) { + Actions actions = new Actions(getDriver()); + actions.dragAndDropBy(area, 10, yOffset).perform(); + ultimateWait(); + } + + public static void waitForBackLoader() { + waitForBackLoader(timeOut); + } + + public static void waitForBackLoader(int timeOut) { + sleep(1); + waitForElementInVisibilityBy(By.className("tlv-loader-back"), timeOut); + } + +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/utilities/GeneralUtility.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/utilities/GeneralUtility.java new file mode 100644 index 000000000..f2e834e03 --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/utilities/GeneralUtility.java @@ -0,0 +1,155 @@ +/*- + * ============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.onap.sdc.ci.tests.utilities; + +import java.io.File; +import java.io.IOException; +import java.util.List; +import java.util.regex.Pattern; + +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.io.FileUtils; + +public class GeneralUtility { + + public static boolean generateTextFile(String fileName, String fileData) { + boolean isSuccessfull = true; + try { + FileUtils.writeStringToFile(new File(fileName), fileData); + } catch (IOException e) { + isSuccessfull = false; + } + return isSuccessfull; + } + + /** + * Use with care, usage is not advised!!! + * The method only checks if String does not contain special characters + length divided by 4 with no remainder. + * The methods contained in other common libraries do the same. + */ + public static boolean isBase64Encoded(byte[] data) { + return Base64.isBase64(data); + } + + /** + *Use with care, usage is not advised!!! + * The method only checks if String does not contain special characters + length divided by 4 with no remainder. + * The methods contained in other common libraries do the same. + */ + public static boolean isBase64Encoded(String str) { + boolean isEncoded = false; + try { + // checks if the string was properly padded to the + isEncoded = ((str.length() % 4 == 0) && (Pattern.matches("\\A[a-zA-Z0-9/+]+={0,2}\\z", str))); + if (isEncoded) { + // If no exception is caught, then it is possibly a base64 + // encoded string + byte[] data = Base64.decodeBase64(str); + } + + } catch (Exception e) { + // If exception is caught, then it is not a base64 encoded string + isEncoded = false; + } + return isEncoded; + } + + /** + * Checks whether the passed string exceeds a limit of number of characters. + * + * @param str + * @param limit + * @return the result of comparison, or false if str is null. + */ + public static boolean isExceedingLimit(String str, int limit) { + if (str == null) { + return false; + } + return str.length() > limit; + } + + /** + * Checks the passed string list whether the cumulative length of strings and delimiters between them exceeds a limit of number of characters. For example for list ("one","two","three") with delimiter "," the length of list is calculated + * 3+1+3+1+5=13 + * + * @param strList + * @param limit + * @param delimiterLength + * - 0 if there is no delimeter. + * @return the result of comparison, or false if strList is null. + */ + public static boolean isExceedingLimit(List strList, int limit, int delimiterLength) { + if (strList == null || strList.isEmpty()) { + return false; + } + int sum = 0; + int size = strList.size(); + for (int i = 0; i < size - 1; i++) { + String str = strList.get(i); + if (str != null) { + sum += str.length(); + } + sum += delimiterLength; + } + String str = strList.get(size - 1); + if (str != null) { + sum += str.length(); + } + return sum > limit; + } + + /** + * Return the extension as the substring from the last dot. For input "kuku.txt", "txt" will be returned. If no dot is found or input is null, empty string is returned. + * + * @param fileName + * @return extension + */ + public static String getFilenameExtension(String fileName) { + String res = Constants.EMPTY_STRING; + if (fileName != null) { + int indexOf = fileName.lastIndexOf('.'); + if (indexOf != -1 && indexOf < (fileName.length() - 1)) { + res = fileName.substring(indexOf + 1); + } + } + return res; + } + + public static String calculateMD5ByByteArray(byte[] payload) { + String decodedMd5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(payload); + byte[] encodeMd5 = Base64.encodeBase64(decodedMd5.getBytes()); + return new String(encodeMd5); + + } + + /** + * + * @param data + * @return + */ + public static String calculateMD5ByString(String data) { + String calculatedMd5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(data); + + // encode base-64 result + byte[] encodeBase64 = Base64.encodeBase64(calculatedMd5.getBytes()); + return new String(encodeBase64); + } +} diff --git a/vid-automation/src/main/java/org/onap/sdc/ci/tests/utilities/LoginUtils.java b/vid-automation/src/main/java/org/onap/sdc/ci/tests/utilities/LoginUtils.java new file mode 100644 index 000000000..eca3599c6 --- /dev/null +++ b/vid-automation/src/main/java/org/onap/sdc/ci/tests/utilities/LoginUtils.java @@ -0,0 +1,42 @@ +package org.onap.sdc.ci.tests.utilities; + +import org.onap.sdc.ci.tests.datatypes.UserCredentials; +import org.onap.sdc.ci.tests.datatypes.UserRoleEnum; +import org.openqa.selenium.By; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.support.ui.ExpectedConditions; +import org.openqa.selenium.support.ui.WebDriverWait; + +public class LoginUtils { + + private static final String WEB_SEAL_PASSWORD = "123123a"; + + public static void loginToLocalWebsealSimulator(UserRoleEnum role) { + WebDriver driver = GeneralUIUtils.getDriver(); + WebDriverWait wait = new WebDriverWait(driver, 30); + + wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.xpath("//*[@method='" + "post" + "']")))); + + WebElement userIdTextbox = GeneralUIUtils.getWebElementBy(By.name("userId")); + userIdTextbox.sendKeys(role.getUserId()); + WebElement passwordTextbox = GeneralUIUtils.getWebElementBy(By.name("password")); + passwordTextbox.sendKeys(WEB_SEAL_PASSWORD); + + wait.until(ExpectedConditions.elementToBeClickable(driver.findElement(By.xpath("//*[@value='" + "Login" + "']")))).click(); + } + + public static void loginToLocalWebsealSimulator(UserCredentials user) { + WebDriver driver = GeneralUIUtils.getDriver(); + WebDriverWait wait = new WebDriverWait(driver, 30); + + wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.xpath("//*[@method='" + "post" + "']")))); + + WebElement userIdTextbox = GeneralUIUtils.getWebElementBy(By.name("userId")); + userIdTextbox.sendKeys(user.getUserId()); + WebElement passwordTextbox = GeneralUIUtils.getWebElementBy(By.name("password")); + passwordTextbox.sendKeys(user.getPassword()); + + wait.until(ExpectedConditions.elementToBeClickable(driver.findElement(By.xpath("//*[@value='" + "Login" + "']")))).click(); + } +} -- cgit 1.2.3-korg