summaryrefslogtreecommitdiffstats
path: root/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils
diff options
context:
space:
mode:
Diffstat (limited to 'asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils')
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/ArtifactUtils.java66
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/DbUtils.java286
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/Decoder.java62
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/DistributionUtils.java166
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/ReqCap.java630
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/ToscaParserUtils.java305
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/Utils.java656
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/cassandra/CassandraUtils.java225
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/cassandra/CassandraUtils2.java172
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/AtomicOperationUtils.java692
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/Convertor.java341
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/ElementFactory.java948
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/FileUtils.java137
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/ImportUtils.java57
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/graph/GraphFileUtils.java60
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ArtifactRestUtils.java920
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/AssetRestUtils.java557
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/BaseRestUtils.java263
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CatalogRestUtils.java87
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CategoryRestUtils.java308
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CommonRestUtils.java22
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ComponentInstanceRestUtils.java304
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ComponentRestUtils.java70
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ConsumerRestUtils.java245
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/EcompUserRestUtils.java252
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/GroupRestUtils.java61
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ImportRestUtils.java399
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/InputsRestUtils.java122
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/LifecycleRestUtils.java410
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ProductRestUtils.java196
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/PropertyRestUtils.java262
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtils.java725
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtilsExternalAPI.java63
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResponseParser.java564
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ServiceRestUtils.java285
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/UserRestUtils.java281
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ArtifactValidationUtils.java223
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/AuditValidationUtils.java1390
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/BaseValidationUtils.java116
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/CategoryValidationUtils.java126
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/CsarValidationUtils.java298
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/DistributionValidationUtils.java86
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ErrorValidationUtils.java121
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ProductValidationUtils.java239
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ResourceValidationUtils.java358
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ServiceValidationUtils.java131
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/TestYamlParser.java92
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/UserValidationUtils.java275
48 files changed, 0 insertions, 14654 deletions
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/ArtifactUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/ArtifactUtils.java
deleted file mode 100644
index 7a26403053..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/ArtifactUtils.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utils;
-
-import org.apache.commons.codec.binary.Base64;
-import org.openecomp.sdc.be.model.ArtifactDefinition;
-import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
-import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
-
-public class ArtifactUtils {
- /**
- * Converts ArtifactReqDetails to ArtifactDefinition
- * @param artifactReq
- * @return
- */
- public static ArtifactDefinition convertArtifactReqToDefinition(ArtifactReqDetails artifactReq) {
- ArtifactDefinition artifact = new ArtifactDefinition();
- artifact.setArtifactLabel(artifactReq.getArtifactLabel());
- artifact.setArtifactDisplayName(artifactReq.getArtifactDisplayName());
- artifact.setArtifactGroupType(ArtifactGroupTypeEnum.findType(artifactReq.getArtifactGroupType()));
- artifact.setArtifactType(artifactReq.getArtifactType().toUpperCase());
- artifact.setArtifactName(artifactReq.getArtifactName());
- artifact.setDescription(artifactReq.getDescription());
- artifact.setUniqueId(artifactReq.getUniqueId());
- artifact.setTimeout(artifactReq.getTimeout());
- artifact.setEsId(artifactReq.getUniqueId());
-
- return artifact;
- }
- /**
- * Converts ArtifactDefinition to ArtifactReqDetails
- * @param artifactDef
- * @return
- */
- public static ArtifactReqDetails convertArtifactDefinitionToArtifactReqDetails( ArtifactDefinition artifactDef) {
- ArtifactReqDetails artifactReq = new ArtifactReqDetails();
- artifactReq.setArtifactLabel(artifactDef.getArtifactLabel());
- artifactReq.setArtifactDisplayName(artifactDef.getArtifactDisplayName());
- artifactReq.setArtifactGroupType(artifactDef.getArtifactGroupType().getType());
- artifactReq.setArtifactType(artifactDef.getArtifactType().toUpperCase());
- artifactReq.setArtifactName(artifactDef.getArtifactName());
- artifactReq.setDescription(artifactDef.getDescription());
- artifactReq.setUniqueId(artifactDef.getUniqueId());
- artifactReq.setTimeout(artifactDef.getTimeout());
- artifactReq.setPayload(Base64.encodeBase64String(artifactDef.getPayloadData()));
- return artifactReq;
- }
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/DbUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/DbUtils.java
deleted file mode 100644
index 41aa1a567f..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/DbUtils.java
+++ /dev/null
@@ -1,286 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utils;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-
-import org.apache.tinkerpop.gremlin.structure.Edge;
-import org.apache.tinkerpop.gremlin.structure.Element;
-import org.apache.tinkerpop.gremlin.structure.Vertex;
-import org.apache.tinkerpop.gremlin.structure.util.ElementHelper;
-import org.openecomp.sdc.ci.tests.api.Urls;
-import org.openecomp.sdc.ci.tests.config.Config;
-import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest;
-import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
-import org.openecomp.sdc.ci.tests.users.UserAuditJavaObject;
-import org.openecomp.sdc.ci.tests.utils.cassandra.CassandraUtils;
-
-import com.google.gson.Gson;
-import com.google.gson.JsonArray;
-import com.google.gson.JsonElement;
-import com.google.gson.JsonObject;
-import com.google.gson.JsonParser;
-import com.thinkaurelius.titan.core.TitanEdge;
-import com.thinkaurelius.titan.core.TitanFactory;
-import com.thinkaurelius.titan.core.TitanGraph;
-import com.thinkaurelius.titan.core.TitanVertex;
-
-import fj.data.Either;
-
-public class DbUtils {
-
- private static String titanConfigFilePath;
- private static TitanGraph titanGraph;
-
- public static void cleanAllAudits() throws IOException {
- CassandraUtils.truncateAllTables("sdcaudit");
- }
-
- public static RestResponse deleteFromEsDbByPattern(String patternToDelete) throws IOException {
- Config config = Utils.getConfig();
- String url = String.format(Urls.GET_SEARCH_DATA_FROM_ES, config.getEsHost(), config.getEsPort(),
- patternToDelete);
- HttpRequest httpRequest = new HttpRequest();
- RestResponse restResponse = httpRequest.httpSendDelete(url, null);
- restResponse.getErrorCode();
- cleanAllAudits();
-
- return restResponse;
- }
-
- public static RestResponse getFromEsByPattern(String patternToGet) throws IOException {
- Config config = Utils.getConfig();
- String url = String.format(Urls.GET_SEARCH_DATA_FROM_ES, config.getEsHost(), config.getEsPort(), patternToGet);
- HttpRequest httpRequest = new HttpRequest();
- RestResponse restResponse = httpRequest.httpSendGet(url, null);
- restResponse.getErrorCode();
-
- return restResponse;
- }
-
- public Either<Vertex, Boolean> getVertexByUId(String uid) {
- TitanGraph titanGraph = getTitanGraph();
- Either<Vertex, Boolean> result = Either.right(false);
- // Iterator<Vertex> vertexItr = titanGraph.getVertices().iterator();
-
- Iterator<TitanVertex> vertexItr = titanGraph.query().vertices().iterator();
- while (vertexItr.hasNext()) {
- Vertex vertex = vertexItr.next();
- // String uidFoundVal = vertex.getProperty("uid");
- String uidFoundVal = vertex.value("uid");
- if (uid.equals(uidFoundVal)) {
- result = Either.left(vertex);
- }
- }
- return result;
- }
-
- public static TitanState getCurrentTitanState() {
- TitanGraph titanGraph = getTitanGraph();
- List<Vertex> vertices = new ArrayList<>();
- List<Edge> edges = new ArrayList<>();
- // Iterator<Edge> edgesItr = titanGraph.getEdges().iterator();
- Iterator<TitanEdge> edgesItr = titanGraph.query().edges().iterator();
- // Iterator<Vertex> verticesItr = titanGraph.getVertices().iterator();
- Iterator<TitanVertex> verticesItr = titanGraph.query().vertices().iterator();
- while (edgesItr.hasNext()) {
- edges.add(edgesItr.next());
- }
- while (verticesItr.hasNext()) {
- vertices.add(verticesItr.next());
- }
-
- TitanState currState = new TitanState(edges, vertices);
- return currState;
-
- }
-
- private static TitanGraph getTitanGraph() {
- if (titanGraph == null) {
- titanGraph = TitanFactory.open(titanConfigFilePath);
- }
- return titanGraph;
- }
-
- public void restoreToTitanState(TitanState titanStateToRestoreTo) {
- List<Vertex> verticesToRemove = new ArrayList<>(), verticesToAdd = new ArrayList<>();
- List<Edge> edgesToRemove = new ArrayList<>(), edgesToAdd = new ArrayList<>();
-
- TitanState currentTitanState = getCurrentTitanState();
-
- List<Edge> joinedEdges = new ArrayList<>();
- joinedEdges.addAll(titanStateToRestoreTo.edges);
- joinedEdges.retainAll(currentTitanState.edges);
-
- List<Vertex> joinedVertices = new ArrayList<>();
- joinedVertices.addAll(titanStateToRestoreTo.vertices);
- joinedVertices.retainAll(currentTitanState.vertices);
-
- edgesToRemove.addAll(currentTitanState.edges);
- edgesToRemove.removeAll(joinedEdges);
-
- verticesToRemove.addAll(currentTitanState.vertices);
- verticesToRemove.removeAll(joinedVertices);
-
- edgesToAdd.addAll(titanStateToRestoreTo.edges);
- edgesToAdd.removeAll(joinedEdges);
-
- verticesToAdd.addAll(titanStateToRestoreTo.vertices);
- verticesToAdd.removeAll(joinedVertices);
-
- modifyGraphAccordingToDelta(verticesToRemove, verticesToAdd, edgesToRemove, edgesToAdd);
-
- }
-
- private void modifyGraphAccordingToDelta(List<Vertex> verticesToRemove, List<Vertex> verticesToAdd,
- List<Edge> edgesToRemove, List<Edge> edgesToAdd) {
-
- TitanGraph titanGraph = getTitanGraph();
-
- for (Vertex vertex : verticesToRemove) {
- // titanGraph.removeVertex(vertex);
- vertex.remove();
- }
- for (Vertex vertex : verticesToAdd) {
- TitanVertex titanVertex = titanGraph.addVertex();
- copyProperties(vertex, titanVertex);
- }
-
- for (Edge edge : edgesToRemove) {
- // titanGraph.removeEdge(edge);
- edge.remove();
- }
-
- for (Edge edge : edgesToAdd) {
- // Element addedEdge = titanGraph.addEdge(edge.getId(),
- // edge.getVertex(Direction.OUT), edge.getVertex(Direction.IN),
- // edge.getLabel());
-
- // Edge edge = tGraph.addEdge(null, fromV.left().value(),
- // toV.left().value(), type);
-
- Element addedEdge = edge.outVertex().addEdge(edge.label(), edge.inVertex());
-
- copyProperties(edge, addedEdge);
-
- }
-
- // titanGraph.commit();
- titanGraph.tx().commit();
-
- }
-
- private void copyProperties(Element copyFrom, Element copyTo) {
- // Set<String> properties = copyFrom.getPropertyKeys();
- Set<String> properties = copyFrom.keys();
- for (String propertyKey : properties) {
- // copyTo.setProperty(propertyKey,
- // copyFrom.getProperty(propertyKey));
- copyTo.property(propertyKey, copyFrom.value(propertyKey));
- }
-
- }
-
- public static class TitanState {
- private List<Edge> edges;
- private List<Vertex> vertices;
-
- private TitanState(List<Edge> edges, List<Vertex> vertices) {
- this.edges = edges;
- this.vertices = vertices;
- }
-
- @Override
- public String toString() {
- return "TitanState [edges=" + edges.size() + ", vertices=" + vertices.size() + "]";
- }
-
- }
-
- public void shutDowntitan() {
- if (titanGraph != null) {
- // titanGraph.shutdown();
- titanGraph.close();
- }
- }
-
- public static void setProperties(Element element, Map<String, Object> properties) {
-
- if (properties != null && false == properties.isEmpty()) {
-
- Object[] propertyKeyValues = new Object[properties.size() * 2];
- int i = 0;
- for (Entry<String, Object> entry : properties.entrySet()) {
- propertyKeyValues[i++] = entry.getKey();
- propertyKeyValues[i++] = entry.getValue();
- }
-
- ElementHelper.attachProperties(element, propertyKeyValues);
-
- }
-
- }
-
- public static UserAuditJavaObject parseAuditRespByAction(String action) throws Exception {
-
- // String index = "auditingevents*";
- // String type = "useradminevent";
- // String pattern = "/_search?q=action:\""+action+"\"";
- // String auditingMessage = retrieveAuditMessageByIndexType(index, type,
- // pattern);
- UserAuditJavaObject auditParsedResp = new UserAuditJavaObject();
- Gson gson = new Gson();
-
- String pattern = "/_search?q=ACTION:\"" + action + "\"";
- String auditingMessage = retrieveAuditMessagesByPattern(pattern);
- JsonElement jElement = new JsonParser().parse(auditingMessage);
- JsonObject jObject = jElement.getAsJsonObject();
- JsonObject hitsObject = (JsonObject) jObject.get("hits");
- JsonArray hitsArray = (JsonArray) hitsObject.get("hits");
- // for (int i = 0; i < hitsArray.size();){
- if (hitsArray.size() == 0) {
- return auditParsedResp;
- }
- JsonObject jHitObject = (JsonObject) hitsArray.get(0);
- JsonObject jSourceObject = (JsonObject) jHitObject.get("_source");
-
- auditParsedResp = gson.fromJson(jSourceObject, UserAuditJavaObject.class);
-
- return auditParsedResp;
-
- }
-
- public static String retrieveAuditMessagesByPattern(String pattern) throws IOException {
-
- Config config = Utils.getConfig();
- HttpRequest getAuditingMessage = new HttpRequest();
- String url = String.format(Urls.GET_SEARCH_DATA_FROM_ES, config.getEsHost(), config.getEsPort(), pattern);
- RestResponse restResponse = getAuditingMessage.httpSendGet(url, null);
-
- return restResponse.getResponse();
- }
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/Decoder.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/Decoder.java
deleted file mode 100644
index 7d90eb0b6d..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/Decoder.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utils;
-
-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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/DistributionUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/DistributionUtils.java
deleted file mode 100644
index 6bfa1b8e94..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/DistributionUtils.java
+++ /dev/null
@@ -1,166 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utils;
-
-import java.io.IOException;
-import java.text.ParseException;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-
-import org.openecomp.sdc.be.model.ArtifactDefinition;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.Service;
-import org.openecomp.sdc.ci.tests.datatypes.ServiceDistributionStatus;
-import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
-import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
-import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
-import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
-import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
-
-//
-//
-//
-// import static org.testng.AssertJUnit.assertTrue;
-// import static org.testng.AssertJUnit.assertEquals;
-// import static org.testng.AssertJUnit.assertNotNull;
-// import java.io.IOException;
-// import java.util.HashMap;
-// import java.util.Map;
-//
-// import org.apache.log4j.Logger;
-//
-// import org.openecomp.sdc.be.model.ArtifactDefinition;
-// import org.openecomp.sdc.ci.tests.api.Urls;
-// import org.openecomp.sdc.ci.tests.config.Config;
-// import
-// org.openecomp.sdc.ci.tests.executeOnUGN.distributionClient.ClientConfiguration;
-// import org.openecomp.sdc.ci.tests.http.HttpHeaderEnum;
-// import org.openecomp.sdc.ci.tests.http.RestResponse;
-// import org.openecomp.sdc.ci.tests.run.StartTest;
-// import com.google.gson.Gson;
-//
- public class DistributionUtils {
-
- final static String serviceDistributionSuffix = "/sdc/v1/catalog/services/";
-
- public static ServiceDistributionStatus getLatestServiceDistributionObject(Service service) throws IOException, ParseException {
- ServiceDistributionStatus serviceDistributionStatus = null;
- RestResponse distributionServiceList = ServiceRestUtils.getDistributionServiceList(service, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
- Map<Long, ServiceDistributionStatus> serviveDistributionStatusMap = ResponseParser.convertServiceDistributionStatusToObject(distributionServiceList.getResponse());
- if(serviveDistributionStatusMap.size() != 0){
- serviceDistributionStatus = getLatestServiceDistributionObjectFromMap(serviveDistributionStatusMap);
- return serviceDistributionStatus;
- }
-
- return null;
- }
-
- public static ServiceDistributionStatus getLatestServiceDistributionObjectFromMap(Map<Long, ServiceDistributionStatus> serviceDistributionStatusMap) {
-
- ServiceDistributionStatus serviceDistributionStatus = null;
- if (serviceDistributionStatusMap.size() == 1 ){
- for (Entry<Long, ServiceDistributionStatus> entry : serviceDistributionStatusMap.entrySet()) {
- return entry.getValue();
- }
- }
- else{
- serviceDistributionStatus = getFilteredServiceDistributionObject(serviceDistributionStatusMap);
- }
-
- return serviceDistributionStatus;
- }
-
- private static ServiceDistributionStatus getFilteredServiceDistributionObject(Map<Long, ServiceDistributionStatus> serviceDistributionStatusMap) {
-
- List<Long> list = new ArrayList<Long>();
- list.addAll(serviceDistributionStatusMap.keySet());
- Collections.sort(list);
- return serviceDistributionStatusMap.get(list.get(list.size() - 1));
- }
-
- public static Map<String, String> getArtifactsMapOfDistributedService(Service service) throws Exception{
-
- Map<String, String> expectedDistributionArtifactMap = new HashMap<String, String>();
- expectedDistributionArtifactMap = addServiceDeploymentArtifactToMap(service, expectedDistributionArtifactMap);
- expectedDistributionArtifactMap = addComponentInstancesDeploymentArtifactToMap(service, expectedDistributionArtifactMap);
-
- return expectedDistributionArtifactMap;
- }
-
-
- public static Map<String, String> addServiceDeploymentArtifactToMap(Service service, Map<String, String> distributionArtifactMap){
-
- Map<String, ArtifactDefinition> deploymentArtifacts = service.getDeploymentArtifacts();
- if (deploymentArtifacts != null && deploymentArtifacts.size() > 0){
- for(Entry<String, ArtifactDefinition> artifact : deploymentArtifacts.entrySet()){
- String url = buildServiceDeploymentUrl(service, artifact.getValue().getArtifactName(), artifact.getValue().getArtifactUUID());
- distributionArtifactMap.put(artifact.getKey(), url);
- }
- }
-
- return distributionArtifactMap;
- }
-
- private static String buildServiceDeploymentUrl(Service service, String artifactName, String artifactUUID) {
-// format "/sdc/v1/catalog/services/" + service.getSystemName() + "/" + service.getVersion() + "/artifacts/AAI-" + service.getName() + "-service-1.xml"
- return serviceDistributionSuffix + service.getSystemName() + "/" + service.getVersion() + "/artifacts/" + artifactName;
- }
-
- public static String buildResourceInstanceDeploymentUrl(Service service, String artifactName, String artifactUUID){
-
-// /sdc/v1/catalog/services/Servicefordistribution/1.0 /resourceInstances/nestedfrommarina2 /artifacts/FEAdd_On_Module_vProbeLauncher.yaml
- String resourceInstanceNormalizedName = getResourceInstanceNormalizeName(service, artifactName, artifactUUID );
- return serviceDistributionSuffix + service.getSystemName() + "/" + service.getVersion() + "/resourceInstances/" + resourceInstanceNormalizedName +"/artifacts/" + artifactName;
- }
-
- public static String getResourceInstanceNormalizeName(Service service, String artifactName, String artifactUUID) {
- for (ComponentInstance componentInstance : service.getComponentInstances()){
- for(String key : componentInstance.getDeploymentArtifacts().keySet()){
- if(componentInstance.getDeploymentArtifacts().get(key).getArtifactUUID().equals(artifactUUID)) {
- return componentInstance.getNormalizedName();
- }
- }
- }
- return null;
- }
-
- public static Map<String, String> addComponentInstancesDeploymentArtifactToMap(Service service, Map<String, String> distributionArtifactMap){
-// TODO Andrey create correct method to build RI url
- if(service.getComponentInstances() != null && service.getComponentInstances().size() != 0){
- for(ComponentInstance componentInstance : service.getComponentInstances()){
- if (componentInstance.getDeploymentArtifacts() != null && componentInstance.getDeploymentArtifacts().size() != 0){
- for(Entry<String, ArtifactDefinition> artifact : componentInstance.getDeploymentArtifacts().entrySet()){
- String url = buildResourceInstanceDeploymentUrl(service, artifact.getValue().getArtifactName(), artifact.getValue().getArtifactUUID());;
- distributionArtifactMap.put(artifact.getKey(), url);
- }
- }
- }
- }
-
- return distributionArtifactMap;
- }
-
-
- }
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/ReqCap.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/ReqCap.java
deleted file mode 100644
index 66379f18ef..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/ReqCap.java
+++ /dev/null
@@ -1,630 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utils;
-
-import static org.testng.AssertJUnit.assertEquals;
-import static org.testng.AssertJUnit.assertNotNull;
-import static org.testng.AssertJUnit.assertTrue;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-import java.util.function.Function;
-import java.util.stream.Collectors;
-
-import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
-import org.openecomp.sdc.be.model.CapabilityDefinition;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.Product;
-import org.openecomp.sdc.be.model.RelationshipInfo;
-import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
-import org.openecomp.sdc.be.model.RequirementDefinition;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.Service;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.ComponentReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
-import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
-import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
-import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
-import org.openecomp.sdc.ci.tests.utils.rest.ComponentInstanceRestUtils;
-import org.openecomp.sdc.ci.tests.utils.rest.ProductRestUtils;
-import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
-import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
-import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
-import org.testng.Assert;
-
-public class ReqCap {
-
- public static Map<String, List<CapabilityDefinition>> expectedContainerCapabilities;
- public static Map<String, List<RequirementDefinition>> expectedContainerRequirements;
- public static Map<String, RequirementDefinition> removedRequirements;
- public static Map<String, ImmutablePair<Map<String, List<CapabilityDefinition>>, Map<String, List<RequirementDefinition>>>> expectedContInstReqCap;
-
- public static void verifyVFReqCap(String componentId) throws Exception {
- RestResponse restResponse = ResourceRestUtils.getResource(componentId);
- Resource resource = ResponseParser.parseToObject(restResponse.getResponse(), Resource.class);
- verifyReqCap(resource);
- }
-
- public static void verifyServiceReqCap(String componentId, User sdncDesignerDetails) throws Exception {
- RestResponse restResponse = ServiceRestUtils.getService(componentId, sdncDesignerDetails);
- Service service = ResponseParser.parseToObject(restResponse.getResponse(), Service.class);
- verifyReqCap(service);
- }
-
- public static void verifyProductReqCap(String componentId, User sdncPsDetails1) throws Exception {
- RestResponse restResponse = ProductRestUtils.getProduct(componentId, sdncPsDetails1.getUserId());
- Product product = ResponseParser.parseToObject(restResponse.getResponse(), Product.class);
- verifyReqCap(product);
- }
-
- public static void verifyReqCap(Component actualComponent) {
- verifyContainerReqCap(actualComponent);
- verifyCompInstReqCap(actualComponent);
- }
-
- public RestResponse changeServiceInstanceVersion(String componentUniqueId, String serviceInstanceToReplaceUniqueId,
- String serviceUniqueId, User sdncModifierDetails, ComponentTypeEnum componentType, boolean isHighestLevel)
- throws Exception {
- RestResponse changeResourceInstanceVersion = ProductRestUtils.changeServiceInstanceVersion(componentUniqueId,
- serviceInstanceToReplaceUniqueId, serviceUniqueId, sdncModifierDetails, componentType);
- if (changeResourceInstanceVersion.getErrorCode().equals(BaseRestUtils.STATUS_CODE_SUCCESS) && isHighestLevel) {
- /*
- * // Add RI Capabilities and Requirements to expected MAP -->
- * expectedVfCapabilities and expectedVfRequirements
- *
- * ComponentInstance componentInstance =
- * ResponseParser.parseToObjectUsingMapper(
- * changeResourceInstanceVersion.getResponse(),
- * ComponentInstance.class);
- * addCompInstReqCapToExpected(componentInstance, componentType);
- */
- }
- return changeResourceInstanceVersion;
- }
-
- public static void updateExpectedReqCapAfterChangeLifecycleState(String oldContainerUniqueIdToReplace,
- String newContainerUniqueId) {
-
- // Update of container req/cap
-
- Set<String> compInstKeysToChange = new HashSet<>();
-
- for (String expKey : expectedContainerCapabilities.keySet()) {
- List<CapabilityDefinition> expCapList = expectedContainerCapabilities.get(expKey);
- for (CapabilityDefinition cap : expCapList) {
- String ownerId = cap.getOwnerId();
-
- if (ownerId.contains(oldContainerUniqueIdToReplace)) {
- compInstKeysToChange.add(ownerId);
- cap.setOwnerId(cap.getOwnerId().replaceAll(oldContainerUniqueIdToReplace, newContainerUniqueId));
- }
- }
- }
-
- for (String expKey : expectedContainerRequirements.keySet()) {
- List<RequirementDefinition> expCapList = expectedContainerRequirements.get(expKey);
- for (RequirementDefinition cap : expCapList) {
- String ownerId = cap.getOwnerId();
- if (ownerId.contains(oldContainerUniqueIdToReplace)) {
- compInstKeysToChange.add(ownerId);
- cap.setOwnerId(cap.getOwnerId().replaceAll(oldContainerUniqueIdToReplace, newContainerUniqueId));
- }
- }
- }
-
- // Update of internal comp instances req/cap
- for (String oldKey : compInstKeysToChange) {
- ImmutablePair<Map<String, List<CapabilityDefinition>>, Map<String, List<RequirementDefinition>>> immutablePair = expectedContInstReqCap
- .get(oldKey);
- if (immutablePair != null) {
- expectedContInstReqCap.remove(oldKey);
- String newKey = oldKey.replaceAll(oldContainerUniqueIdToReplace, newContainerUniqueId);
- expectedContInstReqCap.put(newKey, immutablePair);
- }
- }
- }
-
- private static void verifyCompInstReqCap(Component actualComponent) {
- List<ComponentInstance> componentInstances = actualComponent.getComponentInstances();
- if (componentInstances != null) {
- assertEquals(expectedContInstReqCap.size(), componentInstances.size());
- for (ComponentInstance compInst : componentInstances) {
- String uniqueId = compInst.getUniqueId();
- // System.out.println("Verifying req/cap of component instance
- // "+ uniqueId);
- Map<String, List<RequirementDefinition>> actualCompInstReq = compInst.getRequirements();
- if (actualCompInstReq == null) {
- actualCompInstReq = new HashMap<>();
- }
- Map<String, List<CapabilityDefinition>> actualCompInstCap = compInst.getCapabilities();
- if (actualCompInstCap == null) {
- actualCompInstCap = new HashMap<>();
- }
- ImmutablePair<Map<String, List<CapabilityDefinition>>, Map<String, List<RequirementDefinition>>> expReqCap = expectedContInstReqCap
- .get(uniqueId);
- assertNotNull(expReqCap);
- // System.out.println("expected instance requirements:
- // "+expReqCap.right);
- // System.out.println("expected instance capabilities:
- // "+expReqCap.left);
- // System.out.println("actual instance requirements:
- // "+actualCompInstReq);
- // System.out.println("actual instance capabilities:
- // "+actualCompInstCap);
-
- // REQ comparison
- compareReqCapMaps(expReqCap.right, actualCompInstReq);
-
- // CAP comparison
- compareReqCapMaps(expReqCap.left, actualCompInstCap);
- }
-
- } else {
- assertTrue(expectedContInstReqCap.isEmpty());
- }
- }
-
- private static void verifyContainerReqCap(Component actualComponent) {
- Map<String, List<RequirementDefinition>> actualContainerRequirements = actualComponent.getRequirements();
- if (actualContainerRequirements == null) {
- actualContainerRequirements = new HashMap<>();
- }
- Map<String, List<CapabilityDefinition>> actualContainerCapabilities = actualComponent.getCapabilities();
- if (actualContainerCapabilities == null) {
- actualContainerCapabilities = new HashMap<>();
- }
- // System.out.println("Verifying req/cap of container component "+
- // actualComponent.getUniqueId());
- // System.out.println("expected container requirements:
- // "+expectedContainerRequirements);
- // System.out.println("expected container capabilities:
- // "+expectedContainerCapabilities);
- // System.out.println("actual container requirements:
- // "+actualContainerRequirements);
- // System.out.println("actual container capabilities:
- // "+actualContainerCapabilities);
-
- // REQ comparison
- compareReqCapMaps(expectedContainerRequirements, actualContainerRequirements);
-
- // CAP comparison
- compareReqCapMaps(expectedContainerCapabilities, actualContainerCapabilities);
- }
-
- private static <T> void compareReqCapMaps(Map<String, List<T>> expectedMap, Map<String, List<T>> actualMap) {
- assertEquals(expectedMap.size(), actualMap.size());
- for (String expKey : expectedMap.keySet()) {
- List<?> expCapList = expectedMap.get(expKey);
- List<?> actCapList = actualMap.get(expKey);
- assertEquals(expCapList.size(), actCapList.size());
- assertEquals(new HashSet<>(expCapList), new HashSet<>(actCapList));
- }
- }
-
- public static void addCompInstReqCapToExpected(ComponentInstance componentInstance,
- ComponentTypeEnum containerComponentType, User sdncDesignerDetails) throws Exception {
-
- sdncDesignerDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
- String uniqueId = componentInstance.getUniqueId();
- String name = componentInstance.getName();
- String originComponentId = componentInstance.getComponentUid();
- RestResponse getResponse = null;
- ComponentTypeEnum compInstType = getCompInstTypeByContainerType(containerComponentType);
- Component component = null;
- if (compInstType == ComponentTypeEnum.RESOURCE) {
- getResponse = ResourceRestUtils.getResource(sdncDesignerDetails, originComponentId);
- ResourceRestUtils.checkSuccess(getResponse);
- component = ResponseParser.parseToObjectUsingMapper(getResponse.getResponse(), Resource.class);
- } else if (compInstType == ComponentTypeEnum.SERVICE) {
- getResponse = ServiceRestUtils.getService(originComponentId, sdncDesignerDetails);
- ResourceRestUtils.checkSuccess(getResponse);
- component = ResponseParser.parseToObjectUsingMapper(getResponse.getResponse(), Service.class);
- } else {
- Assert.fail("Unsupported type - " + containerComponentType);
- }
-
- Map<String, List<RequirementDefinition>> resourceRequirements = component.getRequirements();
- if (resourceRequirements == null) {
- resourceRequirements = new HashMap<>();
- }
-
- Function<Entry<String, List<RequirementDefinition>>, List<RequirementDefinition>> requirementDefinitionMapper = e -> new ArrayList<>(e.getValue().stream().map(item -> new RequirementDefinition(item)).collect(Collectors.toList()));
- Map<String, List<RequirementDefinition>> reqCopy = resourceRequirements.entrySet().stream().collect(Collectors.toMap(e -> e.getKey(), requirementDefinitionMapper));
-
- Map<String, List<CapabilityDefinition>> resourceCapabilities = component.getCapabilities();
- if (resourceCapabilities == null) {
- resourceCapabilities = new HashMap<>();
- }
-
- Function<Entry<String, List<CapabilityDefinition>>, List<CapabilityDefinition>> capabilityDefinitionMapper = e -> new ArrayList<>(e.getValue().stream().map(item -> new CapabilityDefinition(item)).collect(Collectors.toList()));
- Map<String, List<CapabilityDefinition>> capCopy = resourceCapabilities.entrySet().stream().collect(Collectors.toMap(e -> e.getKey(), capabilityDefinitionMapper));
-
- setupContainerExpectedReqCap(uniqueId, name, resourceRequirements, resourceCapabilities);
- if (component.getComponentType().equals(ComponentTypeEnum.RESOURCE)
- && ((Resource) component).getResourceType() != ResourceTypeEnum.VF) {
- setupConstInstExpectedReqCap(uniqueId, name, reqCopy, capCopy);
- }
-
- // adding entry for expected componentInstance
- ImmutablePair<Map<String, List<CapabilityDefinition>>, Map<String, List<RequirementDefinition>>> compInstReqCapPair = new ImmutablePair<Map<String, List<CapabilityDefinition>>, Map<String, List<RequirementDefinition>>>(
- capCopy, reqCopy);
- expectedContInstReqCap.put(uniqueId, compInstReqCapPair);
- }
-
- private static void setupContainerExpectedReqCap(String uniqueId, String name,
- Map<String, List<RequirementDefinition>> componentRequirements,
- Map<String, List<CapabilityDefinition>> componentCapabilities) {
- for (Entry<String, List<RequirementDefinition>> resReq : componentRequirements.entrySet()) {
- List<RequirementDefinition> reqListToAdd = resReq.getValue();
- for (RequirementDefinition requirementDefinition : reqListToAdd) {
- requirementDefinition.setOwnerId(uniqueId);
- requirementDefinition.setOwnerName(name);
- }
- List<RequirementDefinition> expectedReqList = expectedContainerRequirements.get(resReq.getKey());
- if (expectedReqList == null) {
- expectedReqList = reqListToAdd;
- } else {
- expectedReqList.addAll(reqListToAdd);
- }
- expectedContainerRequirements.put(resReq.getKey(), expectedReqList);
- }
-
- for (Entry<String, List<CapabilityDefinition>> resCap : componentCapabilities.entrySet()) {
- List<CapabilityDefinition> capListToAdd = resCap.getValue();
- for (CapabilityDefinition capDefinition : capListToAdd) {
- capDefinition.setOwnerId(uniqueId);
- capDefinition.setOwnerName(name);
- }
- List<CapabilityDefinition> expectedCapList = expectedContainerCapabilities.get(resCap.getKey());
- if (expectedCapList == null) {
- expectedCapList = capListToAdd;
- } else {
- expectedCapList.addAll(capListToAdd);
- }
- expectedContainerCapabilities.put(resCap.getKey(), expectedCapList);
- }
- }
-
- private static void setupConstInstExpectedReqCap(String uniqueId, String name,
- Map<String, List<RequirementDefinition>> componentRequirements,
- Map<String, List<CapabilityDefinition>> componentCapabilities) {
- for (Entry<String, List<RequirementDefinition>> resReq : componentRequirements.entrySet()) {
- List<RequirementDefinition> reqListToAdd = resReq.getValue();
- for (RequirementDefinition requirementDefinition : reqListToAdd) {
- requirementDefinition.setOwnerId(uniqueId);
- requirementDefinition.setOwnerName(name);
- }
- }
-
- for (Entry<String, List<CapabilityDefinition>> resCap : componentCapabilities.entrySet()) {
- List<CapabilityDefinition> capListToAdd = resCap.getValue();
- for (CapabilityDefinition capDefinition : capListToAdd) {
- capDefinition.setOwnerId(uniqueId);
- capDefinition.setOwnerName(name);
- }
- }
- }
-
- private static ComponentTypeEnum getCompInstTypeByContainerType(ComponentTypeEnum componentType) {
- switch (componentType) {
- case RESOURCE:
- return ComponentTypeEnum.RESOURCE;
- case SERVICE:
- return ComponentTypeEnum.RESOURCE;
- case PRODUCT:
- return ComponentTypeEnum.SERVICE;
- default:
- break;
- }
- return null;
- }
-
- public static void deleteCompInstReqCapFromExpected(String componentInstanceId) {
- List<String> entriesRequirementsToRemove = new ArrayList<>();
- List<String> entriesCapabilitiesToRemove = new ArrayList<>();
- for (Entry<String, List<RequirementDefinition>> reqEntry : expectedContainerRequirements.entrySet()) {
- List<RequirementDefinition> reqList = reqEntry.getValue();
- List<RequirementDefinition> reqListToDelete = new ArrayList<>();
- for (RequirementDefinition requirementDefinition : reqList) {
- if (requirementDefinition.getOwnerId().equals(componentInstanceId)) {
- reqListToDelete.add(requirementDefinition);
- }
- }
- reqList.removeAll(reqListToDelete);
- if (reqList.isEmpty()) {
- entriesRequirementsToRemove.add(reqEntry.getKey());
- }
- }
-
- for (String ekey : entriesRequirementsToRemove) {
- expectedContainerRequirements.remove(ekey);
- }
-
- for (Entry<String, List<CapabilityDefinition>> capEntry : expectedContainerCapabilities.entrySet()) {
- List<CapabilityDefinition> capList = capEntry.getValue();
- List<CapabilityDefinition> capListToDelete = new ArrayList<>();
- for (CapabilityDefinition capabilityDefinition : capList) {
- if (capabilityDefinition.getOwnerId().equals(componentInstanceId)) {
- capListToDelete.add(capabilityDefinition);
- }
- }
- capList.removeAll(capListToDelete);
- if (capList.isEmpty()) {
- entriesCapabilitiesToRemove.add(capEntry.getKey());
- }
- }
- for (String ekey : entriesCapabilitiesToRemove) {
- expectedContainerCapabilities.remove(ekey);
- }
-
- expectedContInstReqCap.remove(componentInstanceId);
-
- }
-
- // Automatically updates the expected req/cap of the container
- public static RestResponse createAtomicInstanceForVF(Resource containerDetails, Resource compInstOriginDetails,
- User modifier) throws Exception {
- return createComponentInstance(containerDetails, compInstOriginDetails, modifier, ComponentTypeEnum.RESOURCE,
- true);
- }
-
- // Automatically updates the expected req/cap of the container
- public static RestResponse createAtomicInstanceForService(Service containerDetails, Resource compInstOriginDetails,
- User modifier) throws Exception {
- return createComponentInstance(containerDetails, compInstOriginDetails, modifier, ComponentTypeEnum.SERVICE,
- true);
- }
-
- // Automatically updates the expected req/cap of the container
- public static RestResponse createVFInstance(Service containerDetails, Resource compInstOriginDetails, User modifier)
- throws Exception {
- return createComponentInstance(containerDetails, compInstOriginDetails, modifier, ComponentTypeEnum.SERVICE,
- true);
- }
-
- // Automatically updates the expected req/cap of the container
- public static RestResponse createServiceInstance(Product containerDetails, Service compInstOriginDetails,
- User modifier) throws Exception {
- return createComponentInstance(containerDetails, compInstOriginDetails, modifier, ComponentTypeEnum.PRODUCT,
- true);
- }
-
- // Automatically updates the expected req/cap of the container
- public static RestResponse deleteAtomicInstanceForVF(String compInstUniqueId, Resource containerDetails,
- User modifier) throws IOException, Exception {
- return deleteComponentInstance(compInstUniqueId, containerDetails, modifier, ComponentTypeEnum.RESOURCE, true);
- }
-
- // Automatically updates the expected req/cap of the container
- public static RestResponse deleteAtomicInstanceForService(String compInstUniqueId, Service containerDetails,
- User modifier) throws IOException, Exception {
- return deleteComponentInstance(compInstUniqueId, containerDetails, modifier, ComponentTypeEnum.SERVICE, true);
- }
-
- // Automatically updates the expected req/cap of the container
- public static RestResponse deleteVFInstance(String compInstUniqueId, Service containerDetails, User modifier)
- throws IOException, Exception {
- return deleteComponentInstance(compInstUniqueId, containerDetails, modifier, ComponentTypeEnum.SERVICE, true);
-
- }
-
- // Automatically updates the expected req/cap of the container
- public static RestResponse deleteServiceInstance(String compInstUniqueId, Product containerDetails, User modifier)
- throws IOException, Exception {
- return deleteComponentInstance(compInstUniqueId, containerDetails, modifier, ComponentTypeEnum.PRODUCT, true);
- }
-
- // Setup of lower components - Doesn't affect req/cap of the container (for
- // example, setup of VF for testing a Product)
- public static RestResponse createAtomicInstanceForVFDuringSetup(Resource containerDetails,
- Resource compInstOriginDetails, User modifier) throws Exception {
- return createComponentInstance(containerDetails, compInstOriginDetails, modifier, ComponentTypeEnum.RESOURCE,
- false);
- }
-
- // Setup of lower components - Doesn't affect req/cap of the container (for
- // example, setup of VF for testing a Product)
- public static RestResponse createAtomicInstanceForServiceDuringSetup(Service containerDetails,
- Resource compInstOriginDetails, User modifier) throws Exception {
- return createComponentInstance(containerDetails, compInstOriginDetails, modifier, ComponentTypeEnum.SERVICE,
- false);
- }
-
- // Setup of lower components - Doesn't affect req/cap of the container (for
- // example, setup of VF for testing a Product)
- public static RestResponse createVFInstanceDuringSetup(Service containerDetails, Resource compInstOriginDetails,
- User modifier) throws Exception {
- return createComponentInstance(containerDetails, compInstOriginDetails, modifier, ComponentTypeEnum.SERVICE,
- false);
- }
-
- // Setup of lower components - Doesn't affect req/cap of the container (for
- // example, setup of VF for testing a Product)
- public static RestResponse createServiceInstanceDuringSetup(Product containerDetails, Service compInstOriginDetails,
- User modifier) throws Exception {
- return createComponentInstance(containerDetails, compInstOriginDetails, modifier, ComponentTypeEnum.PRODUCT,
- false);
- }
-
- // Setup of lower components - Doesn't affect req/cap of the container (for
- // example, setup of VF for testing a Product)
- public static RestResponse deleteAtomicInstanceForVFDuringSetup(String compInstUniqueId, Resource containerDetails,
- User modifier) throws IOException, Exception {
- return deleteComponentInstance(compInstUniqueId, containerDetails, modifier, ComponentTypeEnum.RESOURCE, false);
- }
-
- // Setup of lower components - Doesn't affect req/cap of the container (for
- // example, setup of VF for testing a Product)
- public static RestResponse deleteAtomicInstanceForServiceDuringSetup(String compInstUniqueId,
- Service containerDetails, User modifier) throws IOException, Exception {
- return deleteComponentInstance(compInstUniqueId, containerDetails, modifier, ComponentTypeEnum.SERVICE, false);
- }
-
- // Setup of lower components - Doesn't affect req/cap of the container (for
- // example, setup of VF for testing a Product)
- public static RestResponse deleteVFInstanceDuringSetup(String compInstUniqueId, Service containerDetails,
- User modifier) throws IOException, Exception {
- return deleteComponentInstance(compInstUniqueId, containerDetails, modifier, ComponentTypeEnum.SERVICE, false);
-
- }
-
- // Setup of lower components - Doesn't affect req/cap of the container (for
- // example, setup of VF for testing a Product)
- public static RestResponse deleteServiceInstanceDuringSetup(String compInstUniqueId, Product containerDetails,
- User modifier) throws IOException, Exception {
- return deleteComponentInstance(compInstUniqueId, containerDetails, modifier, ComponentTypeEnum.PRODUCT, false);
- }
-
- public static Component getComponentAndValidateRIs(Component componentDetails, int numberOfRIs,
- int numberOfRelations, User sdncAdminDetails) throws IOException, Exception {
-
- RestResponse getResponse = null;
- Component component = null;
- if (componentDetails instanceof Resource) {
- getResponse = ResourceRestUtils.getResource(sdncAdminDetails, componentDetails.getUniqueId());
- component = ResponseParser.parseToObjectUsingMapper(getResponse.getResponse(), Resource.class);
- } else if (componentDetails instanceof Service) {
- getResponse = ServiceRestUtils.getService((componentDetails.getUniqueId()), sdncAdminDetails);
- component = ResponseParser.parseToObjectUsingMapper(getResponse.getResponse(), Service.class);
- } else if (componentDetails instanceof Product) {
- getResponse = ProductRestUtils.getProduct(componentDetails.getUniqueId(), sdncAdminDetails.getUserId());
- component = ResponseParser.parseToObjectUsingMapper(getResponse.getResponse(), Product.class);
- } else {
- Assert.fail("Unsupported type of componentDetails - " + componentDetails.getClass().getSimpleName());
- }
- ResourceRestUtils.checkSuccess(getResponse);
- int numberOfActualRIs = component.getComponentInstances() != null ? component.getComponentInstances().size()
- : 0;
- int numberOfActualRelations = component.getComponentInstancesRelations() != null
- ? component.getComponentInstancesRelations().size() : 0;
- assertEquals("Check number of RIs meet the expected number", numberOfRIs, numberOfActualRIs);
- assertEquals("Check number of RI relations meet the expected number", numberOfRelations,
- numberOfActualRelations);
- verifyReqCap(component);
-
- return component;
- }
-
- public static void getComponentAndValidateRIsAfterChangeLifecycleState(String oldComponentUniqueIdToReplace,
- Component componentDetails, int numOfRIs, int numOfRelations, User sdncAdminDetails)
- throws IOException, Exception {
- updateExpectedReqCapAfterChangeLifecycleState(oldComponentUniqueIdToReplace, componentDetails.getUniqueId());
- getComponentAndValidateRIs(componentDetails, numOfRIs, numOfRelations, sdncAdminDetails);
- }
-
- private static RestResponse createComponentInstance(Component containerDetails, Component compInstOriginDetails,
- User modifier, ComponentTypeEnum containerComponentTypeEnum, boolean isHighestLevel)
- throws IOException, Exception {
- ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory
- .getComponentInstance(compInstOriginDetails);
- RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
- resourceInstanceReqDetails, modifier, containerDetails.getUniqueId(), containerComponentTypeEnum);
- if (createResourceInstanceResponse.getErrorCode().equals(BaseRestUtils.STATUS_CODE_CREATED) && isHighestLevel) {
- // Add RI Capabilities and Requirements to expected MAP -->
- // expectedVfCapabilities and expectedVfRequirements
- ComponentInstance componentInstance = ResponseParser
- .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class);
- addCompInstReqCapToExpected(componentInstance, containerComponentTypeEnum, modifier);
- }
- return createResourceInstanceResponse;
- }
-
- private static RestResponse deleteComponentInstance(String compInstUniqueId, Component containerDetails,
- User modifier, ComponentTypeEnum componentTypeEnum, boolean isHighestLevel) throws Exception {
- RestResponse deleteResourceInstanceResponse = ComponentInstanceRestUtils.deleteComponentInstance(modifier,
- containerDetails.getUniqueId(), compInstUniqueId, componentTypeEnum);
- if (deleteResourceInstanceResponse.getErrorCode().equals(BaseRestUtils.STATUS_CODE_DELETE) && isHighestLevel) {
- deleteCompInstReqCapFromExpected(compInstUniqueId);
- }
- return deleteResourceInstanceResponse;
- }
-
- public static RestResponse associateComponentInstancesForService(RequirementCapabilityRelDef requirementDef,
- ComponentReqDetails containerDetails, User user) throws IOException {
-
- RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, user,
- containerDetails.getUniqueId(), ComponentTypeEnum.SERVICE);
- ResourceRestUtils.checkSuccess(associateInstances);
- deleteAssociatedFromExpected(requirementDef);
- return associateInstances;
- }
-
- private static void deleteAssociatedFromExpected(RequirementCapabilityRelDef requirementDef) {
- // removing from requirements
- RelationshipInfo relationship = requirementDef.getRelationships().get(0).getRelation();
- String type = relationship.getRelationship().getType();
- String fromId = requirementDef.getFromNode();
- List<RequirementDefinition> reqList = expectedContainerRequirements.get(type);
- RequirementDefinition toDelete = null;
- if (reqList != null) {
- for (RequirementDefinition reqDef : reqList) {
- if (reqDef.getOwnerId().equals(fromId)) {
- toDelete = reqDef;
- }
- }
- if (toDelete != null) {
- reqList.remove(toDelete);
- if (reqList.isEmpty()) {
- expectedContainerRequirements.remove(type);
- }
- removedRequirements.put(toDelete.getCapability() + " " + toDelete.getOwnerId(), toDelete);
- }
- }
- }
-
- public static void dissociateComponentInstancesForService(RequirementCapabilityRelDef requirementDef,
- ComponentReqDetails containerDetails, User user) throws IOException {
-
- RestResponse dissociateInstances = ComponentInstanceRestUtils.dissociateInstances(requirementDef, user,
- containerDetails.getUniqueId(), ComponentTypeEnum.SERVICE);
- ResourceRestUtils.checkSuccess(dissociateInstances);
- addDissociatedToExpected(requirementDef);
- }
-
- private static void addDissociatedToExpected(RequirementCapabilityRelDef requirementDef) {
- // adding to requirements
- RelationshipInfo relationship = requirementDef.getRelationships().get(0).getRelation();
- String type = relationship.getRelationship().getType();
- String fromId = requirementDef.getFromNode();
- String key = type + " " + fromId;
- RequirementDefinition requirementDefinition = removedRequirements.get(key);
- if (requirementDefinition != null) {
- List<RequirementDefinition> reqList = expectedContainerRequirements.get(type);
- if (reqList == null) {
- reqList = new ArrayList<>();
- expectedContainerRequirements.put(type, reqList);
- }
- reqList.add(requirementDefinition);
- }
- }
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/ToscaParserUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/ToscaParserUtils.java
deleted file mode 100644
index 5449a5fc6b..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/ToscaParserUtils.java
+++ /dev/null
@@ -1,305 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utils;
-
-import static org.testng.AssertJUnit.assertNotNull;
-
-import java.io.ByteArrayInputStream;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-
-import org.apache.commons.codec.binary.Base64;
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.model.ArtifactUiDownloadData;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.ci.tests.datatypes.enums.ToscaKeysEnum;
-import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
-import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaDefinition;
-import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaNodeTemplatesTopologyTemplateDefinition;
-import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaNodeTypesDefinition;
-import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaPropertiesNodeTemplatesDefinition;
-import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaRequirementsNodeTemplatesDefinition;
-import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaTopologyTemplateDefinition;
-import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
-import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
-import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
-import org.openecomp.sdc.ci.tests.utils.validation.CsarValidationUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.yaml.snakeyaml.Yaml;
-
-public class ToscaParserUtils {
-
- private static Logger log = LoggerFactory.getLogger(ToscaParserUtils.class.getName());
-
- public static Map<?, ?> getToscaYamlMap(String csarUUID, String fileLocation) throws Exception {
- String csarPayload = CsarValidationUtils.getCsarPayload(csarUUID, fileLocation);
- if (csarPayload != null) {
- Yaml yaml = new Yaml();
- Map<?, ?> map = (Map<?, ?>) yaml.load(csarPayload);
- return map;
- }
- return null;
- }
-
- public static Map<String, Object> downloadAndParseToscaTemplate(User sdncModifierDetails, Component createdComponent) throws Exception {
- String artifactUniqeId = createdComponent.getToscaArtifacts().get("assettoscatemplate").getUniqueId();
- RestResponse toscaTemplate;
-
- if (createdComponent.getComponentType() == ComponentTypeEnum.RESOURCE) {
- toscaTemplate = ArtifactRestUtils.downloadResourceArtifactInternalApi(createdComponent.getUniqueId(), sdncModifierDetails, artifactUniqeId);
-
- } else {
- toscaTemplate = ArtifactRestUtils.downloadServiceArtifactInternalApi(createdComponent.getUniqueId(), sdncModifierDetails, artifactUniqeId);
- }
- BaseRestUtils.checkSuccess(toscaTemplate);
-
- ArtifactUiDownloadData artifactUiDownloadData = ResponseParser.parseToObject(toscaTemplate.getResponse(), ArtifactUiDownloadData.class);
- byte[] fromUiDownload = artifactUiDownloadData.getBase64Contents().getBytes();
- byte[] decodeBase64 = Base64.decodeBase64(fromUiDownload);
- Yaml yaml = new Yaml();
-
- InputStream inputStream = new ByteArrayInputStream(decodeBase64);
-
- Map<String, Object> load = (Map<String, Object>) yaml.load(inputStream);
- return load;
- }
-
- public static ToscaDefinition getToscaDefinitionObjectByCsarUuid(String csarUUID) throws Exception {
-
- String TOSCAMetaLocation = "TOSCA-Metadata/TOSCA.meta";
- Map<?, ?> map = getToscaYamlMap(csarUUID, TOSCAMetaLocation);
- assertNotNull("Tosca Entry-Definitions is null", map);
- if (map != null) {
- String definitionYamlLocation = (String) map.get("Entry-Definitions");
- Map<?, ?> toscaMap = getToscaYamlMap(csarUUID, definitionYamlLocation);
- assertNotNull("Tosca definition is null", toscaMap);
- if (toscaMap != null) {
- ToscaDefinition toscaDefinition = new ToscaDefinition();
- Set<?> keySet = toscaMap.keySet();
- for (Object key : keySet) {
- ToscaKeysEnum toscaKey = ToscaKeysEnum.findToscaKey((String) key);
- switch (toscaKey) {
- case TOSCA_DEFINITION_VERSION:
- enrichToscaDefinitionWithToscaVersion(toscaMap, toscaDefinition);
- break;
- case NODE_TYPES:
- getToscaNodeTypes(toscaMap, toscaDefinition);
- break;
- case TOPOLOGY_TEMPLATE:
- getToscaTopologyTemplate(toscaMap, toscaDefinition);
- break;
- case IMPORTS:
- // toscaMap.get("imports");
- break;
- default:
- break;
- }
- }
- return toscaDefinition;
- }
- }
- return null;
-
- }
-
- public static void enrichToscaDefinitionWithToscaVersion(Map<?, ?> toscaMap, ToscaDefinition toscaDefinition) {
- if (toscaMap.get("tosca_definitions_version") != null) {
- toscaDefinition.setToscaDefinitionVersion(getToscaVersion(toscaMap));
- }
- }
-
- public static String getToscaVersion(Map<?, ?> toscaMap) {
- return (String) toscaMap.get("tosca_definitions_version");
- }
-
- // spec 90 page
- public static void getToscaNodeTypes(Map<?, ?> toscaMap, ToscaDefinition toscaDefinition) {
- @SuppressWarnings("unchecked")
- Map<String, Map<String, String>> nodeTypes = (Map<String, Map<String, String>>) toscaMap.get("node_types");
- List<ToscaNodeTypesDefinition> listToscaNodeTypes = new ArrayList<>();
- if (nodeTypes != null) {
- for (Entry<String, Map<String, String>> entry : nodeTypes.entrySet()) {
- ToscaNodeTypesDefinition toscaNodeTypes = new ToscaNodeTypesDefinition();
- String toscaNodeName = entry.getKey();
- toscaNodeTypes.setName(toscaNodeName);
-
- Map<String, String> toscaNodeType = entry.getValue();
- if (toscaNodeType != null) {
- Set<Entry<String, String>> entrySet = toscaNodeType.entrySet();
- if (entrySet != null) {
- // boolean found = false;
- for (Entry<String, String> toscaNodeTypeMap : entrySet) {
- String key = toscaNodeTypeMap.getKey();
- if (key.equals("derived_from")) {
- String derivedFrom = toscaNodeTypeMap.getValue();
- toscaNodeTypes.setDerivedFrom(derivedFrom);
- // found = true;
- break;
- } else {
- continue;
- }
-
- }
- // if (found == false) {
- // System.out.println("Tosca file not valid,
- // derived_from not found");
- // }
- }
-
- }
- listToscaNodeTypes.add(toscaNodeTypes);
- }
- toscaDefinition.setToscaNodeTypes(listToscaNodeTypes);
- }
- }
-
- public static void getToscaTopologyTemplate(Map<?, ?> toscaMap, ToscaDefinition toscaDefinition) {
- ToscaTopologyTemplateDefinition toscaTopologyTemplate = new ToscaTopologyTemplateDefinition();
- @SuppressWarnings("unchecked")
- Map<String, Map<String, Object>> topologyTemplateMap = (Map<String, Map<String, Object>>) toscaMap
- .get("topology_template");
- List<ToscaNodeTemplatesTopologyTemplateDefinition> listToscaNodeTemplates = new ArrayList<>();
-
- if (topologyTemplateMap != null) {
- getToscaNodeTemplates(topologyTemplateMap, listToscaNodeTemplates);
- }
- toscaTopologyTemplate.setToscaNodeTemplatesTopologyTemplateDefinition(listToscaNodeTemplates);
- toscaDefinition.setToscaTopologyTemplate(toscaTopologyTemplate);
- }
-
- public static void getToscaNodeTemplates(Map<String, Map<String, Object>> topologyTemplateMap,
- List<ToscaNodeTemplatesTopologyTemplateDefinition> listToscaNodeTemplates) {
- Map<String, Object> nodeTemplatesMap = topologyTemplateMap.get("node_templates");
- if (nodeTemplatesMap != null) {
-
- for (Entry<String, Object> nodeTemplates : nodeTemplatesMap.entrySet()) {
- ToscaNodeTemplatesTopologyTemplateDefinition toscaNodeTemplates = new ToscaNodeTemplatesTopologyTemplateDefinition();
- getToscaNodeTemplatesName(nodeTemplates, toscaNodeTemplates);
-
- @SuppressWarnings("unchecked")
- Map<String, Object> node = (Map<String, Object>) nodeTemplates.getValue();
- getNodeTemplatesType(toscaNodeTemplates, node);
- getToscaNodeTemplateProperties(toscaNodeTemplates, node);
- getToscaNodeTemplateRequirements(toscaNodeTemplates, node);
- listToscaNodeTemplates.add(toscaNodeTemplates);
- }
- }
- }
-
- public static void getToscaNodeTemplateRequirements(ToscaNodeTemplatesTopologyTemplateDefinition toscaNodeTemplates,
- Map<String, Object> node) {
- List<ToscaRequirementsNodeTemplatesDefinition> toscaRequirements = new ArrayList<>();
- if (node.get("requirements") != null) {
- @SuppressWarnings("unchecked")
- List<Map<String, Object>> requirementList = (List<Map<String, Object>>) node.get("requirements");
- for (int i = 0; i < requirementList.size(); i++) {
- for (Entry<String, Object> requirement : requirementList.get(i).entrySet()) {
- ToscaRequirementsNodeTemplatesDefinition toscaRequirement = new ToscaRequirementsNodeTemplatesDefinition();
- if (requirement.getKey() != null) {
- String requirementName = requirement.getKey();
- toscaRequirement.setName(requirementName);
- } else {
- log.debug("Tosca file not valid, requirements should contain name");
- }
-
- @SuppressWarnings("unchecked")
- Map<String, String> requirementMap = (Map<String, String>) requirement.getValue();
- Set<Entry<String, String>> entrySet = requirementMap.entrySet();
- if (entrySet != null) {
- for (Entry<String, String> requirementField : entrySet) {
- String key = requirementField.getKey();
- switch (key) {
- case "capability":
- if (requirementMap.get(key) != null) {
- String capability = (String) requirementMap.get(key);
- toscaRequirement.setCapability(capability);
- break;
- } else {
- continue;
- }
- case "node":
- if (requirementMap.get(key) != null) {
- String requirementNode = (String) requirementMap.get(key);
- toscaRequirement.setNode(requirementNode);
- break;
- } else {
- continue;
- }
- case "relationship":
- if (requirementMap.get(key) != null) {
- String relationship = (String) requirementMap.get(key);
- toscaRequirement.setRelationship(relationship);
- break;
- } else {
- continue;
- }
- default:
- break;
- }
- }
- }
- toscaRequirements.add(toscaRequirement);
- }
- }
- }
- toscaNodeTemplates.setRequirements(toscaRequirements);
- }
-
- public static void getToscaNodeTemplateProperties(ToscaNodeTemplatesTopologyTemplateDefinition toscaNodeTemplates,
- Map<String, Object> node) {
- List<ToscaPropertiesNodeTemplatesDefinition> listToscaProperties = new ArrayList<>();
- if (node.get("properties") != null) {
- @SuppressWarnings("unchecked")
- Map<String, Object> properties = (Map<String, Object>) node.get("properties");
- for (Entry<String, Object> property : properties.entrySet()) {
- ToscaPropertiesNodeTemplatesDefinition toscaProperty = new ToscaPropertiesNodeTemplatesDefinition();
- String propertyName = property.getKey();
- Object propertyValue = property.getValue();
- toscaProperty.setName(propertyName);
- toscaProperty.setValue(propertyValue);
- listToscaProperties.add(toscaProperty);
- }
- }
- toscaNodeTemplates.setProperties(listToscaProperties);
- }
-
- protected static void getNodeTemplatesType(ToscaNodeTemplatesTopologyTemplateDefinition toscaNodeTemplates,
- Map<String, Object> node) {
- if (node.get("type") != null) {
- String type = (String) node.get("type");
- toscaNodeTemplates.setType(type);
- } else {
- log.debug("Tosca file not valid, nodeTemplate should contain type");
- }
- }
-
- protected static void getToscaNodeTemplatesName(Entry<String, Object> nodeTemplates,
- ToscaNodeTemplatesTopologyTemplateDefinition toscaNodeTemplates) {
- String name = nodeTemplates.getKey();
- toscaNodeTemplates.setName(name);
- }
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/Utils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/Utils.java
deleted file mode 100644
index 8a8ec58217..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/Utils.java
+++ /dev/null
@@ -1,656 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utils;
-
-import static org.testng.AssertJUnit.assertEquals;
-import static org.testng.AssertJUnit.assertNotNull;
-import static org.testng.AssertJUnit.assertTrue;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.InputStream;
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-
-import org.apache.commons.lang3.StringUtils;
-import org.apache.log4j.Logger;
-import org.openecomp.sdc.ci.tests.config.Config;
-import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
-import org.openecomp.sdc.common.api.ToscaNodeTypeInfo;
-import org.openecomp.sdc.common.api.YamlConstants;
-import org.yaml.snakeyaml.Yaml;
-
-import com.google.gson.Gson;
-import com.google.gson.JsonElement;
-import com.google.gson.JsonObject;
-import com.google.gson.JsonParser;
-
-public final class Utils {
-
- Gson gson = new Gson();
-
- static Logger logger = Logger.getLogger(Utils.class.getName());
-
- String contentTypeHeaderData = "application/json";
- String acceptHeaderDate = "application/json";
-
- public Utils() {
- /*
- * super();
- *
- * StartTest.enableLogger(); logger =
- * Logger.getLogger(Utils.class.getName());
- */
-
- }
-
- // public String serviceTopologyPattern = "/topology/topology/%s";
- // public String serviceTopologyTemplatePattern =
- // "/topologytemplate/topologytemplate/%s";
- //
- // public String serviceTopologySearchPattern =
- // "topology/topology/_search?q=%s";
- // public String serviceTopologyTemplateSearchPattern =
- // "topologytemplate/topologytemplate/_search?q=%s";
- //
- // public ArtifactTypeEnum getFileTypeByExtension(String fileName) {
- //
- // String fileExtension = null;
- // if (fileName.matches("(.*)\\.(.*)")) {
- // System.out.println(fileName.substring(fileName.lastIndexOf(".") + 1));
- // fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1);
- // }
- //
- // switch (fileExtension) {
- // case "sh":
- // return ArtifactTypeEnum.SHELL_SCRIPT;
- // case "png":
- // return ArtifactTypeEnum.ICON;
- // case "ppp":
- // return ArtifactTypeEnum.PUPPET;
- // case "yang":
- // return ArtifactTypeEnum.YANG;
- // default:
- // return ArtifactTypeEnum.UNKNOWN;
- // }
- //
- // }
- //
- // public ArrayList<String> getScriptList (List<UploadArtifactInfo>
- // artifactsList){
- //
- // ArrayList<String> scriptNameArray = new ArrayList<>();
- // if (artifactsList != null){
- // for (UploadArtifactInfo fileInArtifactsList : artifactsList){
- // String artifactFileName = fileInArtifactsList.getArtifactName();
- // ArtifactTypeEnum artifactFileType =
- // fileInArtifactsList.getArtifactType();
- // if (! artifactFileType.equals(ArtifactTypeEnum.ICON)){
- // scriptNameArray.add(artifactFileName);
- // }
- // continue;
- // }
- // return scriptNameArray;
- // }
- // return null;
- // }
- //
- //
- // public String getYamlFileLocation(File testResourcesPath) {
- // File[] files = testResourcesPath.listFiles();
- // if (files.length == 0){
- // return null;
- // }else{
- // for (int i = 0; i < files.length; i++){
- // if (files[i].isFile()){
- // return files[i].getAbsoluteFile().toString();
- // }
- // }
- // }
- // return null;
- // }
- //
- // public String readFileContentToString (String fileName) throws
- // IOException {
- //
- // Path path = Paths.get(fileName);
- // String stringFromFile = new String(Files.readAllBytes(path));
- // return stringFromFile;
- //
- //
- // }
- //
- @SuppressWarnings("unchecked")
- public ToscaNodeTypeInfo parseToscaNodeYaml(String fileContent) {
-
- ToscaNodeTypeInfo result = new ToscaNodeTypeInfo();
- Object templateVersion = null;
- Object templateName = null;
-
- if (fileContent != null) {
- Yaml yaml = new Yaml();
-
- Map<String, Object> yamlObject = (Map<String, Object>) yaml.load(fileContent);
-
- templateVersion = yamlObject.get(YamlConstants.TEMPLATE_VERSION);
- if (templateVersion != null) {
- result.setTemplateVersion(templateVersion.toString());
- }
- templateName = yamlObject.get(YamlConstants.TEMPLATE_NAME);
- if (templateName != null) {
- result.setTemplateName(templateName.toString());
- }
- Object nodeTypes = yamlObject.get(YamlConstants.NODE_TYPES);
-
- if (nodeTypes != null) {
- Map<String, Object> nodeTypesMap = (Map<String, Object>) nodeTypes;
- for (Entry<String, Object> entry : nodeTypesMap.entrySet()) {
-
- String nodeName = entry.getKey();
- if (nodeName != null) {
- result.setNodeName(nodeName);
- }
-
- break;
-
- }
- }
-
- }
-
- return result;
- }
-
- //
- //
- // public ArtifactsMetadata getArtifactsMetadata(String response){
- // ArtifactsMetadata artifactsMetadata = new ArtifactsMetadata();
- //
- // artifactsMetadata.setId(getJsonObjectValueByKey(response, "id"));
- // artifactsMetadata.setName(getJsonObjectValueByKey(response, "name"));
- // artifactsMetadata.setType(getJsonObjectValueByKey(response, "type"));
- //
- // artifactsMetadata.setCreator(getJsonObjectValueByKey(response,
- // "creator"));
- // artifactsMetadata.setCreationTime(getJsonObjectValueByKey(response,
- // "creationTime"));
- // artifactsMetadata.setLastUpdateTime(getJsonObjectValueByKey(response,
- // "lastUpdateTime"));
- // artifactsMetadata.setChecksum(getJsonObjectValueByKey(response,
- // "checksum"));
- // artifactsMetadata.setDescription(getJsonObjectValueByKey(response,
- // "description"));
- // artifactsMetadata.setLastUpdater(getJsonObjectValueByKey(response,
- // "lastUpdater"));
- //
- // return artifactsMetadata;
- // }
- //
- public static String getJsonObjectValueByKey(String metadata, String key) {
- JsonElement jelement = new JsonParser().parse(metadata);
-
- JsonObject jobject = jelement.getAsJsonObject();
- Object obj = jobject.get(key);
- if (obj == null) {
- return null;
- } else {
- String value;
- value = (String) jobject.get(key).getAsString();
- return value;
- }
- }
-
- public static Config getConfig() throws FileNotFoundException {
- Config config = Config.instance();
- return config;
- }
-
- // public void uploadNormativeTypes() throws IOException{
- // Config config = getConfig();
- // String[] normativeTypes = {"root", "compute", "blockStorage",
- // "softwareComponent", "DBMS", "database", "network", "objectStorage",
- // "webServer", "webApplication"};
- // for( String normativeType : normativeTypes ){
- // uploadComponent(config.getComponentsConfigDir()+File.separator+"normativeTypes"+File.separator+normativeType);
- // }
- //
- // }
- //
- // public void uploadApacheComponent() throws IOException{
- // Config config = getConfig();
- // uploadComponent(config.getComponentsConfigDir()+File.separator+"apache");
- // }
- //
- // public void uploadComponent(String componentDir) throws IOException{
- //
- // //*********************************************upload*************************************************************
- // Config config = getConfig();
- // ZipDirectory zipDirectory = new ZipDirectory();
- // System.out.println(config.getEsHost());
- //
- // List<UploadArtifactInfo> artifactsList = new
- // ArrayList<UploadArtifactInfo>();
- //
- //// read test resources and zip it as byte array
- // byte[] zippedAsByteArray = zipDirectory.zip(componentDir, artifactsList);
- //
- //// encode zipped directory using base64
- // String payload = Decoder.encode(zippedAsByteArray);
- //
- //// zip name build as testName with ".zip" extension
- // String payloadZipName = getPayloadZipName(componentDir);
- //
- //// build json
- // UploadResourceInfo resourceInfo = new UploadResourceInfo(payload,
- // payloadZipName, "description", "category/mycategory", null,
- // artifactsList);
- // String json = new Gson().toJson(resourceInfo);
- //
- //// calculate md5 on the content of json
- // String jsonMd5 =
- // org.apache.commons.codec.digest.DigestUtils.md5Hex(json);
- //
- //// encode the md5 to base64, sent as header in post http request
- // String encodedMd5 = Decoder.encode(jsonMd5.getBytes());
- //
- //// upload component to Elastic Search DB
- // String url = null;
- // HttpRequest http = new HttpRequest();
- //
- // url = String.format(Urls.UPLOAD_ZIP_URL, config.getCatalogFeHost(),
- // config.getCatalogFePort());
- //
- //// Prepare headers to post upload component request
- // HeaderData headerData = new HeaderData(encodedMd5, "application/json",
- // "att", "test", "testIvanovich", "RoyalSeal", "Far_Far_Away",
- // "getResourceArtifactListTest");
- //
- // MustHeaders headers = new MustHeaders(headerData);
- // System.out.println("headers:"+headers.getMap());
- //
- // RestResponse response = http.httpSendPost(url, json, headers.getMap());
- //
- // assertEquals("upload component failed with code " +
- // response.getErrorCode().intValue(),response.getErrorCode().intValue(),
- // 204);
- // }
- //
- // private String getPayloadZipName(String componentDir) {
- // String payloadName;
- // if( componentDir.contains( File.separator) ){
- // String delimiter = null;
- // if( File.separator.equals("\\")){
- // delimiter ="\\\\";
- // }
- // else{
- // delimiter = File.separator;
- // }
- // String[] split = componentDir.split(delimiter);
- // payloadName = split[split.length-1];
- // }
- // else{
- // payloadName = componentDir;
- // }
- // return payloadName+".zip";
- // }
- //
- //
- //
- // public List<UploadArtifactInfo> createArtifactsList(String srcDir) {
- //
- // List<UploadArtifactInfo> artifactsList = new
- // ArrayList<UploadArtifactInfo>();
- // File srcFile = new File(srcDir);
- // addFileToList(srcFile, artifactsList);
- //
- // return artifactsList;
- // }
- //
- // public void addFileToList(File srcFile, List<UploadArtifactInfo>
- // artifactsList) {
- //
- // File[] files = srcFile.listFiles();
- //
- // for (int i = 0; i < files.length; i++) {
- // // if the file is directory, use recursion
- // if (files[i].isDirectory()) {
- // addFileToList(files[i], artifactsList);
- // continue;
- // }
- //
- // String fileName = files[i].getName();
- // String artifactPath = fileName;
- //
- // if ( ! files[i].getName().matches("(.*)\\.y(?)ml($)")) {
- // UploadArtifactInfo uploadArtifactInfo = new UploadArtifactInfo();
- // uploadArtifactInfo.setArtifactName(files[i].getName());
- // String parent = files[i].getParent();
- //
- // if (parent != null) {
- // System.out.println(parent);
- // int lastSepartor = parent.lastIndexOf(File.separator);
- // if (lastSepartor > -1) {
- // String actualParent = parent.substring(lastSepartor + 1);
- // artifactPath = actualParent + "/" + artifactPath;
- // }
- // }
- //
- // uploadArtifactInfo.setArtifactPath(artifactPath);
- // uploadArtifactInfo.setArtifactType(getFileTypeByExtension(fileName));
- // uploadArtifactInfo.setArtifactDescription("description");
- // artifactsList.add(uploadArtifactInfo);
- //
- // System.out.println("artifact list: " + artifactsList);
- //
- // }
- //
- // }
- // }
- //
- //
- // public String buildArtifactListUrl (String nodesType, String
- // templateVersion, String artifactName) throws FileNotFoundException{
- // //"http://172.20.43.132/sdc2/v1/catalog/resources/tosca.nodes.Root/1.0.0.wd03-SNAPSHOT/artifacts/wxs_baseline_compare.sh"
- // Config config = getConfig();
- // return "\"http://" + config.getCatalogBeHost() + ":" +
- // config.getCatalogBePort() + "/sdc2/v1/catalog/resources/" +nodesType +
- // "/" + templateVersion + "/artifacts/" + artifactName +"\"";
- // }
- //
- //
- // public void addTopologyToES(String testFolder, String
- // serviceTopologyPattern) throws IOException{
- // Config config = getConfig();
- // String url = String.format(Urls.ES_URL, config.getEsHost(),
- // config.getEsPort()) + serviceTopologyPattern;
- // String sourceDir =
- // config.getResourceConfigDir()+File.separator+testFolder;
- // Path filePath = FileSystems.getDefault().getPath(sourceDir,
- // "topology.txt");
- // postFileContentsToUrl(url, filePath);
- // }
- //
- // public void addTopologyTemplateToES(String testFolder, String
- // serviceTopologyTemplatePattern) throws IOException{
- // Config config = getConfig();
- // String url = String.format(Urls.ES_URL, config.getEsHost(),
- // config.getEsPort()) + serviceTopologyTemplatePattern;
- // String sourceDir =
- // config.getResourceConfigDir()+File.separator+testFolder;
- // Path filePath = FileSystems.getDefault().getPath(sourceDir,
- // "topologyTemplate.txt");
- // postFileContentsToUrl(url, filePath);
- // }
- //
- //
- // public void postFileContentsToUrl(String url, Path filePath) throws
- // IOException {
- // HttpClientContext localContext = HttpClientContext.create();
- // CloseableHttpResponse response = null;
- //
- // byte[] fileContent = Files.readAllBytes(filePath);
- //
- // try(CloseableHttpClient httpClient = HttpClients.createDefault()){
- // HttpPost httpPost = new HttpPost(url);
- // StringEntity entity = new StringEntity(new String(fileContent) ,
- // ContentType.APPLICATION_JSON);
- // httpPost.setEntity(entity);
- // response = httpClient.execute(httpPost, localContext);
- //
- // }
- // finally{
- // response.close();
- // }
- //
- //
- // }
- //
- //
- //// public boolean isPatternInEsDb(String patternToSearch)throws
- // IOException{
- //// Config config = getConfig();
- //// String url = String.format(Urls.GET_SEARCH_DATA_FROM_ES,
- // config.getEsHost(), config.getEsPort(),patternToSearch);
- //// HttpRequest httpRequest = new HttpRequest();
- //// RestResponse restResponse = httpRequest.httpSendGet(url);
- //// if (restResponse.getErrorCode() == 200){
- //// return true;
- //// }
- //// if (restResponse.getErrorCode() == 404){
- //// return false;
- //// }
- ////
- //// return false;
- //// }
- //
- // public static RestResponse deleteAllDataFromEs() throws IOException{
- // return deleteFromEsDbByPattern("_all");
- // }
- //
-
- //
- // public List<String> buildIdArrayListByTypesIndex (String index, String
- // types) throws IOException{
- //
- // Config config = getConfig();
- // HttpRequest http = new HttpRequest();
- // RestResponse getResponce =
- // http.httpSendGet(String.format(Urls.GET_ID_LIST_BY_INDEX_FROM_ES,
- // config.getEsHost(), config.getEsPort(), index, types), null);
- //
- // List <String> idArray = new ArrayList<String>();
- //
- // JsonElement jelement = new JsonParser().parse(getResponce.getResponse());
- // JsonObject jobject = jelement.getAsJsonObject();
- // JsonObject hitsObject = (JsonObject) jobject.get("hits");
- // JsonArray hitsArray = (JsonArray) hitsObject.get("hits");
- // for (int i = 0; i < hitsArray.size(); i ++){
- // JsonObject idObject = (JsonObject) hitsArray.get(i);
- // String id = idObject.get("_id").toString();
- // id = id.replace("\"", "");
- // idArray.add(id);
- // }
- //
- // return idArray;
- // }
- //
- // public List<String> buildCategoriesTagsListFromJson(String
- // categoriesTagsJson){
- //
- // ArrayList<String> categoriesTagsArray = new ArrayList<>();
- // JsonElement jelement = new JsonParser().parse(categoriesTagsJson);
- // JsonArray jArray = jelement.getAsJsonArray();
- // for (int i = 0; i < jArray.size(); i ++){
- // JsonObject categoriesTagsObject = (JsonObject) jArray.get(i);
- // String categories = categoriesTagsObject.get("name").toString();
- // categoriesTagsArray.add(categories);
- // }
- //
- // return categoriesTagsArray;
- // }
- //
- // public ArrayList <String> getCategoriesFromDb() throws Exception{
- //
- // ArrayList<String> categoriesFromDbArrayList = new ArrayList<>();
- // RestResponse restResponse = new RestResponse();
- // String contentTypeHeaderData = "application/json";
- // String acceptHeaderDate = "application/json";
- //
- // Map<String, String> headersMap = new HashMap<String,String>();
- // headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(),contentTypeHeaderData);
- // headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
- //
- // HttpRequest httpRequest = new HttpRequest();
- // String url = String.format(Urls.QUERY_NEO4J,
- // Config.instance().getNeoHost(), Config.instance().getNeoPort());
- // String body = "{\"statements\" : [ { \"statement\" : \"MATCH
- // (category:category) return (category)\"} ]}";
- // restResponse = httpRequest.httpSendPostWithAuth(url, body, headersMap,
- // Config.instance().getNeoDBusername(),
- // Config.instance().getNeoDBpassword());
- //
- // if (restResponse.getResponse()==null){
- // return categoriesFromDbArrayList;
- // }else{
- // JsonElement jelement = new
- // JsonParser().parse(restResponse.getResponse());
- // JsonObject jobject = jelement.getAsJsonObject();
- // JsonArray resultsArray = (JsonArray) jobject.get("results");
- // JsonObject resObject = (JsonObject) resultsArray.get(0);
- // JsonArray dataArray = (JsonArray) resObject.get("data");
- // for (int i = 0; i < dataArray.size(); i ++){
- // JsonObject rowObject = (JsonObject) dataArray.get(i);
- // JsonArray rowArray = (JsonArray) rowObject.get("row");
- // JsonObject nameObject = (JsonObject) rowArray.get(0);
- // String name = nameObject.get("name").toString();
- //// name = name.replace("\"", "");
- // categoriesFromDbArrayList.add(name);
- // }
- //
- //
- // }
- //
- // return categoriesFromDbArrayList;
- // }
- //
- public static void compareArrayLists(List<String> actualArraylList, List<String> expectedArrayList,
- String message) {
-
- ArrayList<String> actual = new ArrayList<String>(actualArraylList);
- ArrayList<String> expected = new ArrayList<String>(expectedArrayList);
- // assertEquals(message + " count got by rest API not match to " +
- // message + " expected count", expected.size(),actual.size());
- expected.removeAll(actual);
- assertEquals(message + " content got by rest API not match to " + message + " actual content", 0,
- expected.size());
- }
-
- public static Object parseYamlConfig(String pattern) throws FileNotFoundException {
-
- Yaml yaml = new Yaml();
- Config config = getConfig();
- String configurationFile = config.getConfigurationFile();
- File file = new File(configurationFile);
- // File file = new
- // File("../catalog-be/src/main/resources/config/configuration.yaml");
- InputStream inputStream = new FileInputStream(file);
- Map<?, ?> map = (Map<?, ?>) yaml.load(inputStream);
- Object patternMap = (Object) map.get(pattern);
-
- return patternMap;
- }
-
- public static String getDepArtLabelFromConfig(ArtifactTypeEnum artifactTypeEnum) throws FileNotFoundException {
-
- @SuppressWarnings("unchecked")
- Map<String, Object> mapOfDepResArtTypesObjects = (Map<String, Object>) parseYamlConfig(
- "deploymentResourceArtifacts");
- for (Map.Entry<String, Object> iter : mapOfDepResArtTypesObjects.entrySet()) {
- if (iter.getValue().toString().contains(artifactTypeEnum.getType())) {
- return iter.getKey().toLowerCase();
- }
- }
-
- return "defaultLabelName";
- }
-
- public static String multipleChar(String ch, int repeat) {
- return StringUtils.repeat(ch, repeat);
- }
-
- public static List<String> getListOfDepResArtLabels(Boolean isLowerCase) throws FileNotFoundException {
-
- List<String> listOfResDepArtTypesFromConfig = new ArrayList<String>();
- @SuppressWarnings("unchecked")
- Map<String, Object> resourceDeploymentArtifacts = (Map<String, Object>) parseYamlConfig(
- "deploymentResourceArtifacts");
- if (resourceDeploymentArtifacts != null) {
-
- if (isLowerCase) {
- for (Map.Entry<String, Object> iter : resourceDeploymentArtifacts.entrySet()) {
- listOfResDepArtTypesFromConfig.add(iter.getKey().toLowerCase());
- }
- } else {
-
- for (Map.Entry<String, Object> iter : resourceDeploymentArtifacts.entrySet()) {
- listOfResDepArtTypesFromConfig.add(iter.getKey());
- }
- }
- }
- return listOfResDepArtTypesFromConfig;
- }
-
- public static List<String> getListOfToscaArtLabels(Boolean isLowerCase) throws FileNotFoundException {
-
- List<String> listOfToscaArtTypesFromConfig = new ArrayList<String>();
- @SuppressWarnings("unchecked")
- Map<String, Object> toscaArtifacts = (Map<String, Object>) parseYamlConfig("toscaArtifacts");
- if (toscaArtifacts != null) {
-
- if (isLowerCase) {
- for (Map.Entry<String, Object> iter : toscaArtifacts.entrySet()) {
- listOfToscaArtTypesFromConfig.add(iter.getKey().toLowerCase());
- }
- } else {
- for (Map.Entry<String, Object> iter : toscaArtifacts.entrySet()) {
- listOfToscaArtTypesFromConfig.add(iter.getKey());
- }
- }
- }
- return listOfToscaArtTypesFromConfig;
- }
-
- public static List<String> getListOfResPlaceHoldersDepArtTypes() throws FileNotFoundException {
- List<String> listResDepArtTypesFromConfig = new ArrayList<String>();
- List<String> listOfResDepArtLabelsFromConfig = getListOfDepResArtLabels(false);
- assertNotNull("deployment artifact types list is null", listOfResDepArtLabelsFromConfig);
- Object parseYamlConfig = Utils.parseYamlConfig("deploymentResourceArtifacts");
- Map<String, Object> mapOfDepResArtTypesObjects = (Map<String, Object>) Utils
- .parseYamlConfig("deploymentResourceArtifacts");
-
- // assertNotNull("deployment artifact types list is null",
- // mapOfDepResArtTypesObjects);
- if (listOfResDepArtLabelsFromConfig != null) {
- for (String resDepArtType : listOfResDepArtLabelsFromConfig) {
- Object object = mapOfDepResArtTypesObjects.get(resDepArtType);
- if (object instanceof Map<?, ?>) {
- Map<String, Object> map = (Map<String, Object>) object;
- listResDepArtTypesFromConfig.add((String) map.get("type"));
- } else {
- assertTrue("return object does not instance of map", false);
- }
- }
- }
- return listResDepArtTypesFromConfig;
- }
-
- public static Long getEpochTimeFromUTC(String time) throws ParseException {
- SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS zzz");
- java.util.Date date = df.parse(time);
- long epoch = date.getTime();
- return epoch;
- }
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/cassandra/CassandraUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/cassandra/CassandraUtils.java
deleted file mode 100644
index b6cc44ce36..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/cassandra/CassandraUtils.java
+++ /dev/null
@@ -1,225 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utils.cassandra;
-
-import java.io.FileNotFoundException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-
-import org.javatuples.Pair;
-import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
-import org.openecomp.sdc.ci.tests.utils.Utils;
-import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.datastax.driver.core.Cluster;
-import com.datastax.driver.core.KeyspaceMetadata;
-import com.datastax.driver.core.Metadata;
-import com.datastax.driver.core.Row;
-import com.datastax.driver.core.Session;
-import com.datastax.driver.core.TableMetadata;
-import com.datastax.driver.core.querybuilder.QueryBuilder;
-import com.datastax.driver.core.querybuilder.Select;
-import com.datastax.driver.core.querybuilder.Select.Where;
-
-public final class CassandraUtils {
- private static Logger logger = LoggerFactory.getLogger(CassandraUtils.class.getName());
-
- protected static Cluster cluster = null;
- protected static Session session;
-
- protected static void initConnection(String keyspace) throws FileNotFoundException {
-
- String cassandraHost = Utils.getConfig().getCassandraHost();
- Boolean cassandraAuthenticate = Utils.getConfig().getCassandraAuthenticate();
- String cassandraUsername = Utils.getConfig().getCassandraUsername();
- String cassandraPassword = Utils.getConfig().getCassandraPassword();
- Boolean cassandraSsl = Utils.getConfig().getCassandraSsl();
- String cassandraTruststorePath = Utils.getConfig().getCassandraTruststorePath();
- String cassandraTruststorePassword = Utils.getConfig().getCassandraTruststorePassword();
- /*
- * String cassandraAuditKeySpace=
- * Utils.getConfig().getCassandraAuditKeySpace(); String
- * cassandraArtifactKeySpace=
- * Utils.getConfig().getCassandraArtifactKeySpace();
- */
-
- Cluster.Builder clusterBuilder = Cluster.builder().addContactPoint(cassandraHost);
- if (cassandraAuthenticate) {
- // authantication
- clusterBuilder.withCredentials(cassandraUsername, cassandraPassword);
- }
-
- if (cassandraSsl) {
- // ssl
- System.setProperty("javax.net.ssl.trustStore", cassandraTruststorePath);
- System.setProperty("javax.net.ssl.trustStorePassword", cassandraTruststorePassword);
- clusterBuilder.withSSL();
- }
-
- cluster = clusterBuilder.build();
- session = cluster.connect(keyspace);
-
- }
-
- public static void truncateTable(String keyspace, String tableName) throws FileNotFoundException {
-
- if (session == null || session.isClosed()) {
- initConnection(keyspace);
- }
-
- try {
-
- if (session != null) {
- session.execute(QueryBuilder.truncate(keyspace, tableName));
- logger.debug("The table {}.{} was cleaned",keyspace,tableName);
- } else {
- throw new RuntimeException("Keyspace " + keyspace + " not connected");
- }
- } finally {
- // if (cluster != null) {
- // cluster.close();
- // }
- }
- }
-
- public static void close() {
- if (cluster != null) {
- cluster.close();
- }
- }
-
- public static void truncateAllKeyspaces() throws FileNotFoundException {
- // truncateAllTables(AuditingTypesConstants.ARTIFACT_KEYSPACE);
- truncateAllTables(AuditingTypesConstants.AUDIT_KEYSPACE);
- }
-
- public static void truncateAllTables(String keyspace) throws FileNotFoundException {
-
- if (session == null || session.isClosed()) {
- initConnection(keyspace);
- }
- try {
-
- if (session != null) {
- Metadata metadata = cluster.getMetadata();
- KeyspaceMetadata keyspaceMetadata = metadata.getKeyspace(keyspace);
- if (keyspaceMetadata != null) {
- Collection<TableMetadata> tables = keyspaceMetadata.getTables();
- tables.forEach(table -> {
- session.execute(QueryBuilder.truncate(table));
- logger.debug("Table trunceted - {}",table.getName());
- });
- }
- } else {
- throw new RuntimeException("Keyspace " + keyspace + " not connected");
- }
-
- } finally {
- // if (cluster != null) {
- // cluster.close();
- // }
- }
- }
-
- public static List<Row> fetchFromTable(String keyspace, String tableName,
- List<Pair<AuditingFieldsKeysEnum, String>> fields) throws FileNotFoundException {
-
- List<Pair<String, String>> fieldsConverted = new ArrayList<>();
-
-// fields.forEach(pair -> {
-// Pair<String, String> newPair = new Pair(pair.getValue0().getDisplayName(), pair.getValue1());
-// fieldsConverted.add(newPair);
-// });
-
- fields.forEach(pair ->{
- Pair<String, String> newPair;
- if(pair.getValue0() == AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL ){
- newPair = new Pair<String, String>("RESOURE_URL", pair.getValue1());
-
- }else{
- newPair = new Pair<String, String>(pair.getValue0().getDisplayName(), pair.getValue1());
- }
- fieldsConverted.add(newPair);
-
- });
-
- return fetchFromTableQuery(keyspace, tableName, fieldsConverted);
- }
-
- public static List<Row> fetchFromTableQuery(String keyspace, String tableName, List<Pair<String, String>> fields)
- throws FileNotFoundException {
-
- if (session == null || session.isClosed()) {
- initConnection(keyspace);
- }
- try {
-
- if (session != null) {
- Select select = QueryBuilder.select().all().from(keyspace, tableName);
- if (fields != null) {
- // Set<Entry<AuditingFieldsKeysEnum, String>> entrySet =
- // fields.entrySet();
- // fields.
- boolean multiple = (fields.size() > 1) ? true : false;
- Where where = null;
- int size = 0;
-
- for (Pair<String, String> pair : fields) {
- ++size;
- if (size == 1) {
- where = select.where(QueryBuilder.eq(pair.getValue0(), pair.getValue1()));
- } else {
- where.and(QueryBuilder.eq(pair.getValue0(), pair.getValue1()));
- }
- }
- if (multiple) {
- select.allowFiltering();
- }
-
- }
-
- List<Row> rows = session.execute(select).all();
- for (Row row : rows) {
- logger.debug("{}", row);
- }
- return rows;
- }
- } finally {
- // if (cluster != null) {
- // cluster.close();
- // }
- }
- return null;
- }
- //
- // public static void main(String[] args) throws FileNotFoundException {
- // Map<AuditingFieldsKeysEnum, String> map = new HashMap<>();
- // map.put(AuditingFieldsKeysEnum.AUDIT_ACTION, "Access");
- // map.put(AuditingFieldsKeysEnum.AUDIT_STATUS, "200");
- // // CassandraUtils.truncateTable("sdcartifact", "resources");
- //// CassandraUtils.truncateAllTables("sdcaudit");
- // CassandraUtils.fetchFromTable("sdcaudit", "useraccessevent", map );
- // }
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/cassandra/CassandraUtils2.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/cassandra/CassandraUtils2.java
deleted file mode 100644
index 05336c475b..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/cassandra/CassandraUtils2.java
+++ /dev/null
@@ -1,172 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utils.cassandra;
-
-import java.io.FileNotFoundException;
-import java.util.Collection;
-import java.util.List;
-
-import org.javatuples.Pair;
-import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
-import org.openecomp.sdc.ci.tests.utils.Utils;
-import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.datastax.driver.core.Cluster;
-import com.datastax.driver.core.KeyspaceMetadata;
-import com.datastax.driver.core.Metadata;
-import com.datastax.driver.core.Row;
-import com.datastax.driver.core.Session;
-import com.datastax.driver.core.TableMetadata;
-import com.datastax.driver.core.querybuilder.QueryBuilder;
-import com.datastax.driver.core.querybuilder.Select;
-import com.datastax.driver.core.querybuilder.Select.Where;
-
-public final class CassandraUtils2 {
- private static Logger logger = LoggerFactory.getLogger(CassandraUtils2.class.getName());
-
- public static void truncateTable(String keyspace, String tableName) throws FileNotFoundException {
-
- String cassandraHost = Utils.getConfig().getCassandraHost();
-
- Cluster cluster = null;
- Session session;
-
- try {
- Cluster.Builder clusterBuilder = Cluster.builder().addContactPoint(cassandraHost);
- // authantication
- // clusterBuilder.withCredentials(username,password);
- // ssl
- // System.setProperty("javax.net.ssl.trustStore",truststorePath);
- // System.setProperty("javax.net.ssl.trustStorePassword",truststorePassword);
- // clusterBuilder.withSSL();
- cluster = clusterBuilder.build();
- session = cluster.connect(keyspace);
- if (session != null) {
- session.execute(QueryBuilder.truncate(keyspace, tableName));
- logger.debug("The table {}.{} was cleaned",keyspace,tableName);
- } else {
- throw new RuntimeException("Keyspace " + keyspace + " not connected");
- }
- } finally {
- if (cluster != null) {
- cluster.close();
- }
- }
- }
-
- public static void truncateAllKeyspaces() throws FileNotFoundException {
- truncateAllTables(AuditingTypesConstants.ARTIFACT_KEYSPACE);
- truncateAllTables(AuditingTypesConstants.AUDIT_KEYSPACE);
- }
-
- public static void truncateAllTables(String keyspace) throws FileNotFoundException {
- String cassandraHost = Utils.getConfig().getCassandraHost();
-
- Cluster cluster = null;
- Session session;
-
- try {
- cluster = Cluster.builder().addContactPoint(cassandraHost).build();
- session = cluster.connect(keyspace);
- if (session != null) {
- Metadata metadata = cluster.getMetadata();
- KeyspaceMetadata keyspaceMetadata = metadata.getKeyspace(keyspace);
- if (keyspaceMetadata != null) {
- Collection<TableMetadata> tables = keyspaceMetadata.getTables();
- tables.forEach(table -> {
- session.execute(QueryBuilder.truncate(table));
- logger.debug("Table trunceted - {}",table.getName());
- });
- }
- } else {
- throw new RuntimeException("Keyspace " + keyspace + " not connected");
- }
-
- } finally {
- if (cluster != null) {
- cluster.close();
- }
- }
- }
-
- public static List<Row> fetchFromTable(String keyspace, String tableName,
- List<Pair<AuditingFieldsKeysEnum, String>> fields) throws FileNotFoundException {
-
- // List<Pair<AuditingFieldsKeysEnum, String>>
- // Map<AuditingFieldsKeysEnum, String>
-
- Cluster cluster = null;
- Session session;
- String cassandraHost = Utils.getConfig().getCassandraHost();
-
- try {
- cluster = Cluster.builder().addContactPoint(cassandraHost).build();
- session = cluster.connect(keyspace);
- if (session != null) {
- Select select = QueryBuilder.select().all().from(keyspace, tableName);
- if (fields != null) {
- // Set<Entry<AuditingFieldsKeysEnum, String>> entrySet =
- // fields.entrySet();
- // fields.
- boolean multiple = (fields.size() > 1) ? true : false;
- Where where = null;
- int size = 0;
-
- for (Pair<AuditingFieldsKeysEnum, String> pair : fields) {
- ++size;
- if (size == 1) {
- where = select.where(QueryBuilder.eq(pair.getValue0().getDisplayName(), pair.getValue1()));
- } else {
- where.and(QueryBuilder.eq(pair.getValue0().getDisplayName(), pair.getValue1()));
- }
- }
- if (multiple) {
- select.allowFiltering();
- }
-
- }
-
- List<Row> rows = session.execute(select).all();
- for (Row row : rows) {
- logger.debug("{}", row);
- }
- return rows;
- }
- } finally {
- if (cluster != null) {
- cluster.close();
- }
- }
- return null;
- }
- //
- // public static void main(String[] args) throws FileNotFoundException {
- // Map<AuditingFieldsKeysEnum, String> map = new HashMap<>();
- // map.put(AuditingFieldsKeysEnum.AUDIT_ACTION, "Access");
- // map.put(AuditingFieldsKeysEnum.AUDIT_STATUS, "200");
- // // CassandraUtils.truncateTable("sdcartifact", "resources");
- //// CassandraUtils.truncateAllTables("sdcaudit");
- // CassandraUtils.fetchFromTable("sdcaudit", "useraccessevent", map );
- // }
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/AtomicOperationUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/AtomicOperationUtils.java
deleted file mode 100644
index 465153af14..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/AtomicOperationUtils.java
+++ /dev/null
@@ -1,692 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utils.general;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.AssertJUnit.assertTrue;
-
-import java.io.File;
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Map;
-
-import org.apache.commons.codec.binary.Base64;
-import org.apache.commons.lang3.tuple.Pair;
-import org.json.JSONException;
-import org.openecomp.sdc.be.datatypes.elements.ConsumerDataDefinition;
-import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
-import org.openecomp.sdc.be.model.ArtifactDefinition;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.ComponentInstanceProperty;
-import org.openecomp.sdc.be.model.DistributionStatusEnum;
-import org.openecomp.sdc.be.model.Product;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.Service;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.ImportReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.ProductReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.PropertyReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
-import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
-import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum;
-import org.openecomp.sdc.ci.tests.datatypes.enums.PropertyTypeEnum;
-import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum;
-import org.openecomp.sdc.ci.tests.datatypes.enums.ServiceCategoriesEnum;
-import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
-import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
-import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
-import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
-import org.openecomp.sdc.ci.tests.utils.rest.ComponentInstanceRestUtils;
-import org.openecomp.sdc.ci.tests.utils.rest.ConsumerRestUtils;
-import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
-import org.openecomp.sdc.ci.tests.utils.rest.ProductRestUtils;
-import org.openecomp.sdc.ci.tests.utils.rest.PropertyRestUtils;
-import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
-import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
-import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
-import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
-
-import com.google.gson.Gson;
-
-import fj.data.Either;
-
-public final class AtomicOperationUtils {
-
- private AtomicOperationUtils() {
- throw new UnsupportedOperationException();
- }
-
- // *********** RESOURCE ****************
- /**
- * Import a vfc From tosca file
- *
- * @param filePath
- * @param fileName
- * @return
- * @throws IOException
- * @throws JSONException
- */
- public static Either<Resource, RestResponse> importResource(String filePath, String fileName) {
- try {
- User designer = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
- ImportReqDetails importReqDetails = ElementFactory.getDefaultImportResource("ciTmpVFC");
- importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, filePath, fileName);
- RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, designer, null);
- return buildResourceFromResponse(importResourceResponse);
- } catch (Exception e) {
- throw new AtomicOperationException(e);
- }
- }
-
- public static Either<Resource, RestResponse> createResourceByType(ResourceTypeEnum resourceType, UserRoleEnum userRole, Boolean validateState) {
- try {
- User defaultUser = ElementFactory.getDefaultUser(userRole);
- ResourceReqDetails defaultResource = ElementFactory.getDefaultResourceByType(resourceType, defaultUser);
- RestResponse resourceResp = ResourceRestUtils.createResource(defaultResource, defaultUser);
-
- if (validateState) {
- assertTrue(resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED);
- }
-
- if (resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) {
- Resource resourceResponseObject = ResponseParser.convertResourceResponseToJavaObject(resourceResp.getResponse());
- return Either.left(resourceResponseObject);
- }
- return Either.right(resourceResp);
- } catch (Exception e) {
- throw new AtomicOperationException(e);
- }
- }
-
- public static Either<Resource, RestResponse> createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum resourceType, NormativeTypesEnum normativeTypes, ResourceCategoryEnum resourceCategory, UserRoleEnum userRole, Boolean validateState)
- throws Exception {
- User defaultUser = ElementFactory.getDefaultUser(userRole);
- ResourceReqDetails defaultResource = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(resourceType, normativeTypes, resourceCategory, defaultUser);
- RestResponse resourceResp = ResourceRestUtils.createResource(defaultResource, defaultUser);
-
- if (validateState) {
- assertTrue(resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED);
- }
-
- if (resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) {
- // Resource resourceResponseObject = ResponseParser
- // .convertResourceResponseToJavaObject(resourceResp.getResponse());
- Resource resourceResponseObject = ResponseParser.parseToObjectUsingMapper(resourceResp.getResponse(), Resource.class);
- return Either.left(resourceResponseObject);
- }
- return Either.right(resourceResp);
- }
-
- public static Either<Resource, RestResponse> createResourcesByCustomNormativeTypeAndCatregory(ResourceTypeEnum resourceType, Resource resourceNormativeType, ResourceCategoryEnum resourceCategory, UserRoleEnum userRole, Boolean validateState)
- throws Exception {
- User defaultUser = ElementFactory.getDefaultUser(userRole);
- ResourceReqDetails defaultResource = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(resourceType, resourceNormativeType, resourceCategory, defaultUser);
- RestResponse resourceResp = ResourceRestUtils.createResource(defaultResource, defaultUser);
-
- if (validateState) {
- assertTrue("actual result: " + resourceResp.getResponseMessage(), resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED);
- }
-
- if (resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) {
- // Resource resourceResponseObject = ResponseParser
- // .convertResourceResponseToJavaObject(resourceResp.getResponse());
- Resource resourceResponseObject = ResponseParser.parseToObjectUsingMapper(resourceResp.getResponse(), Resource.class);
- return Either.left(resourceResponseObject);
- }
- return Either.right(resourceResp);
- }
-
- // *********** SERVICE ****************
-
- public static Either<Service, RestResponse> createDefaultService(UserRoleEnum userRole, Boolean validateState) throws Exception {
- User defaultUser = ElementFactory.getDefaultUser(userRole);
- ServiceReqDetails serviceDetails = ElementFactory.getDefaultService(defaultUser);
- RestResponse createServiceResp = ServiceRestUtils.createService(serviceDetails, defaultUser);
-
- if (validateState) {
- assertTrue(createServiceResp.getErrorCode() == ServiceRestUtils.STATUS_CODE_CREATED);
- }
-
- if (createServiceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) {
- Service serviceResponseObject = ResponseParser.convertServiceResponseToJavaObject(createServiceResp.getResponse());
- return Either.left(serviceResponseObject);
- }
- return Either.right(createServiceResp);
- }
-
- public static Either<Service, RestResponse> createServiceByCategory(ServiceCategoriesEnum category, UserRoleEnum userRole, Boolean validateState) throws Exception {
- User defaultUser = ElementFactory.getDefaultUser(userRole);
- ServiceReqDetails serviceDetails = ElementFactory.getDefaultService(category, defaultUser);
- RestResponse createServiceResp = ServiceRestUtils.createService(serviceDetails, defaultUser);
-
- if (validateState) {
- assertTrue(createServiceResp.getErrorCode() == ServiceRestUtils.STATUS_CODE_CREATED);
- }
-
- if (createServiceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) {
- Service serviceResponseObject = ResponseParser.convertServiceResponseToJavaObject(createServiceResp.getResponse());
- return Either.left(serviceResponseObject);
- }
- return Either.right(createServiceResp);
- }
-
- // *********** PRODUCT ****************
-
- public static Either<Product, RestResponse> createDefaultProduct(UserRoleEnum userRole, Boolean validateState) throws Exception {
- User defaultUser = ElementFactory.getDefaultUser(userRole);
- ProductReqDetails defaultProduct = ElementFactory.getDefaultProduct();
- RestResponse createProductResp = ProductRestUtils.createProduct(defaultProduct, defaultUser);
-
- if (validateState) {
- assertTrue(createProductResp.getErrorCode() == ProductRestUtils.STATUS_CODE_CREATED);
- }
-
- if (createProductResp.getErrorCode() == ProductRestUtils.STATUS_CODE_CREATED) {
- Product productResponseJavaObject = ResponseParser.convertProductResponseToJavaObject(createProductResp.getResponse());
- return Either.left(productResponseJavaObject);
- }
- return Either.right(createProductResp);
- }
-
- // public static ComponentReqDetails
- // convertCompoentToComponentReqDetails(Component component){
- //
- // ComponentReqDetails componentReqDetails =
- // ElementFactory.getDefaultService();
- // componentReqDetails.setName(component.getName());
- // componentReqDetails.setDescription(component.getDescription());
- // componentReqDetails.setTags(component.getTags());
- // componentReqDetails.setContactId(component.getContactId());
- // componentReqDetails.setIcon(component.getIcon());
- // componentReqDetails.setUniqueId(component.getUniqueId());
- // componentReqDetails.setCreatorUserId(component.getCreatorUserId());
- // componentReqDetails.setCreatorFullName(component.getCreatorFullName());
- // componentReqDetails.setLastUpdaterUserId(component.getLastUpdaterUserId());
- // componentReqDetails.setLastUpdaterFullName(component.getLastUpdaterFullName());
- // componentReqDetails.setCreationDate(component.getCreationDate());
- // componentReqDetails.setLastUpdateDate(component.getLastUpdateDate());
- // componentReqDetails.setLifecycleState(component.getLifecycleState());
- // componentReqDetails.setVersion(component.getVersion());
- // componentReqDetails.setUuid(component.getUUID());
- // componentReqDetails.setCategories(component.getCategories());
- // componentReqDetails.setProjectCode(component.getProjectCode());
- //
- // return componentReqDetails;
- // }
-
- // *********** LIFECYCLE ***************
-
- public static Pair<Component, RestResponse> changeComponentState(Component component, UserRoleEnum userRole, LifeCycleStatesEnum targetState, Boolean validateState) throws Exception {
-
- Boolean isValidationFailed = false;
- RestResponse lifeCycleStatesResponse = null;
- User defaultUser = ElementFactory.getDefaultUser(userRole);
-
- LifeCycleStatesEnum curentCompState = LifeCycleStatesEnum.findByCompState(component.getLifecycleState().toString());
-
- if (curentCompState == targetState) {
- component = getCompoenntObject(component, userRole);
- return Pair.of(component, null);
- }
- // List<LifeCycleStatesEnum> lifeCycleStatesEnumOrigList = new
- // ArrayList<LifeCycleStatesEnum>(EnumSet.allOf(LifeCycleStatesEnum.class));
-
- ArrayList<String> lifeCycleStatesEnumList = new ArrayList<String>();
- if (curentCompState.equals(LifeCycleStatesEnum.CHECKIN) && targetState.equals(LifeCycleStatesEnum.CHECKOUT)) {
- lifeCycleStatesEnumList.add(LifeCycleStatesEnum.CHECKIN.toString());
- lifeCycleStatesEnumList.add(LifeCycleStatesEnum.CHECKOUT.toString());
- } else {
- lifeCycleStatesEnumList.add(LifeCycleStatesEnum.CHECKOUT.toString());
- lifeCycleStatesEnumList.add(LifeCycleStatesEnum.CHECKIN.toString());
- lifeCycleStatesEnumList.add(LifeCycleStatesEnum.CERTIFICATIONREQUEST.toString());
- lifeCycleStatesEnumList.add(LifeCycleStatesEnum.STARTCERTIFICATION.toString());
- lifeCycleStatesEnumList.add(LifeCycleStatesEnum.CERTIFY.toString());
- }
- for (int i = 0; i < lifeCycleStatesEnumList.size(); i++) {
- if (lifeCycleStatesEnumList.get(i).equals(curentCompState.name())) {
- int a;
- a = (i == lifeCycleStatesEnumList.size() - 1) ? 0 : i + 1;
-
- for (int n = a; n < lifeCycleStatesEnumList.size(); n++) {
- if (lifeCycleStatesEnumList.get(n).equals(LifeCycleStatesEnum.STARTCERTIFICATION.name()) || lifeCycleStatesEnumList.get(n).equals(LifeCycleStatesEnum.CERTIFY.name())) {
- defaultUser = ElementFactory.getDefaultUser(UserRoleEnum.TESTER);
- } else
- defaultUser = ElementFactory.getDefaultUser(userRole);
-
- lifeCycleStatesResponse = LifecycleRestUtils.changeComponentState(component, defaultUser, LifeCycleStatesEnum.findByState(lifeCycleStatesEnumList.get(n)));
- if (lifeCycleStatesResponse.getErrorCode() != LifecycleRestUtils.STATUS_CODE_SUCCESS)
- isValidationFailed = true;
- if (lifeCycleStatesEnumList.get(n).equals(targetState.toString()) || isValidationFailed == true) {
- break;
- }
- }
- }
-
- }
- Component componentJavaObject = getCompoenntObject(component, userRole);
-
- if (validateState == true && isValidationFailed == true) {
- assertTrue("change state failed" + lifeCycleStatesResponse.getResponse(), false);
-
- return Pair.of(componentJavaObject, lifeCycleStatesResponse);
- }
-
- if (isValidationFailed == true) {
- return Pair.of(componentJavaObject, lifeCycleStatesResponse);
- }
-
- return Pair.of(componentJavaObject, lifeCycleStatesResponse);
- }
-
- public static RestResponse distributeService(Component component, Boolean validateState) throws Exception {
-
- Service service = (Service) component;
-
- User opsUser = ElementFactory.getDefaultUser(UserRoleEnum.OPS);
- User governotUser = ElementFactory.getDefaultUser(UserRoleEnum.GOVERNOR);
-
- ServiceReqDetails serviceDetails = new ServiceReqDetails(service);
- RestResponse distributionService = null;
-
- RestResponse approveDistribution = LifecycleRestUtils.changeDistributionStatus(serviceDetails, null, governotUser, "approveService", DistributionStatusEnum.DISTRIBUTION_APPROVED);
- if (approveDistribution.getErrorCode() == 200) {
- distributionService = LifecycleRestUtils.changeDistributionStatus(serviceDetails, null, opsUser, "approveService", DistributionStatusEnum.DISTRIBUTED);
- }
-
- if (validateState) {
- assertTrue(approveDistribution.getErrorCode() == ProductRestUtils.STATUS_CODE_SUCCESS);
- assertTrue(distributionService.getErrorCode() == ProductRestUtils.STATUS_CODE_SUCCESS);
- return distributionService;
- }
-
- return distributionService;
-
- }
-
- public static RestResponse approveAndRejectServiceForDistribution(Component component) throws Exception {
-
- Service service = (Service) component;
-
- User opsUser = ElementFactory.getDefaultUser(UserRoleEnum.OPS);
- opsUser.setRole("OPS");
- User governotUser = ElementFactory.getDefaultUser(UserRoleEnum.GOVERNOR);
-
- ServiceReqDetails serviceDetails = new ServiceReqDetails(service);
- RestResponse distributionService = null;
-
- RestResponse approveDistribution = LifecycleRestUtils.changeDistributionStatus(serviceDetails, null, governotUser, "approveService", DistributionStatusEnum.DISTRIBUTION_APPROVED);
- if (approveDistribution.getErrorCode() == 200) {
- distributionService = LifecycleRestUtils.changeDistributionStatus(serviceDetails, null, opsUser, "rejectService", DistributionStatusEnum.DISTRIBUTION_REJECTED);
- }
-
- assertEquals(approveDistribution.getErrorCode(), new Integer(ProductRestUtils.STATUS_CODE_SUCCESS));
- assertEquals(distributionService.getErrorCode(), new Integer(ProductRestUtils.STATUS_CODE_SUCCESS));
-
- return distributionService;
-
- }
-
- // *********** ARTIFACTS *****************
-
- public static Either<ArtifactDefinition, RestResponse> uploadArtifactByType(ArtifactTypeEnum artifactType, Component component, UserRoleEnum userRole, Boolean deploymentTrue, Boolean validateState) throws Exception {
-
- User defaultUser = ElementFactory.getDefaultUser(userRole);
- ArtifactReqDetails artifactDetails = ElementFactory.getArtifactByType(null, artifactType, deploymentTrue);
- if (deploymentTrue == false)
- artifactDetails.setArtifactGroupType(ArtifactGroupTypeEnum.INFORMATIONAL.getType());
- RestResponse uploadArtifactResp = ArtifactRestUtils.uploadArtifact(artifactDetails, component, defaultUser);
-
- if (validateState) {
- assertTrue("artifact upload failed: " + artifactDetails.getArtifactName(), uploadArtifactResp.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
- }
-
- if (uploadArtifactResp.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS) {
- ArtifactDefinition artifactJavaObject = ResponseParser.convertArtifactDefinitionResponseToJavaObject(uploadArtifactResp.getResponse());
- return Either.left(artifactJavaObject);
- }
- return Either.right(uploadArtifactResp);
- }
-
- // *********** CONTAINERS *****************
- /**
- * Adds Component instance to Component
- *
- * @param compInstParent
- * @param compContainer
- * @return
- */
- public static Either<ComponentInstance, RestResponse> addComponentInstanceToComponentContainer(Component compInstParent, Component compContainer) {
- return addComponentInstanceToComponentContainer(compInstParent, compContainer, UserRoleEnum.DESIGNER, false);
- }
-
- public static Either<ComponentInstance, RestResponse> addComponentInstanceToComponentContainer(Component compInstParent, Component compContainer, UserRoleEnum userRole, Boolean validateState) {
- try {
- User defaultUser = ElementFactory.getDefaultUser(userRole);
- ComponentInstanceReqDetails componentInstanceDetails = ElementFactory.getComponentInstance(compInstParent);
- RestResponse createComponentInstance = ComponentInstanceRestUtils.createComponentInstance(componentInstanceDetails, defaultUser, compContainer);
-
- if (validateState) {
- assertTrue(createComponentInstance.getErrorCode() == ServiceRestUtils.STATUS_CODE_CREATED);
- }
-
- if (createComponentInstance.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) {
- ComponentInstance componentInstance = ResponseParser.convertComponentInstanceResponseToJavaObject(createComponentInstance.getResponse());
- return Either.left(componentInstance);
- }
- return Either.right(createComponentInstance);
- } catch (Exception e) {
- throw new AtomicOperationException(e);
- }
- }
-
- public static Resource getResourceObject(Component containerDetails, UserRoleEnum userRole) throws Exception {
- // User defaultUser = ElementFactory.getDefaultUser(userRole);
- RestResponse restResponse = ResourceRestUtils.getResource(containerDetails.getUniqueId());
- Resource container = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse());
- return container;
- }
-
- public static Resource getResourceObjectByNameAndVersion(UserRoleEnum sdncModifierDetails, String resourceName, String resourceVersion) throws Exception {
- User defaultUser = ElementFactory.getDefaultUser(sdncModifierDetails);
- RestResponse resourceResponse = ResourceRestUtils.getResourceByNameAndVersion(defaultUser.getUserId(), resourceName, resourceVersion);
- Resource container = ResponseParser.convertResourceResponseToJavaObject(resourceResponse.getResponse());
- return container;
- }
-
- public static Service getServiceObject(Component containerDetails, UserRoleEnum userRole) throws Exception {
- User defaultUser = ElementFactory.getDefaultUser(userRole);
- RestResponse serviceResponse = ServiceRestUtils.getService(containerDetails.getUniqueId(), defaultUser);
- Service container = ResponseParser.convertServiceResponseToJavaObject(serviceResponse.getResponse());
- return container;
- }
-
- public static Service getServiceObjectByNameAndVersion(UserRoleEnum sdncModifierDetails, String serviceName, String serviceVersion) throws Exception {
- User defaultUser = ElementFactory.getDefaultUser(sdncModifierDetails);
- RestResponse serviceResponse = ServiceRestUtils.getServiceByNameAndVersion(defaultUser, serviceName, serviceVersion);
- Service container = ResponseParser.convertServiceResponseToJavaObject(serviceResponse.getResponse());
- return container;
- }
-
- public static Product getProductObject(Component containerDetails, UserRoleEnum userRole) throws Exception {
- User defaultUser = ElementFactory.getDefaultUser(userRole);
- RestResponse productRest = ProductRestUtils.getProduct(containerDetails.getUniqueId(), defaultUser.getUserId());
- Product container = ResponseParser.convertProductResponseToJavaObject(productRest.getResponse());
- return container;
- }
-
- public static Component getCompoenntObject(Component containerDetails, UserRoleEnum userRole) throws Exception {
- User defaultUser = ElementFactory.getDefaultUser(userRole);
-
- switch (containerDetails.getComponentType()) {
- case RESOURCE:
- RestResponse restResponse = ResourceRestUtils.getResource(containerDetails.getUniqueId());
- containerDetails = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse());
- break;
- case SERVICE:
- RestResponse serviceResponse = ServiceRestUtils.getService(containerDetails.getUniqueId(), defaultUser);
- containerDetails = ResponseParser.convertServiceResponseToJavaObject(serviceResponse.getResponse());
- break;
- case PRODUCT:
- RestResponse productRest = ProductRestUtils.getProduct(containerDetails.getUniqueId(), defaultUser.getUserId());
- containerDetails = ResponseParser.convertProductResponseToJavaObject(productRest.getResponse());
- break;
- default:
- break;
- }
- return containerDetails;
- }
-
- public static Component convertReposnseToComponentObject(Component containerDetails, RestResponse restresponse) throws Exception {
-
- switch (containerDetails.getComponentType()) {
- case RESOURCE:
- containerDetails = ResponseParser.convertResourceResponseToJavaObject(restresponse.getResponse());
- break;
- case SERVICE:
- containerDetails = ResponseParser.convertServiceResponseToJavaObject(restresponse.getResponse());
- break;
- case PRODUCT:
- containerDetails = ResponseParser.convertProductResponseToJavaObject(restresponse.getResponse());
- break;
- default:
- break;
- }
- return containerDetails;
- }
-
- public static RestResponse associate2ResourceInstances(Component containerDetails, ComponentInstance fromNode, ComponentInstance toNode, String assocType, UserRoleEnum userRole, Boolean validateState) throws IOException {
- User defaultUser = ElementFactory.getDefaultUser(userRole);
- RestResponse associate2ResourceInstancesResponse = ResourceRestUtils.associate2ResourceInstances(containerDetails, fromNode, toNode, assocType, defaultUser);
-
- if (validateState) {
- assertTrue(associate2ResourceInstancesResponse.getErrorCode() == ServiceRestUtils.STATUS_CODE_SUCCESS);
- }
-
- return associate2ResourceInstancesResponse;
- }
-
- public static Either<Pair<Component, ComponentInstance>, RestResponse> changeComponentInstanceVersion(Component containerDetails, ComponentInstance componentInstanceToReplace, Component newInstance, UserRoleEnum userRole, Boolean validateState)
- throws Exception {
- User defaultUser = ElementFactory.getDefaultUser(userRole);
-
- RestResponse changeComponentInstanceVersionResp = ComponentInstanceRestUtils.changeComponentInstanceVersion(containerDetails, componentInstanceToReplace, newInstance, defaultUser);
- if (validateState) {
- assertTrue("change ComponentInstance version failed: " + changeComponentInstanceVersionResp.getResponseMessage(), changeComponentInstanceVersionResp.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
- }
-
- if (changeComponentInstanceVersionResp.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS) {
-
- Component compoenntObject = AtomicOperationUtils.getCompoenntObject(containerDetails, userRole);
- ComponentInstance componentInstanceJavaObject = ResponseParser.convertComponentInstanceResponseToJavaObject(changeComponentInstanceVersionResp.getResponse());
-
- return Either.left(Pair.of(compoenntObject, componentInstanceJavaObject));
- }
-
- return Either.right(changeComponentInstanceVersionResp);
- }
-
- // *********** PROPERTIES *****************
-
- public static Either<ComponentInstanceProperty, RestResponse> addCustomPropertyToResource(PropertyReqDetails propDetails, Resource resourceDetails, UserRoleEnum userRole, Boolean validateState) throws Exception {
-
- User defaultUser = ElementFactory.getDefaultUser(userRole);
- Map<String, PropertyReqDetails> propertyToSend = new HashMap<String, PropertyReqDetails>();
- propertyToSend.put(propDetails.getName(), propDetails);
- Gson gson = new Gson();
- RestResponse addPropertyResponse = PropertyRestUtils.createProperty(resourceDetails.getUniqueId(), gson.toJson(propertyToSend), defaultUser);
-
- if (validateState) {
- assertTrue("add property to resource failed: " + addPropertyResponse.getErrorCode(), addPropertyResponse.getErrorCode() == BaseRestUtils.STATUS_CODE_CREATED);
- }
-
- if (addPropertyResponse.getErrorCode() == BaseRestUtils.STATUS_CODE_CREATED) {
- ComponentInstanceProperty compInstProp = null;
- String property = ResponseParser.getJsonObjectValueByKey(addPropertyResponse.getResponse(), propDetails.getName());
- compInstProp = (ResponseParser.convertPropertyResponseToJavaObject(property));
- return Either.left(compInstProp);
- }
- return Either.right(addPropertyResponse);
- }
-
- // Benny
- public static Either<ComponentInstanceProperty, RestResponse> updatePropertyOfResource(PropertyReqDetails propDetails, Resource resourceDetails, String propertyUniqueId, UserRoleEnum userRole, Boolean validateState) throws Exception {
-
- User defaultUser = ElementFactory.getDefaultUser(userRole);
- Map<String, PropertyReqDetails> propertyToSend = new HashMap<String, PropertyReqDetails>();
- propertyToSend.put(propDetails.getName(), propDetails);
- Gson gson = new Gson();
- RestResponse addPropertyResponse = PropertyRestUtils.updateProperty(resourceDetails.getUniqueId(), propertyUniqueId, gson.toJson(propertyToSend), defaultUser);
-
- if (validateState) {
- assertTrue("add property to resource failed: " + addPropertyResponse.getResponseMessage(), addPropertyResponse.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
- }
-
- if (addPropertyResponse.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS) {
- ComponentInstanceProperty compInstProp = null;
- String property = ResponseParser.getJsonObjectValueByKey(addPropertyResponse.getResponse(), propDetails.getName());
- compInstProp = (ResponseParser.convertPropertyResponseToJavaObject(property));
- return Either.left(compInstProp);
- }
- return Either.right(addPropertyResponse);
- }
-
- public static RestResponse deletePropertyOfResource(String resourceId, String propertyId, UserRoleEnum userRole) throws Exception {
- User defaultUser = ElementFactory.getDefaultUser(userRole);
- return PropertyRestUtils.deleteProperty(resourceId, propertyId, defaultUser);
- }
-
- public static Either<ComponentInstanceProperty, RestResponse> addDefaultPropertyToResource(PropertyTypeEnum propertyType, Resource resourceDetails, UserRoleEnum userRole, Boolean validateState) throws Exception {
-
- User defaultUser = ElementFactory.getDefaultUser(userRole);
- PropertyReqDetails propDetails = ElementFactory.getPropertyDetails(propertyType);
- Map<String, PropertyReqDetails> propertyToSend = new HashMap<String, PropertyReqDetails>();
- propertyToSend.put(propDetails.getName(), propDetails);
- Gson gson = new Gson();
- RestResponse addPropertyResponse = PropertyRestUtils.createProperty(resourceDetails.getUniqueId(), gson.toJson(propertyToSend), defaultUser);
-
- if (validateState) {
- assertTrue("add property to resource failed: " + addPropertyResponse.getResponseMessage(), addPropertyResponse.getErrorCode() == BaseRestUtils.STATUS_CODE_CREATED);
- }
-
- if (addPropertyResponse.getErrorCode() == BaseRestUtils.STATUS_CODE_CREATED) {
- ComponentInstanceProperty compInstProp = null;
- String property = ResponseParser.getJsonObjectValueByKey(addPropertyResponse.getResponse(), propDetails.getName());
- compInstProp = (ResponseParser.convertPropertyResponseToJavaObject(property));
-
- return Either.left(compInstProp);
- }
- return Either.right(addPropertyResponse);
- }
-
- public static RestResponse createDefaultConsumer(Boolean validateState) {
- try {
- ConsumerDataDefinition defaultConsumerDefinition = ElementFactory.getDefaultConsumerDetails();
- RestResponse createResponse = ConsumerRestUtils.createConsumer(defaultConsumerDefinition, ElementFactory.getDefaultUser(UserRoleEnum.ADMIN));
- BaseRestUtils.checkCreateResponse(createResponse);
-
- if (validateState) {
- assertTrue(createResponse.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED);
- }
- return createResponse;
- } catch (Exception e) {
- throw new AtomicOperationException(e);
- }
- }
-
- /**
- * Builds Resource From rest response
- *
- * @param resourceResp
- * @return
- */
- public static Either<Resource, RestResponse> buildResourceFromResponse(RestResponse resourceResp) {
- Either<Resource, RestResponse> result;
- if (resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) {
- Resource resourceResponseObject = ResponseParser.convertResourceResponseToJavaObject(resourceResp.getResponse());
- result = Either.left(resourceResponseObject);
- } else {
- result = Either.right(resourceResp);
- }
- return result;
- }
-
- private static class AtomicOperationException extends RuntimeException {
- private AtomicOperationException(Exception e) {
- super(e);
- }
-
- private static final long serialVersionUID = 1L;
- };
-
- /**
- * Import resource from CSAR
- *
- * @param resourceType
- * @param userRole
- * @param fileName
- * @param filePath
- * @return Resource
- * @throws Exception
- */
- public static Resource importResourceFromCSAR(ResourceTypeEnum resourceType, UserRoleEnum userRole, String fileName, String... filePath) throws Exception {
- // Get the CSARs path
- String realFilePath = System.getProperty("user.dir") + File.separator + "src" + File.separator + "test" + File.separator + "resources" + File.separator + "CI" + File.separator + "csars" ;
- if (filePath != null && filePath.length > 0) {
- realFilePath = filePath.toString();
- }
-
- // Create default import resource & user
- ImportReqDetails resourceDetails = ElementFactory.getDefaultImportResource();
- User sdncModifierDetails = ElementFactory.getDefaultUser(userRole);
-
- byte[] data = null;
- Path path = Paths.get(realFilePath + File.separator + fileName);
- data = Files.readAllBytes(path);
- String payloadName = fileName;
- String payloadData = Base64.encodeBase64String(data);
- resourceDetails.setPayloadData(payloadData);
- resourceDetails.setCsarUUID(payloadName);
- resourceDetails.setPayloadName(payloadName);
- resourceDetails.setResourceType(resourceType.name());
-
- RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
- BaseRestUtils.checkCreateResponse(createResource);
- return ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
- };
-
- public static Either<Resource, RestResponse> importResourceByFileName(ResourceTypeEnum resourceType, UserRoleEnum userRole, String fileName, Boolean validateState, String... filePath) throws IOException {
-
- String realFilePath = System.getProperty("user.dir") + File.separator + "src" + File.separator + "test" + File.separator + "resources" + File.separator + "CI" + File.separator + "csars" ;
- if (filePath != null && filePath.length > 0) {
- realFilePath = filePath.toString();
- }
-
- try {
- User defaultUser = ElementFactory.getDefaultUser(userRole);
- ResourceReqDetails defaultResource = ElementFactory.getDefaultResource(defaultUser);
- ImportReqDetails defaultImportResource = ElementFactory.getDefaultImportResource(defaultResource);
- ImportUtils.getImportResourceDetailsByPathAndName(defaultImportResource, realFilePath, fileName);
- RestResponse resourceResp = ResourceRestUtils.createResource(defaultImportResource, defaultUser);
-
- if (validateState) {
- assertTrue(resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED);
- }
-
- if (resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) {
- Resource resourceResponseObject = ResponseParser.convertResourceResponseToJavaObject(resourceResp.getResponse());
- return Either.left(resourceResponseObject);
- }
- return Either.right(resourceResp);
- } catch (Exception e) {
- throw new AtomicOperationException(e);
- }
- }
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/Convertor.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/Convertor.java
deleted file mode 100644
index a9b8aaea15..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/Convertor.java
+++ /dev/null
@@ -1,341 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utils.general;
-
-import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_CREATED;
-import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_SUCCESS;
-
-import java.io.FileNotFoundException;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.apache.commons.lang3.StringUtils;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.model.LifecycleStateEnum;
-import org.openecomp.sdc.be.model.Product;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.model.category.CategoryDefinition;
-import org.openecomp.sdc.ci.tests.datatypes.ComponentReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.ProductReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.ResourceRespJavaObject;
-import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo;
-import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
-import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedProductAudit;
-import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedResourceAuditJavaObject;
-import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedUserCRUDAudit;
-import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
-import org.openecomp.sdc.common.api.Constants;
-
-public class Convertor {
- // ***** resource *****
- public static ResourceRespJavaObject constructFieldsForRespValidation(ResourceReqDetails resourceDetails,
- String resourceVersion) {
- return convertToRespObject(resourceDetails, resourceVersion, UserRoleEnum.ADMIN.getUserId(),
- UserRoleEnum.ADMIN.getUserName());
-
- }
-
- public static ResourceRespJavaObject constructFieldsForRespValidation(ResourceReqDetails resourceDetails) {
- return convertToRespObject(resourceDetails, resourceDetails.getVersion(), UserRoleEnum.ADMIN.getUserId(),
- UserRoleEnum.ADMIN.getUserName());
-
- }
-
- public static ResourceRespJavaObject constructFieldsForRespValidation(ResourceReqDetails resourceDetails,
- String resourceVersion, User user) {
- return convertToRespObject(resourceDetails, resourceVersion, user.getUserId(), user.getFullName());
-
- }
-
- private static ResourceRespJavaObject convertToRespObject(ResourceReqDetails resourceDetails,
- String resourceVersion, String userId, String userName) {
- ResourceRespJavaObject resourceRespJavaObject = new ResourceRespJavaObject();
-
- resourceRespJavaObject.setUniqueId(resourceDetails.getUniqueId());
- resourceRespJavaObject.setName(resourceDetails.getName());
- resourceRespJavaObject.setCreatorUserId(resourceDetails.getCreatorUserId());
- resourceRespJavaObject.setCreatorFullName(resourceDetails.getCreatorFullName());
- resourceRespJavaObject.setLastUpdaterUserId(userId);
- resourceRespJavaObject.setLastUpdaterFullName(userName);
- resourceRespJavaObject.setDescription(resourceDetails.getDescription());
- resourceRespJavaObject.setIcon(resourceDetails.getIcon());
- resourceRespJavaObject.setTags(resourceDetails.getTags());
- resourceRespJavaObject.setIsHighestVersion("true");
- resourceRespJavaObject.setCategories(resourceDetails.getCategories());
- resourceRespJavaObject.setLifecycleState(
- resourceDetails.getLifecycleState() != null ? resourceDetails.getLifecycleState().toString()
- : LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.toString());
- // resourceRespJavaObject.setLifecycleState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
- resourceRespJavaObject.setDerivedFrom(resourceDetails.getDerivedFrom());
- resourceRespJavaObject.setVendorName(resourceDetails.getVendorName());
- resourceRespJavaObject.setVendorRelease(resourceDetails.getVendorRelease());
- resourceRespJavaObject.setContactId(resourceDetails.getContactId());
- resourceRespJavaObject.setAbstractt("false");
- resourceRespJavaObject.setVersion(resourceVersion);
- resourceRespJavaObject.setCost(resourceDetails.getCost());
- resourceRespJavaObject.setLicenseType(resourceDetails.getLicenseType());
- resourceRespJavaObject.setResourceType(resourceDetails.getResourceType());
-
- return resourceRespJavaObject;
-
- }
-
- // ********** service **************
-
- // public static ServiceRespJavaObject
- // constructFieldsForRespValidation(ServiceReqDetails serviceDetails, String
- // serviceVersion, User user) {
- // return convertToRespObject(serviceDetails, serviceVersion,
- // user.getUserId(), user.getFullName());
- //
- // }
- //
- // private static ServiceRespJavaObject
- // convertToRespObject(ServiceReqDetails serviceDetails, String
- // serviceVersion, String UserId, String userName) {
- // ServiceRespJavaObject serviceRespJavaObject = new
- // ServiceRespJavaObject();
- //
- // serviceRespJavaObject.setUniqueId(serviceDetails.getUniqueId());
- // serviceRespJavaObject.setName(serviceDetails.getName());
- // serviceRespJavaObject.setCreatorUserId(UserId);
- // serviceRespJavaObject.setCreatorFullName(userName);
- // serviceRespJavaObject.setLastUpdaterUserId(UserId);
- // serviceRespJavaObject.setLastUpdaterFullName(userName);
- // serviceRespJavaObject.setDescription(serviceDetails.getDescription());
- // serviceRespJavaObject.setIcon(serviceDetails.getIcon());
- // serviceRespJavaObject.setCategory(serviceDetails.getCategory());
- // serviceRespJavaObject.setLifecycleState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
- // serviceRespJavaObject.setContactId(serviceDetails.getContactId());
- // serviceRespJavaObject.setVersion(serviceVersion);
- //
- // return serviceRespJavaObject;
- // }
-
- // ********** product **************
-
- public static Product constructFieldsForRespValidation(ProductReqDetails productDetails, String productVersion,
- User user) {
- return convertToRespObject(productDetails, productVersion, user.getUserId(), user.getFullName());
- }
-
- private static Product convertToRespObject(ProductReqDetails productDetails, String productVersion, String userId,
- String userName) {
- Product expectedProduct = new Product();
-
- expectedProduct.setUniqueId(productDetails.getUniqueId());
- expectedProduct.setName(productDetails.getName());
- expectedProduct.setFullName(productDetails.getFullName());
- expectedProduct.setCreatorUserId(productDetails.getCreatorUserId());
- expectedProduct.setCreatorFullName(productDetails.getCreatorFullName());
- expectedProduct.setLastUpdaterUserId(userId);
- expectedProduct.setLastUpdaterFullName(userName);
- expectedProduct.setDescription(productDetails.getDescription());
- // expectedProduct.setIcon(resourceDetails.getIcon());
- expectedProduct.setTags(productDetails.getTags());
- expectedProduct.setHighestVersion(true);
- List<CategoryDefinition> categories = productDetails.getCategories();
- if (categories == null) {
- categories = new ArrayList<>();
- }
- expectedProduct.setCategories(categories);
- expectedProduct.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
- expectedProduct.setVersion(productVersion);
- expectedProduct.setContacts(productDetails.getContacts());
- return expectedProduct;
- }
-
- // ***** audit *****
-
- public static ExpectedResourceAuditJavaObject constructFieldsForAuditValidation(ResourceReqDetails resourceDetails,
- String resourceVersion) {
- return convertToAuditObject(resourceDetails, resourceVersion, UserRoleEnum.ADMIN.getUserId(),
- UserRoleEnum.ADMIN.getUserName());
- }
-
- public static ExpectedResourceAuditJavaObject constructFieldsForAuditValidation(
- ResourceReqDetails resourceDetails) {
- return convertToAuditObject(resourceDetails, resourceDetails.getVersion(), UserRoleEnum.ADMIN.getUserId(),
- UserRoleEnum.ADMIN.getUserName());
- }
-
- public static ExpectedResourceAuditJavaObject constructFieldsForAuditValidation(ResourceReqDetails resourceDetails,
- String resourceVersion, User user) {
- return convertToAuditObject(resourceDetails, resourceVersion, user.getUserId(), user.getFullName());
- }
-
- private static ExpectedResourceAuditJavaObject convertToAuditObject(ResourceReqDetails resourceDetails,
- String resourceVersion, String userId, String userName) {
- ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = new ExpectedResourceAuditJavaObject();
-
- expectedResourceAuditJavaObject.setAction("Checkout");
- expectedResourceAuditJavaObject.setModifierName(userName);
- expectedResourceAuditJavaObject.setModifierUid(userId);
- expectedResourceAuditJavaObject.setStatus("200.0");
- expectedResourceAuditJavaObject.setDesc("OK");
- expectedResourceAuditJavaObject.setResourceName(resourceDetails.getName());
- expectedResourceAuditJavaObject.setResourceType("Resource");
- expectedResourceAuditJavaObject.setPrevVersion(String.valueOf(Float.parseFloat(resourceVersion) - 0.1f));
- expectedResourceAuditJavaObject.setCurrVersion(resourceVersion);
- expectedResourceAuditJavaObject.setPrevState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
- expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
- expectedResourceAuditJavaObject.setComment(null);
-
- return expectedResourceAuditJavaObject;
- }
-
- public static ExpectedProductAudit constructFieldsForAuditValidation(Product productDetails, String action,
- User user, ActionStatus actionStatus, String prevVersion, String currVersion, LifecycleStateEnum prevState,
- LifecycleStateEnum currState, String uuid, String... errorMessageParams) throws FileNotFoundException {
- ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(actionStatus.name());
- return convertToAuditObject(productDetails, action, user, errorInfo, prevVersion, currVersion, prevState,
- currState, uuid, errorMessageParams);
- }
-
- private static ExpectedProductAudit convertToAuditObject(Product productDetails, String action, User user,
- ErrorInfo errorInfo, String prevVersion, String currVersion, LifecycleStateEnum prevState,
- LifecycleStateEnum currState, String uuid, String... errorMessageParams) {
- ExpectedProductAudit expectedProductAudit = new ExpectedProductAudit();
-
- expectedProductAudit.setACTION(action);
- String userUserId = user.getUserId();
- String userFullName;
- if (StringUtils.isEmpty(user.getFirstName()) && StringUtils.isEmpty(user.getLastName())) {
- userFullName = "";
- } else {
- userFullName = user.getFullName();
- }
- if (StringUtils.isEmpty(userUserId)) {
- userUserId = "UNKNOWN";
- }
- expectedProductAudit.setMODIFIER(
- !StringUtils.isEmpty(userFullName) ? userFullName + "(" + userUserId + ")" : "(" + userUserId + ")");
- expectedProductAudit.setSTATUS(Integer.toString(errorInfo.getCode()));
- expectedProductAudit.setDESC(errorInfo.getAuditDesc((Object[]) (errorMessageParams)));
- expectedProductAudit
- .setRESOURCE_NAME(productDetails != null ? productDetails.getName() : Constants.EMPTY_STRING);
- expectedProductAudit.setRESOURCE_TYPE("Product");
- expectedProductAudit.setPREV_VERSION(prevVersion);
- expectedProductAudit.setCURR_VERSION(currVersion);
- expectedProductAudit.setPREV_STATE(prevState != null ? prevState.name() : Constants.EMPTY_STRING);
- expectedProductAudit.setCURR_STATE(currState != null ? currState.name() : Constants.EMPTY_STRING);
- expectedProductAudit.setSERVICE_INSTANCE_ID(uuid);
- return expectedProductAudit;
- }
-
- ////////////////
- // Convertor.constructFieldsForAuditValidationSuccess(addUser,
- //////////////// sdncAdminUser, mechIdUser, null, STATUS_CODE_CREATED);
- public static ExpectedUserCRUDAudit constructFieldsForAuditValidation(String action, User userModifier,
- ActionStatus actionStatus, User userAfter, User userBefore, Object... variables) throws Exception {
- ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(actionStatus.name());
- ExpectedUserCRUDAudit expectedAddUserAuditJavaObject = new ExpectedUserCRUDAudit();
- expectedAddUserAuditJavaObject.setAction(action);
- expectedAddUserAuditJavaObject.setModifier(
- userModifier.getFirstName() != null ? userModifier.getFullName() + "(" + userModifier.getUserId() + ")"
- : "(" + userModifier.getUserId() + ")");
- String status = Integer.toString(errorInfo.getCode());
- expectedAddUserAuditJavaObject.setStatus(status);
- if (errorInfo.getCode() == STATUS_CODE_SUCCESS || errorInfo.getCode() == STATUS_CODE_CREATED) {
- expectedAddUserAuditJavaObject.setDesc("OK");
- } else {
- expectedAddUserAuditJavaObject.setDesc(errorInfo.getAuditDesc(variables));
- }
- expectedAddUserAuditJavaObject.setUserBefore(userBefore != null
- ? userBefore.getUserId() + ", " + userBefore.getFirstName() + " " + userBefore.getLastName() + ", "
- + userBefore.getEmail() + ", " + userBefore.getRole()
- : Constants.EMPTY_STRING);
- expectedAddUserAuditJavaObject.setUserAfter(userAfter != null
- ? userAfter.getUserId() + ", " + userAfter.getFirstName() + " " + userAfter.getLastName() + ", "
- + userAfter.getEmail() + ", " + userAfter.getRole()
- : Constants.EMPTY_STRING);
- return expectedAddUserAuditJavaObject;
- }
-
- // For RESOURCE and SERVICE same Audit
- public static ExpectedResourceAuditJavaObject constructFieldsForAuditValidation(
- ComponentReqDetails componentDetails, String action, User userModifier, ActionStatus actionStatus,
- String currVersion, String prevVersion, String curState, String prevState, String uuid, String comment,
- Object... variables) throws Exception {
- ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(actionStatus.name());
- ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = new ExpectedResourceAuditJavaObject();
- expectedResourceAuditJavaObject.setAction(action);
- expectedResourceAuditJavaObject.setMODIFIER(
- userModifier.getFirstName() != null ? userModifier.getFullName() + "(" + userModifier.getUserId() + ")"
- : "(" + userModifier.getUserId() + ")");
- String status = Integer.toString(errorInfo.getCode());
- expectedResourceAuditJavaObject.setStatus(status);
- if (errorInfo.getCode() == STATUS_CODE_SUCCESS || errorInfo.getCode() == STATUS_CODE_CREATED) {
- expectedResourceAuditJavaObject.setDesc("OK");
- } else {
- expectedResourceAuditJavaObject.setDesc(errorInfo.getAuditDesc(variables));
- }
- expectedResourceAuditJavaObject.setCurrState(curState);
- expectedResourceAuditJavaObject.setPrevState(prevState);
- expectedResourceAuditJavaObject.setCurrVersion(currVersion);
- expectedResourceAuditJavaObject.setPrevVersion(prevVersion);
- expectedResourceAuditJavaObject.setComment(comment);
- expectedResourceAuditJavaObject.setSERVICE_INSTANCE_ID(uuid);
- if (componentDetails instanceof ServiceReqDetails) {
- expectedResourceAuditJavaObject.setResourceName(((ServiceReqDetails) componentDetails).getName());
- expectedResourceAuditJavaObject.setResourceType("Service");
- }
- if (componentDetails instanceof ResourceReqDetails) {
- expectedResourceAuditJavaObject.setResourceName(((ResourceReqDetails) componentDetails).getName());
- expectedResourceAuditJavaObject.setResourceType("Resource");
- }
- return expectedResourceAuditJavaObject;
- }
-
- // Distribution Service Audit
- public static ExpectedResourceAuditJavaObject constructFieldsForDistributionAuditValidation(
- ComponentReqDetails componentDetails, String action, User userModifier, ActionStatus actionStatus,
- String currVersion, String distCurrStatus, String distProvStatus, String curState, String uuid,
- String comment, Object... variables) throws Exception {
- ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(actionStatus.name());
- ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = new ExpectedResourceAuditJavaObject();
- expectedResourceAuditJavaObject.setAction(action);
- expectedResourceAuditJavaObject.setMODIFIER(
- userModifier.getFirstName() != null ? userModifier.getFullName() + "(" + userModifier.getUserId() + ")"
- : "(" + userModifier.getUserId() + ")");
- String status = Integer.toString(errorInfo.getCode());
- expectedResourceAuditJavaObject.setStatus(status);
- if (errorInfo.getCode() == STATUS_CODE_SUCCESS || errorInfo.getCode() == STATUS_CODE_CREATED) {
- expectedResourceAuditJavaObject.setDesc("OK");
- } else {
- expectedResourceAuditJavaObject.setDesc(errorInfo.getAuditDesc(variables));
- }
- expectedResourceAuditJavaObject.setCurrState(curState);
- expectedResourceAuditJavaObject.setCurrVersion(currVersion);
- expectedResourceAuditJavaObject.setDcurrStatus(distCurrStatus);
- expectedResourceAuditJavaObject.setDprevStatus(distProvStatus);
- expectedResourceAuditJavaObject.setComment(comment);
- expectedResourceAuditJavaObject.setSERVICE_INSTANCE_ID(uuid);
- if (componentDetails instanceof ServiceReqDetails) {
- expectedResourceAuditJavaObject.setResourceName(((ServiceReqDetails) componentDetails).getName());
- expectedResourceAuditJavaObject.setResourceType("Service");
- }
- return expectedResourceAuditJavaObject;
- }
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/ElementFactory.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/ElementFactory.java
deleted file mode 100644
index 076261adef..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/ElementFactory.java
+++ /dev/null
@@ -1,948 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utils.general;
-
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.UUID;
-
-import org.apache.commons.lang.StringUtils;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.datatypes.elements.ConsumerDataDefinition;
-import org.openecomp.sdc.be.datatypes.enums.AssetTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
-import org.openecomp.sdc.be.model.ArtifactDefinition;
-import org.openecomp.sdc.be.model.CapabilityDefinition;
-import org.openecomp.sdc.be.model.CapabilityRequirementRelationship;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.LifecycleStateEnum;
-import org.openecomp.sdc.be.model.RelationshipImpl;
-import org.openecomp.sdc.be.model.RelationshipInfo;
-import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
-import org.openecomp.sdc.be.model.RequirementDefinition;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.model.category.CategoryDefinition;
-import org.openecomp.sdc.be.model.category.GroupingDefinition;
-import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
-import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
-import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.ComponentReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.ImportReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.ProductReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.PropertyReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.ResourceExternalReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
-import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo;
-import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum;
-import org.openecomp.sdc.ci.tests.datatypes.enums.PropertyTypeEnum;
-import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum;
-import org.openecomp.sdc.ci.tests.datatypes.enums.ServiceCategoriesEnum;
-import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
-import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedExternalAudit;
-import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedResourceAuditJavaObject;
-import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
-import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
-import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils;
-import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
-import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
-import org.openecomp.sdc.common.util.ValidationUtils;
-
-public class ElementFactory {
-
- private static final String JH0003 = "jh0003";
- private static final String CI_RES = "ciRes";
- private static String DEFAULT_ARTIFACT_LABEL = "artifact1";
- private static final String RESOURCE_INSTANCE_POS_X = "20";
- private static final String RESOURCE_INSTANCE_POS_Y = "20";
- private static final String RESOURCE_INSTANCE_DESCRIPTION = "description";
-
- // *** RESOURCE ***
-
- public static ResourceReqDetails getDefaultResource() {
- return getDefaultResource(CI_RES, NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, JH0003);
- }
-
- public static ResourceReqDetails getDefaultResource(ResourceCategoryEnum category) {
- return getDefaultResource(CI_RES, NormativeTypesEnum.ROOT, category, JH0003);
- }
-
- public static ResourceReqDetails getDefaultResource(String contactId) {
- return getDefaultResource(CI_RES, NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, contactId);
- }
-
- public static ResourceReqDetails getDefaultResource(User modifier) {
- return getDefaultResource(CI_RES, NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, modifier.getUserId());
- }
-
- public static ResourceReqDetails getDefaultResource(NormativeTypesEnum derivedFrom, ResourceCategoryEnum category) {
- return getDefaultResource(CI_RES, derivedFrom, category, JH0003);
- }
-
- public static ResourceReqDetails getDefaultResource(NormativeTypesEnum derivedFrom) {
- return getDefaultResource(CI_RES, derivedFrom, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, JH0003);
- }
-
- public static ResourceReqDetails getDefaultResource(String resourceName, NormativeTypesEnum derivedFrom) {
- return getDefaultResource(resourceName, derivedFrom, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, JH0003);
- }
-
- public static ResourceReqDetails getDefaultResource(NormativeTypesEnum derivedFrom, String contactId) {
- return getDefaultResource(CI_RES, derivedFrom, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, contactId);
- }
-
- // New
- public static ResourceReqDetails getDefaultResourceByType(ResourceTypeEnum ResourceType, String resourceName) {
- return getDefaultResourceByType(resourceName, NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, JH0003, ResourceType.toString());
- }
-
- public static ResourceReqDetails getDefaultResourceByType(ResourceTypeEnum ResourceType, User user) {
- return getDefaultResourceByType(CI_RES, NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, user.getUserId(), ResourceType.toString());
- }
-
- public static ResourceReqDetails getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum resourceType, NormativeTypesEnum normativeTypes, ResourceCategoryEnum resourceCategory, User user) {
- return getDefaultResourceByType(CI_RES, normativeTypes, resourceCategory, user.getUserId(), resourceType.toString());
- }
-
- public static PropertyReqDetails getDefaultMapProperty(PropertyTypeEnum innerType) {
- return getPropertyDetails(innerType);
- }
-
- public static PropertyReqDetails getDefaultMapProperty() {
- return getPropertyDetails(PropertyTypeEnum.STRING_MAP);
- }
-
- public static ResourceReqDetails getDefaultResource(String resourceName, NormativeTypesEnum derived, ResourceCategoryEnum category, String contactId) {
- resourceName = (resourceName + generateUUIDforSufix());
- String description = "Represents a generic software component that can be managed and run by a Compute Node Type.";
- ArrayList<String> resourceTags = new ArrayList<String>();
- resourceTags.add(resourceName);
-
- ArrayList<String> derivedFrom = new ArrayList<String>();
- derivedFrom.add(derived.normativeName);
- String vendorName = "ATT Tosca";
- String vendorRelease = "1.0.0.wd03";
- String icon = "defaulticon";
- ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, null, derivedFrom, vendorName, vendorRelease, contactId, icon);
- resourceDetails.addCategoryChain(category.getCategory(), category.getSubCategory());
-
- return resourceDetails;
-
- }
-
- public static ResourceReqDetails getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum resourceType, Resource normativeTypes, ResourceCategoryEnum resourceCategory, User user) {
- return getDefaultResource(CI_RES + resourceType, normativeTypes, resourceCategory, user.getUserId());
- }
-
- public static ResourceReqDetails getDefaultResource(String resourceName, Resource derived, ResourceCategoryEnum category, String contactId) {
- resourceName = (resourceName + generateUUIDforSufix());
- String description = "Represents a generic software component that can be managed and run by a Compute Node Type.";
- ArrayList<String> resourceTags = new ArrayList<String>();
- resourceTags.add(resourceName);
-
- ArrayList<String> derivedFrom = new ArrayList<String>();
- derivedFrom.add(derived.getToscaResourceName());
- String vendorName = "ATT Tosca";
- String vendorRelease = "1.0.0.wd03";
- String icon = "defaulticon";
- ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, null, derivedFrom, vendorName, vendorRelease, contactId, icon);
- resourceDetails.addCategoryChain(category.getCategory(), category.getSubCategory());
-
- return resourceDetails;
-
- }
-
- public static ResourceReqDetails getDefaultResourceByType(String resourceName, NormativeTypesEnum derived, ResourceCategoryEnum category, String contactId, ResourceTypeEnum resourceType) {
- return getDefaultResourceByType(resourceName, derived, category, contactId, resourceType.toString());
- }
-
- // New
- public static ResourceReqDetails getDefaultResourceByType(String resourceName, NormativeTypesEnum derived, ResourceCategoryEnum category, String contactId, String resourceType) {
- resourceName = (resourceName + resourceType + generateUUIDforSufix());
- String description = "Represents a generic software component that can be managed and run by a Compute Node Type.";
- ArrayList<String> resourceTags = new ArrayList<String>();
- resourceTags.add(resourceName);
- ArrayList<String> derivedFrom = null;
- if (derived != null) {
- derivedFrom = new ArrayList<String>();
- derivedFrom.add(derived.normativeName);
- }
- String vendorName = "ATT Tosca";
- String vendorRelease = "1.0.0.wd03";
- String icon = "defaulticon";
- ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, null, derivedFrom, vendorName, vendorRelease, contactId, icon, resourceType.toString());
- resourceDetails.addCategoryChain(category.getCategory(), category.getSubCategory());
- return resourceDetails;
- }
-
- public static ResourceExternalReqDetails getDefaultResourceByType(String resourceName, ResourceCategoryEnum category, String contactId, String resourceType) {
- resourceName = (resourceName + resourceType + generateUUIDforSufix());
- String description = "Represents a generic software component that can be managed and run by a Compute Node Type.";
- ArrayList<String> resourceTags = new ArrayList<String>();
- resourceTags.add(resourceName);
- String vendorName = "ATT Tosca";
- String vendorRelease = "1.0.0.wd03";
- String icon = "defaulticon";
- ResourceExternalReqDetails resourceDetails = new ResourceExternalReqDetails(resourceName, description, resourceTags,
- vendorName, vendorRelease, contactId, icon,
- resourceType.toString(), category.getCategory(), category.getSubCategory());
- return resourceDetails;
- }
-
- // New
- public static ImportReqDetails getDefaultImportResourceByType(String resourceName, NormativeTypesEnum derived, ResourceCategoryEnum category, String contactId, String resourceType) {
- resourceName = (resourceName + resourceType + generateUUIDforSufix());
- String description = "Represents a generic software component that can be managed and run by a Compute Node Type.";
- ArrayList<String> resourceTags = new ArrayList<String>();
- resourceTags.add(resourceName);
- ArrayList<String> derivedFrom = null;
- if (derived != null) {
- derivedFrom = new ArrayList<String>();
- derivedFrom.add(derived.normativeName);
- }
- String vendorName = "SDC Tosca";
- String vendorRelease = "1.0.0.wd03";
- String icon = "defaulticon";
- ImportReqDetails resourceDetails = new ImportReqDetails(resourceName, description, resourceTags, derivedFrom, vendorName, vendorRelease, contactId, icon);
- resourceDetails.addCategoryChain(category.getCategory(), category.getSubCategory());
- return resourceDetails;
- }
- ////
-
- public static ImportReqDetails getDefaultImportResource(ResourceReqDetails resourceReqDetails) {
- ImportReqDetails importReqDetails = new ImportReqDetails(resourceReqDetails.getName(), resourceReqDetails.getDescription(), resourceReqDetails.getTags(), resourceReqDetails.getDerivedFrom(), resourceReqDetails.getVendorName(),
- resourceReqDetails.getVendorRelease(), resourceReqDetails.getContactId(), resourceReqDetails.getIcon());
- importReqDetails.setPayloadName("ciMyCompute.yaml");
- importReqDetails.setCategories(resourceReqDetails.getCategories());
- importReqDetails.setPayloadData(
- "dG9zY2FfZGVmaW5pdGlvbnNfdmVyc2lvbjogdG9zY2Ffc2ltcGxlX3lhbWxfMV8wXzANCm5vZGVfdHlwZXM6IA0KICBvcmcub3BlbmVjb21wLnJlc291cmNlLk15Q29tcHV0ZToNCiAgICBkZXJpdmVkX2Zyb206IHRvc2NhLm5vZGVzLlJvb3QNCiAgICBhdHRyaWJ1dGVzOg0KICAgICAgcHJpdmF0ZV9hZGRyZXNzOg0KICAgICAgICB0eXBlOiBzdHJpbmcNCiAgICAgIHB1YmxpY19hZGRyZXNzOg0KICAgICAgICB0eXBlOiBzdHJpbmcNCiAgICAgIG5ldHdvcmtzOg0KICAgICAgICB0eXBlOiBtYXANCiAgICAgICAgZW50cnlfc2NoZW1hOg0KICAgICAgICAgIHR5cGU6IHRvc2NhLmRhdGF0eXBlcy5uZXR3b3JrLk5ldHdvcmtJbmZvDQogICAgICBwb3J0czoNCiAgICAgICAgdHlwZTogbWFwDQogICAgICAgIGVudHJ5X3NjaGVtYToNCiAgICAgICAgICB0eXBlOiB0b3NjYS5kYXRhdHlwZXMubmV0d29yay5Qb3J0SW5mbw0KICAgIHJlcXVpcmVtZW50czoNCiAgICAgIC0gbG9jYWxfc3RvcmFnZTogDQogICAgICAgICAgY2FwYWJpbGl0eTogdG9zY2EuY2FwYWJpbGl0aWVzLkF0dGFjaG1lbnQNCiAgICAgICAgICBub2RlOiB0b3NjYS5ub2Rlcy5CbG9ja1N0b3JhZ2UNCiAgICAgICAgICByZWxhdGlvbnNoaXA6IHRvc2NhLnJlbGF0aW9uc2hpcHMuQXR0YWNoZXNUbw0KICAgICAgICAgIG9jY3VycmVuY2VzOiBbMCwgVU5CT1VOREVEXSAgDQogICAgY2FwYWJpbGl0aWVzOg0KICAgICAgaG9zdDogDQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5Db250YWluZXINCiAgICAgICAgdmFsaWRfc291cmNlX3R5cGVzOiBbdG9zY2Eubm9kZXMuU29mdHdhcmVDb21wb25lbnRdIA0KICAgICAgZW5kcG9pbnQgOg0KICAgICAgICB0eXBlOiB0b3NjYS5jYXBhYmlsaXRpZXMuRW5kcG9pbnQuQWRtaW4gDQogICAgICBvczogDQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5PcGVyYXRpbmdTeXN0ZW0NCiAgICAgIHNjYWxhYmxlOg0KICAgICAgICB0eXBlOiB0b3NjYS5jYXBhYmlsaXRpZXMuU2NhbGFibGUNCiAgICAgIGJpbmRpbmc6DQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5uZXR3b3JrLkJpbmRhYmxlDQo=");
- return importReqDetails;
- }
-
- public static ImportReqDetails getDefaultImportResource() {
- ResourceReqDetails resourceReqDetails = getDefaultResource();
- ImportReqDetails importReqDetails = new ImportReqDetails(resourceReqDetails.getName(), resourceReqDetails.getDescription(), resourceReqDetails.getTags(), resourceReqDetails.getDerivedFrom(), resourceReqDetails.getVendorName(),
- resourceReqDetails.getVendorRelease(), resourceReqDetails.getContactId(), resourceReqDetails.getIcon());
- importReqDetails.setPayloadName("ciMyCompute.yaml");
- importReqDetails.setCategories(resourceReqDetails.getCategories());
- importReqDetails.setPayloadData(
- "dG9zY2FfZGVmaW5pdGlvbnNfdmVyc2lvbjogdG9zY2Ffc2ltcGxlX3lhbWxfMV8wXzANCm5vZGVfdHlwZXM6IA0KICBvcmcub3BlbmVjb21wLnJlc291cmNlLk15Q29tcHV0ZToNCiAgICBkZXJpdmVkX2Zyb206IHRvc2NhLm5vZGVzLlJvb3QNCiAgICBhdHRyaWJ1dGVzOg0KICAgICAgcHJpdmF0ZV9hZGRyZXNzOg0KICAgICAgICB0eXBlOiBzdHJpbmcNCiAgICAgIHB1YmxpY19hZGRyZXNzOg0KICAgICAgICB0eXBlOiBzdHJpbmcNCiAgICAgIG5ldHdvcmtzOg0KICAgICAgICB0eXBlOiBtYXANCiAgICAgICAgZW50cnlfc2NoZW1hOg0KICAgICAgICAgIHR5cGU6IHRvc2NhLmRhdGF0eXBlcy5uZXR3b3JrLk5ldHdvcmtJbmZvDQogICAgICBwb3J0czoNCiAgICAgICAgdHlwZTogbWFwDQogICAgICAgIGVudHJ5X3NjaGVtYToNCiAgICAgICAgICB0eXBlOiB0b3NjYS5kYXRhdHlwZXMubmV0d29yay5Qb3J0SW5mbw0KICAgIHJlcXVpcmVtZW50czoNCiAgICAgIC0gbG9jYWxfc3RvcmFnZTogDQogICAgICAgICAgY2FwYWJpbGl0eTogdG9zY2EuY2FwYWJpbGl0aWVzLkF0dGFjaG1lbnQNCiAgICAgICAgICBub2RlOiB0b3NjYS5ub2Rlcy5CbG9ja1N0b3JhZ2UNCiAgICAgICAgICByZWxhdGlvbnNoaXA6IHRvc2NhLnJlbGF0aW9uc2hpcHMuQXR0YWNoZXNUbw0KICAgICAgICAgIG9jY3VycmVuY2VzOiBbMCwgVU5CT1VOREVEXSAgDQogICAgY2FwYWJpbGl0aWVzOg0KICAgICAgaG9zdDogDQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5Db250YWluZXINCiAgICAgICAgdmFsaWRfc291cmNlX3R5cGVzOiBbdG9zY2Eubm9kZXMuU29mdHdhcmVDb21wb25lbnRdIA0KICAgICAgZW5kcG9pbnQgOg0KICAgICAgICB0eXBlOiB0b3NjYS5jYXBhYmlsaXRpZXMuRW5kcG9pbnQuQWRtaW4gDQogICAgICBvczogDQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5PcGVyYXRpbmdTeXN0ZW0NCiAgICAgIHNjYWxhYmxlOg0KICAgICAgICB0eXBlOiB0b3NjYS5jYXBhYmlsaXRpZXMuU2NhbGFibGUNCiAgICAgIGJpbmRpbmc6DQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5uZXR3b3JrLkJpbmRhYmxlDQo=");
- return importReqDetails;
- }
-
- public static ImportReqDetails getDefaultImportResource(String name) {
- ResourceReqDetails resourceReqDetails = getDefaultResourceByType(ResourceTypeEnum.VFC, name);
- ImportReqDetails importReqDetails = new ImportReqDetails(resourceReqDetails.getName(), resourceReqDetails.getDescription(), resourceReqDetails.getTags(), resourceReqDetails.getDerivedFrom(), resourceReqDetails.getVendorName(),
- resourceReqDetails.getVendorRelease(), resourceReqDetails.getContactId(), resourceReqDetails.getIcon());
- importReqDetails.setPayloadName("ciMyCompute.yaml");
- importReqDetails.setCategories(resourceReqDetails.getCategories());
- importReqDetails.setPayloadData(
- "dG9zY2FfZGVmaW5pdGlvbnNfdmVyc2lvbjogdG9zY2Ffc2ltcGxlX3lhbWxfMV8wXzANCm5vZGVfdHlwZXM6IA0KICBvcmcub3BlbmVjb21wLnJlc291cmNlLk15Q29tcHV0ZToNCiAgICBkZXJpdmVkX2Zyb206IHRvc2NhLm5vZGVzLlJvb3QNCiAgICBhdHRyaWJ1dGVzOg0KICAgICAgcHJpdmF0ZV9hZGRyZXNzOg0KICAgICAgICB0eXBlOiBzdHJpbmcNCiAgICAgIHB1YmxpY19hZGRyZXNzOg0KICAgICAgICB0eXBlOiBzdHJpbmcNCiAgICAgIG5ldHdvcmtzOg0KICAgICAgICB0eXBlOiBtYXANCiAgICAgICAgZW50cnlfc2NoZW1hOg0KICAgICAgICAgIHR5cGU6IHRvc2NhLmRhdGF0eXBlcy5uZXR3b3JrLk5ldHdvcmtJbmZvDQogICAgICBwb3J0czoNCiAgICAgICAgdHlwZTogbWFwDQogICAgICAgIGVudHJ5X3NjaGVtYToNCiAgICAgICAgICB0eXBlOiB0b3NjYS5kYXRhdHlwZXMubmV0d29yay5Qb3J0SW5mbw0KICAgIHJlcXVpcmVtZW50czoNCiAgICAgIC0gbG9jYWxfc3RvcmFnZTogDQogICAgICAgICAgY2FwYWJpbGl0eTogdG9zY2EuY2FwYWJpbGl0aWVzLkF0dGFjaG1lbnQNCiAgICAgICAgICBub2RlOiB0b3NjYS5ub2Rlcy5CbG9ja1N0b3JhZ2UNCiAgICAgICAgICByZWxhdGlvbnNoaXA6IHRvc2NhLnJlbGF0aW9uc2hpcHMuQXR0YWNoZXNUbw0KICAgICAgICAgIG9jY3VycmVuY2VzOiBbMCwgVU5CT1VOREVEXSAgDQogICAgY2FwYWJpbGl0aWVzOg0KICAgICAgaG9zdDogDQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5Db250YWluZXINCiAgICAgICAgdmFsaWRfc291cmNlX3R5cGVzOiBbdG9zY2Eubm9kZXMuU29mdHdhcmVDb21wb25lbnRdIA0KICAgICAgZW5kcG9pbnQgOg0KICAgICAgICB0eXBlOiB0b3NjYS5jYXBhYmlsaXRpZXMuRW5kcG9pbnQuQWRtaW4gDQogICAgICBvczogDQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5PcGVyYXRpbmdTeXN0ZW0NCiAgICAgIHNjYWxhYmxlOg0KICAgICAgICB0eXBlOiB0b3NjYS5jYXBhYmlsaXRpZXMuU2NhbGFibGUNCiAgICAgIGJpbmRpbmc6DQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5uZXR3b3JrLkJpbmRhYmxlDQo=");
- return importReqDetails;
- }
-
- // *** SERVICE ***
- public static ServiceReqDetails getDefaultService() {
- return getDefaultService("ciService", ServiceCategoriesEnum.MOBILITY, "al1976");
- }
-
- public static ServiceReqDetails getDefaultService(String contactId) {
- return getDefaultService("ciService", ServiceCategoriesEnum.MOBILITY, contactId);
- }
-
- public static ServiceReqDetails getDefaultService(User user) {
- return getDefaultService("ciService", ServiceCategoriesEnum.MOBILITY, user.getUserId());
- }
-
- public static ServiceReqDetails getService(ServiceCategoriesEnum category) {
- return getDefaultService("ciService", category, "al1976");
- }
-
- public static ServiceReqDetails getDefaultService(ServiceCategoriesEnum category, User user) {
- return getDefaultService("ciService", category, user.getUserId());
- }
-
- public static ServiceReqDetails getDefaultService(String serviceName, ServiceCategoriesEnum category, String contactId) {
- serviceName = (serviceName + generateUUIDforSufix());
- ArrayList<String> tags = new ArrayList<String>();
- tags.add("serviceTag");
- tags.add("serviceTag1");
- tags.add(serviceName);
- String description = "service Description";
- String icon = "myIcon";
-
- ServiceReqDetails serviceDetails = new ServiceReqDetails(serviceName, category.getValue(), tags, description, contactId, icon);
-
- return serviceDetails;
- }
-
- // ***** PROPERTY ***
-
- public static PropertyReqDetails getDefaultProperty() {
- return getDefaultProperty("disk_size");
- }
-
- public static PropertyReqDetails getDefaultProperty(String propertyName) {
- PropertyReqDetails property = new PropertyReqDetails();
- property.setName(propertyName);
- property.setPropertyType("integer");
- property.setPropertyRequired(false);
- property.setPropertyDefaultValue("12345");
- property.setPropertyDescription("test property");
- property.setPropertyRangeMax("500");
- property.setPropertyRangeMin("100");
- property.setPropertyPassword(false);
- return property;
- }
-
- public static PropertyReqDetails getDefaultIntegerProperty() {
- return getPropertyDetails(PropertyTypeEnum.INTEGER);
- }
-
- public static PropertyReqDetails getDefaultStringProperty() {
- return getPropertyDetails(PropertyTypeEnum.STRING);
- }
-
- public static PropertyReqDetails getDefaultBooleanProperty() {
- return getPropertyDetails(PropertyTypeEnum.BOOLEAN);
- }
-
- public static PropertyReqDetails getDefaultListProperty() {
- return getPropertyDetails(PropertyTypeEnum.STRING_LIST);
- }
-
- public static PropertyReqDetails getDefaultListProperty(PropertyTypeEnum innerType) {
- return getPropertyDetails(innerType);
- }
-
- public static PropertyReqDetails getPropertyDetails(PropertyTypeEnum propType) {
- return new PropertyReqDetails(propType.getName(), propType.getType(), propType.getValue(), propType.getDescription(), propType.getSchemaDefinition());
- }
-
- // ***** RESOURCE INSTANCE ***
- public static ComponentInstanceReqDetails getDefaultComponentInstance() {
- return getDefaultComponentInstance("resourceInstanceName");
- }
-
- public static ComponentInstanceReqDetails getDefaultComponentInstance(String name) {
- String resourceUid = "resourceId";
- ComponentInstanceReqDetails resourceInstanceDetails = new ComponentInstanceReqDetails(resourceUid, RESOURCE_INSTANCE_DESCRIPTION, RESOURCE_INSTANCE_POS_X, RESOURCE_INSTANCE_POS_Y, name);
-
- return resourceInstanceDetails;
-
- }
-
- public static ComponentInstanceReqDetails getDefaultComponentInstance(String name, ComponentReqDetails componentReqDetails) {
- String resourceUid = componentReqDetails.getUniqueId();
- ComponentInstanceReqDetails resourceInstanceDetails = new ComponentInstanceReqDetails(resourceUid, RESOURCE_INSTANCE_DESCRIPTION, RESOURCE_INSTANCE_POS_X, RESOURCE_INSTANCE_POS_Y, name);
-
- return resourceInstanceDetails;
-
- }
-
- public static ComponentInstanceReqDetails getComponentResourceInstance(ComponentReqDetails compInstOriginDetails) {
- String compInstName = (compInstOriginDetails.getName() != null ? compInstOriginDetails.getName() : "resourceInstanceName");
- String resourceUid = compInstOriginDetails.getUniqueId();
- ComponentInstanceReqDetails resourceInstanceDetails = new ComponentInstanceReqDetails(resourceUid, RESOURCE_INSTANCE_DESCRIPTION, RESOURCE_INSTANCE_POS_X, RESOURCE_INSTANCE_POS_Y, compInstName);
- return resourceInstanceDetails;
-
- }
-
- public static ComponentInstanceReqDetails getComponentInstance(Component compInstOriginDetails) {
- String compInstName = (compInstOriginDetails.getName() != null ? compInstOriginDetails.getName() : "componentInstanceName");
- String compInsUid = compInstOriginDetails.getUniqueId();
- ComponentInstanceReqDetails componentInstanceDetails = new ComponentInstanceReqDetails(compInsUid, RESOURCE_INSTANCE_DESCRIPTION, RESOURCE_INSTANCE_POS_X, RESOURCE_INSTANCE_POS_Y, compInstName);
- return componentInstanceDetails;
-
- }
-
- // ******* USER **********************
- public static User getDefaultUser(UserRoleEnum userRole) {
- User sdncModifierDetails = new User();
- sdncModifierDetails.setUserId(userRole.getUserId());
- sdncModifierDetails.setFirstName(userRole.getFirstName());
- sdncModifierDetails.setLastName(userRole.getLastName());
- return sdncModifierDetails;
- }
-
- public static User getDefaultMechUser() {
- User sdncMechUserDetails = new User();
- sdncMechUserDetails.setUserId("m12345");
- sdncMechUserDetails.setFirstName("Shay");
- sdncMechUserDetails.setLastName("Sponder");
- sdncMechUserDetails.setEmail("mechId@intl.sdc.com");
- sdncMechUserDetails.setRole("DESIGNER");
- return sdncMechUserDetails;
- }
-
- // ******* CONSUMER **********************
-
- public static ConsumerDataDefinition getDefaultConsumerDetails() {
- ConsumerDataDefinition consumer = new ConsumerDataDefinition();
- consumer.setConsumerName("ci");
- consumer.setConsumerSalt("2a1f887d607d4515d4066fe0f5452a50");
- consumer.setConsumerPassword("0a0dc557c3bf594b1a48030e3e99227580168b21f44e285c69740b8d5b13e33b");
- return consumer;
- }
-
- // *** ARTIFACT ***
- public static ArtifactReqDetails getDefaultArtifact() throws IOException, Exception {
- return getDefaultArtifact(DEFAULT_ARTIFACT_LABEL);
- }
-
- public static ArtifactReqDetails getDefaultArtifact(String artifactLabel) throws IOException, Exception {
- List<String> artifactTypes = ResponseParser.getValuesFromJsonArray(ArtifactRestUtils.getArtifactTypesList());
- String artifactType = artifactTypes.get(0);
-
- return getDefaultArtifact(artifactLabel, artifactType);
- }
-
- public static ArtifactReqDetails getDefaultArtifact(String artifactLabel, String artifactType) throws IOException, Exception {
-
- String artifactName = "testArtifact.sh";
- String artifactDescription = "descriptionTest";
- String payloadData = "dGVzdA=="; // content of file
-
- ArtifactReqDetails artifactDetails = new ArtifactReqDetails(artifactName, artifactType, artifactDescription, payloadData, artifactLabel);
- artifactDetails.setUrl("");
- artifactDetails.setArtifactDisplayName(artifactLabel);
- return artifactDetails;
- }
-
- public static ArtifactReqDetails getServiceApiArtifactDetails(String artifactLabel) throws IOException, Exception {
- ArtifactReqDetails defaultArtifact = getDefaultArtifact(artifactLabel, "OTHER");
- defaultArtifact.setUrl("http://www.apple.com");
- defaultArtifact.setServiceApi(true);
- defaultArtifact.setArtifactDisplayName(StringUtils.capitalize(defaultArtifact.getArtifactLabel()));
- return defaultArtifact;
- }
-
- public static ArtifactReqDetails getDefaultDeploymentArtifactForType(String artifactType) throws IOException, Exception {
- return getArtifactByType(DEFAULT_ARTIFACT_LABEL, artifactType, true, false);
- }
-
- public static ArtifactReqDetails getArtifactByType(ArtifactTypeEnum artifactLabel, ArtifactTypeEnum artifactType, Boolean deploymentTrue) throws IOException, Exception {
- return getArtifactByType(DEFAULT_ARTIFACT_LABEL, artifactType.toString(), deploymentTrue, false);
-
- }
-
- public static ArtifactReqDetails getArtifactByType(String artifactLabel, String artifactType, Boolean deploymentTrue, Boolean updatedPayload) throws IOException, Exception {
- String artifactName;
- String updatedPayloadData =null;
- String payloadData = null;
- Integer timeout = null;
- String url = "";
- String artifactDescription = "descriptionTest";
-
- // PLEASE NOTE!!!
- // The non-default payloads here are real ones according to various
- // types validations,
- // Please don't change them unless you know what you are doing!
-
- ArtifactTypeEnum artifactTypeEnum = ArtifactTypeEnum.findType(artifactType);
-
- /*
- * Missing file type: DCAE_JSON
- */
- switch (artifactTypeEnum) {
- case DCAE_INVENTORY_TOSCA:
- case DCAE_EVENT:
- case APPC_CONFIG:
- case DCAE_DOC:
- case DCAE_TOSCA:
- case HEAT:
- case HEAT_NET:
- case HEAT_VOL: {
- artifactName = generateUUIDforSufix() + artifactType + "_install_apache2.yaml";
- payloadData = "aGVhdF90ZW1wbGF0ZV92ZXJzaW9uOiAyMDEzLTA1LTIzDQoNCmRlc2NyaXB0aW9uOiBTaW1wbGUgdGVtcGxhdGUgdG8gZGVwbG95IGEgc3RhY2sgd2l0aCB0d28gdmlydHVhbCBtYWNoaW5lIGluc3RhbmNlcw0KDQpwYXJhbWV0ZXJzOg0KICBpbWFnZV9uYW1lXzE6DQogICAgdHlwZTogc3RyaW5nDQogICAgbGFiZWw6IEltYWdlIE5hbWUNCiAgICBkZXNjcmlwdGlvbjogU0NPSU1BR0UgU3BlY2lmeSBhbiBpbWFnZSBuYW1lIGZvciBpbnN0YW5jZTENCiAgICBkZWZhdWx0OiBjaXJyb3MtMC4zLjEteDg2XzY0DQogIGltYWdlX25hbWVfMjoNCiAgICB0eXBlOiBzdHJpbmcNCiAgICBsYWJlbDogSW1hZ2UgTmFtZQ0KICAgIGRlc2NyaXB0aW9uOiBTQ09JTUFHRSBTcGVjaWZ5IGFuIGltYWdlIG5hbWUgZm9yIGluc3RhbmNlMg0KICAgIGRlZmF1bHQ6IGNpcnJvcy0wLjMuMS14ODZfNjQNCiAgbmV0d29ya19pZDoNCiAgICB0eXBlOiBzdHJpbmcNCiAgICBsYWJlbDogTmV0d29yayBJRA0KICAgIGRlc2NyaXB0aW9uOiBTQ09ORVRXT1JLIE5ldHdvcmsgdG8gYmUgdXNlZCBmb3IgdGhlIGNvbXB1dGUgaW5zdGFuY2UNCiAgICBoaWRkZW46IHRydWUNCiAgICBjb25zdHJhaW50czoNCiAgICAgIC0gbGVuZ3RoOiB7IG1pbjogNiwgbWF4OiA4IH0NCiAgICAgICAgZGVzY3JpcHRpb246IFBhc3N3b3JkIGxlbmd0aCBtdXN0IGJlIGJldHdlZW4gNiBhbmQgOCBjaGFyYWN0ZXJzLg0KICAgICAgLSByYW5nZTogeyBtaW46IDYsIG1heDogOCB9DQogICAgICAgIGRlc2NyaXB0aW9uOiBSYW5nZSBkZXNjcmlwdGlvbg0KICAgICAgLSBhbGxvd2VkX3ZhbHVlczoNCiAgICAgICAgLSBtMS5zbWFsbA0KICAgICAgICAtIG0xLm1lZGl1bQ0KICAgICAgICAtIG0xLmxhcmdlDQogICAgICAgIGRlc2NyaXB0aW9uOiBBbGxvd2VkIHZhbHVlcyBkZXNjcmlwdGlvbg0KICAgICAgLSBhbGxvd2VkX3BhdHRlcm46ICJbYS16QS1aMC05XSsiDQogICAgICAgIGRlc2NyaXB0aW9uOiBQYXNzd29yZCBtdXN0IGNvbnNpc3Qgb2YgY2hhcmFjdGVycyBhbmQgbnVtYmVycyBvbmx5Lg0KICAgICAgLSBhbGxvd2VkX3BhdHRlcm46ICJbQS1aXStbYS16QS1aMC05XSoiDQogICAgICAgIGRlc2NyaXB0aW9uOiBQYXNzd29yZCBtdXN0IHN0YXJ0IHdpdGggYW4gdXBwZXJjYXNlIGNoYXJhY3Rlci4NCiAgICAgIC0gY3VzdG9tX2NvbnN0cmFpbnQ6IG5vdmEua2V5cGFpcg0KICAgICAgICBkZXNjcmlwdGlvbjogQ3VzdG9tIGRlc2NyaXB0aW9uDQoNCnJlc291cmNlczoNCiAgbXlfaW5zdGFuY2UxOg0KICAgIHR5cGU6IE9TOjpOb3ZhOjpTZXJ2ZXINCiAgICBwcm9wZXJ0aWVzOg0KICAgICAgaW1hZ2U6IHsgZ2V0X3BhcmFtOiBpbWFnZV9uYW1lXzEgfQ0KICAgICAgZmxhdm9yOiBtMS5zbWFsbA0KICAgICAgbmV0d29ya3M6DQogICAgICAgIC0gbmV0d29yayA6IHsgZ2V0X3BhcmFtIDogbmV0d29ya19pZCB9DQogIG15X2luc3RhbmNlMjoNCiAgICB0eXBlOiBPUzo6Tm92YTo6U2VydmVyDQogICAgcHJvcGVydGllczoNCiAgICAgIGltYWdlOiB7IGdldF9wYXJhbTogaW1hZ2VfbmFtZV8yIH0NCiAgICAgIGZsYXZvcjogbTEudGlueQ0KICAgICAgbmV0d29ya3M6DQogICAgICAgIC0gbmV0d29yayA6IHsgZ2V0X3BhcmFtIDogbmV0d29ya19pZCB9";
- updatedPayloadData = "dG9zY2FfZGVmaW5pdGlvbnNfdmVyc2lvbjogdG9zY2Ffc2ltcGxlX3lhbWxfMV8wXzANCg0Kbm9kZV90eXBlczoNCiAgY29tLmF0dC5kMi5yZXNvdXJjZS5jcC5DUDoNCiAgICBkZXJpdmVkX2Zyb206IHRvc2NhLm5vZGVzLm5ldHdvcmsuUG9ydA0KICAgIHByb3BlcnRpZXM6DQogICAgICBpc190YWdnZWQ6DQogICAgICAgIHR5cGU6IGJvb2xlYW4NCiAgICAgICAgcmVxdWlyZWQ6IGZhbHNlDQogICAgICAgIGRlZmF1bHQ6IGZhbHNlDQogICAgICAgIGRlc2NyaXB0aW9uOiANCg0KICAgIHJlcXVpcmVtZW50czoNCiAgICAgIC0gdmlydHVhbExpbms6DQogICAgICAgICAgY2FwYWJpbGl0eTogdG9zY2EuY2FwYWJpbGl0aWVzLm5ldHdvcmsuTGlua2FibGUNCiAgICAgICAgICByZWxhdGlvbnNoaXA6IHRvc2NhLnJlbGF0aW9uc2hpcHMubmV0d29yay5MaW5rc1RvDQogICAgICAtIHZpcnR1YWxCaW5kaW5nOg0KICAgICAgICAgIGNhcGFiaWxpdHk6IHRvc2NhLmNhcGFiaWxpdGllcy5uZXR3b3JrLkJpbmRhYmxlDQogICAgICAgICAgcmVsYXRpb25zaGlwOiB0b3NjYS5yZWxhdGlvbnNoaXBzLm5ldHdvcmsuQmluZHNUbw0KICAgIGNhcGFiaWxpdGllczoNCiAgICAgIGF0dGFjaG1lbnQ6DQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5BdHRhY2htZW50DQogICAgICAgIG9jY3VycmVuY2VzOg0KICAgICAgICAtIDENCiAgICAgICAgLSBVTkJPVU5ERUQNCiAgICAgICAgdHlwZTogdG9zY2EuY2FwYWJpbGl0aWVzLm5ldHdvcmsuQmluZGFibGUNCiAgICAgICAgb2NjdXJyZW5jZXM6DQogICAgICAgIC0gMQ0KICAgICAgICAtIFVOQk9VTkRFRA0KICAgICAgdmlydHVhbF9saW5rYWJsZToNCiAgICAgICAgdHlwZTogY29tLmF0dC5kMi5jYXBhYmlsaXRpZXMuTWV0cmljDQogICAgICBlbmRfcG9pbnQ6DQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5FbmRwb2ludCAgICAgICA=";
- timeout = 60;
- artifactLabel = normalizeArtifactLabel(artifactName);
- break;
- }
- case DCAE_INVENTORY_POLICY:
- case DCAE_INVENTORY_BLUEPRINT:
- case DCAE_INVENTORY_EVENT: {
- artifactName = getDcaeArtifactName(artifactTypeEnum, artifactType);
- payloadData = "will be override later";
- updatedPayloadData = "override";
- timeout = 60;
- artifactLabel = normalizeArtifactLabel(artifactName);
- break;
- }
- case MURANO_PKG: {
- artifactName = artifactType + "org.openstack.Rally.zip";
- payloadData = "ODM4MTRjNzkxZjcwYTlkMjk4ZGQ2ODE4MThmNjg0N2Y=";
- updatedPayloadData = "ODM4MTRjNzkxZjcwYTlkMjk4ZGQ2ODE4MThmMTAwN2Y=";
- break;
- }
- case DCAE_POLICY: {
- artifactName = artifactType + "dcae_policy.emf";
- payloadData = "will be override later";
- updatedPayloadData = "override";
- break;
- }
- case DCAE_INVENTORY_JSON:
- case DCAE_JSON: {
- artifactName = artifactType + "dcae_policy.json";
- payloadData = "ew0KICAiYXJ0aWZhY3RzIjogImRmc2FmIiwNCiAgIm5vcm1hbGl6ZWROYW1lIjogImNpc2VydmljZTBiYzY5ODk2OTQ4ZiIsDQogICJzeXN0ZW1OYW1lIjogIkNpc2VydmljZTBiYzY5ODk2OTQ4ZiIsDQogICJpbnZhcmlhbnRVVUlEIjogIjEzZmJkNzI3LWRjNzUtNDU1OS1iNzEyLWUwMjc5YmY4YTg2MSIsDQogICJhdHRDb250YWN0IjogImNzMDAwOCIsDQogICJuYW1lIjogImNpU2VydmljZTBiYzY5ODk2OTQ4ZiINCn0=";
- updatedPayloadData = "ew0KICAiYXJ0aWZhY3RzIjogIjEyMzQzIiwNCiAgIm5vcm1hbGl6ZWROYW1lIjogIjU0MzUzNCIsDQogICJzeXN0ZW1OYW1lIjogIkNpc2VydmljZTBiYzY5ODk2OTQ4ZiIsDQogICJpbnZhcmlhbnRVVUlEIjogIjEzZmJkNzI3LWRjNzUtNDU1OS1iNzEyLWUwMjc5YmY4YTg2MSIsDQogICJhdHRDb250YWN0IjogImNzMDAwOCIsDQogICJuYW1lIjogImNpU2VydmljZTBiYzY5ODk2OTQ4ZiINCn0=";
- break;
- }
- case PUPPET:
- case CHEF:
- case DG_XML:
- case YANG: {
- artifactName = generateUUIDforSufix() + artifactType + "yangXml.xml";
- payloadData = "PD94bWwgdmVyc2lvbj0iMS4wIj8+DQo8ZGF0YT4NCiAgPHNwb3J0cz4NCiAgICA8cGVyc29uPg0KICAgICAgPG5hbWU+TGlvbmVsIEFuZHJlcyBNZXNzaTwvbmFtZT4NCiAgICAgIDxiaXJ0aGRheT4xOTg3LTA2LTI0VDAwOjAwOjAwLTAwOjAwPC9iaXJ0aGRheT4NCiAgICA8L3BlcnNvbj4NCiAgICA8cGVyc29uPg0KICAgICAgPG5hbWU+Q3Jpc3RpYW5vIFJvbmFsZG88L25hbWU+DQogICAgICA8YmlydGhkYXk+MTk4NS0wMi0wNVQwMDowMDowMC0wMDowMDwvYmlydGhkYXk+DQogICAgPC9wZXJzb24+DQogICAgPHRlYW0+DQogICAgICA8bmFtZT5GQyBCYXJjZWxvbmE8L25hbWU+DQogICAgICA8cGxheWVyPg0KICAgICAgICA8bmFtZT5MaW9uZWwgQW5kcmVzIE1lc3NpPC9uYW1lPg0KICAgICAgICA8c2Vhc29uPkNoYW1waW9ucyBMZWFndWUgMjAxNC0yMDE1PC9zZWFzb24+DQogICAgICAgIDxudW1iZXI+MTA8L251bWJlcj4NCiAgICAgICAgPHNjb3Jlcz40Mzwvc2NvcmVzPg0KICAgICAgPC9wbGF5ZXI+DQogICAgPC90ZWFtPg0KICAgIDx0ZWFtPg0KICAgICAgPG5hbWU+UmVhbCBNYWRyaWQ8L25hbWU+DQogICAgICA8cGxheWVyPg0KICAgICAgICA8bmFtZT5DcmlzdGlhbm8gUm9uYWxkbzwvbmFtZT4NCiAgICAgICAgPHNlYXNvbj5DaGFtcGlvbnMgTGVhZ3VlIDIwMTQtMjAxNTwvc2Vhc29uPg0KICAgICAgICA8bnVtYmVyPjc8L251bWJlcj4NCiAgICAgICAgPHNjb3Jlcz40ODwvc2NvcmVzPg0KICAgICAgPC9wbGF5ZXI+DQogICAgPC90ZWFtPg0KICA8L3Nwb3J0cz4NCg0KPC9kYXRhPg==";
- updatedPayloadData = "PD94bWwgdmVyc2lvbj0iMS4wIj8+DQo8ZGF0YT4NCiAgPHNwb3J0cz4NCiAgICA8cGVyc29uPg0KICAgICAgPG5hbWU+TGlvbmVsIEFuZHJlcyBNZXNzaTwvbmFtZT4NCiAgICAgIDxiaXJ0aGRheT4xOTkwLTA2LTI0VDAwOjAwOjAwLTAwOjExPC9iaXJ0aGRheT4NCiAgICA8L3BlcnNvbj4NCiAgICA8cGVyc29uPg0KICAgICAgPG5hbWU+Q3Jpc3RpYW5vIFJvbmFsZG88L25hbWU+DQogICAgICA8YmlydGhkYXk+MTk4NS0wMi0wNVQwMDowMDowMC0wMDowMDwvYmlydGhkYXk+DQogICAgPC9wZXJzb24+DQogICAgPHRlYW0+DQogICAgICA8bmFtZT5GQyBCYXJjZWxvbmE8L25hbWU+DQogICAgICA8cGxheWVyPg0KICAgICAgICA8bmFtZT5MaW9uZWwgQW5kcmVzIE1lc3NpPC9uYW1lPg0KICAgICAgICA8c2Vhc29uPkNoYW1waW9ucyBMZWFndWUgMjAxNC0yMDE1PC9zZWFzb24+DQogICAgICAgIDxudW1iZXI+MTA8L251bWJlcj4NCiAgICAgICAgPHNjb3Jlcz40Mzwvc2NvcmVzPg0KICAgICAgPC9wbGF5ZXI+DQogICAgPC90ZWFtPg0KICAgIDx0ZWFtPg0KICAgICAgPG5hbWU+UmVhbCBNYWRyaWQ8L25hbWU+DQogICAgICA8cGxheWVyPg0KICAgICAgICA8bmFtZT5DcmlzdGlhbm8gUm9uYWxkbzwvbmFtZT4NCiAgICAgICAgPHNlYXNvbj5DaGFtcGlvbnMgTGVhZ3VlIDIwMTQtMjAxNTwvc2Vhc29uPg0KICAgICAgICA8bnVtYmVyPjc8L251bWJlcj4NCiAgICAgICAgPHNjb3Jlcz40ODwvc2NvcmVzPg0KICAgICAgPC9wbGF5ZXI+DQogICAgPC90ZWFtPg0KICA8L3Nwb3J0cz4NCg0KPC9kYXRhPg==";
- timeout = 15;
- artifactLabel = normalizeArtifactLabel(artifactName);
- break;
- }
- case VF_LICENSE:
- case VENDOR_LICENSE:
- case MODEL_INVENTORY_PROFILE:
- case MODEL_QUERY_SPEC:
- case VNF_CATALOG:
- case YANG_XML: {
- artifactName = generateUUIDforSufix() + artifactType + "yangXml.xml";
- payloadData = "PD94bWwgdmVyc2lvbj0iMS4wIj8+DQo8ZGF0YT4NCiAgPHNwb3J0cz4NCiAgICA8cGVyc29uPg0KICAgICAgPG5hbWU+TGlvbmVsIEFuZHJlcyBNZXNzaTwvbmFtZT4NCiAgICAgIDxiaXJ0aGRheT4xOTg3LTA2LTI0VDAwOjAwOjAwLTAwOjAwPC9iaXJ0aGRheT4NCiAgICA8L3BlcnNvbj4NCiAgICA8cGVyc29uPg0KICAgICAgPG5hbWU+Q3Jpc3RpYW5vIFJvbmFsZG88L25hbWU+DQogICAgICA8YmlydGhkYXk+MTk4NS0wMi0wNVQwMDowMDowMC0wMDowMDwvYmlydGhkYXk+DQogICAgPC9wZXJzb24+DQogICAgPHRlYW0+DQogICAgICA8bmFtZT5GQyBCYXJjZWxvbmE8L25hbWU+DQogICAgICA8cGxheWVyPg0KICAgICAgICA8bmFtZT5MaW9uZWwgQW5kcmVzIE1lc3NpPC9uYW1lPg0KICAgICAgICA8c2Vhc29uPkNoYW1waW9ucyBMZWFndWUgMjAxNC0yMDE1PC9zZWFzb24+DQogICAgICAgIDxudW1iZXI+MTA8L251bWJlcj4NCiAgICAgICAgPHNjb3Jlcz40Mzwvc2NvcmVzPg0KICAgICAgPC9wbGF5ZXI+DQogICAgPC90ZWFtPg0KICAgIDx0ZWFtPg0KICAgICAgPG5hbWU+UmVhbCBNYWRyaWQ8L25hbWU+DQogICAgICA8cGxheWVyPg0KICAgICAgICA8bmFtZT5DcmlzdGlhbm8gUm9uYWxkbzwvbmFtZT4NCiAgICAgICAgPHNlYXNvbj5DaGFtcGlvbnMgTGVhZ3VlIDIwMTQtMjAxNTwvc2Vhc29uPg0KICAgICAgICA8bnVtYmVyPjc8L251bWJlcj4NCiAgICAgICAgPHNjb3Jlcz40ODwvc2NvcmVzPg0KICAgICAgPC9wbGF5ZXI+DQogICAgPC90ZWFtPg0KICA8L3Nwb3J0cz4NCg0KPC9kYXRhPg==";
- updatedPayloadData = "PD94bWwgdmVyc2lvbj0iMS4wIj8+DQo8ZGF0YT4NCiAgPHNwb3J0cz4NCiAgICA8cGVyc29uPg0KICAgICAgPG5hbWU+TGlvbmVsIEFuZHJlcyBNZXNzaTwvbmFtZT4NCiAgICAgIDxiaXJ0aGRheT4xOTkwLTA2LTI0VDAwOjAwOjAwLTAwOjExPC9iaXJ0aGRheT4NCiAgICA8L3BlcnNvbj4NCiAgICA8cGVyc29uPg0KICAgICAgPG5hbWU+Q3Jpc3RpYW5vIFJvbmFsZG88L25hbWU+DQogICAgICA8YmlydGhkYXk+MTk4NS0wMi0wNVQwMDowMDowMC0wMDowMDwvYmlydGhkYXk+DQogICAgPC9wZXJzb24+DQogICAgPHRlYW0+DQogICAgICA8bmFtZT5GQyBCYXJjZWxvbmE8L25hbWU+DQogICAgICA8cGxheWVyPg0KICAgICAgICA8bmFtZT5MaW9uZWwgQW5kcmVzIE1lc3NpPC9uYW1lPg0KICAgICAgICA8c2Vhc29uPkNoYW1waW9ucyBMZWFndWUgMjAxNC0yMDE1PC9zZWFzb24+DQogICAgICAgIDxudW1iZXI+MTA8L251bWJlcj4NCiAgICAgICAgPHNjb3Jlcz40Mzwvc2NvcmVzPg0KICAgICAgPC9wbGF5ZXI+DQogICAgPC90ZWFtPg0KICAgIDx0ZWFtPg0KICAgICAgPG5hbWU+UmVhbCBNYWRyaWQ8L25hbWU+DQogICAgICA8cGxheWVyPg0KICAgICAgICA8bmFtZT5DcmlzdGlhbm8gUm9uYWxkbzwvbmFtZT4NCiAgICAgICAgPHNlYXNvbj5DaGFtcGlvbnMgTGVhZ3VlIDIwMTQtMjAxNTwvc2Vhc29uPg0KICAgICAgICA8bnVtYmVyPjc8L251bWJlcj4NCiAgICAgICAgPHNjb3Jlcz40ODwvc2NvcmVzPg0KICAgICAgPC9wbGF5ZXI+DQogICAgPC90ZWFtPg0KICA8L3Nwb3J0cz4NCg0KPC9kYXRhPg==";
- timeout = 0;
- artifactLabel = normalizeArtifactLabel(artifactName);
- break;
- }
- case SNMP_POLL:
- case SNMP_TRAP:
- case DCAE_INVENTORY_DOC:
- case GUIDE:
- case OTHER: {
- artifactName = generateUUIDforSufix() + artifactType + "other.pdf";
- payloadData = "aGVhdF90ZW1wbGF0ZV92ZXJzaW9uOiAyMDEzLTA1LTIzDQoNCmRlc2NyaXB0aW9uOiBTaW1wbGUgdGVtcGxhdGUgdG8gZGVwbG95IGEgc3RhY2sgd2l0aCB0d28gdmlydHVhbCBtYWNoaW5lIGluc3RhbmNlcw0KDQpwYXJhbWV0ZXJzOg0KICBpbWFnZV9uYW1lXzE6DQogICAgdHlwZTogc3RyaW5nDQogICAgbGFiZWw6IEltYWdlIE5hbWUNCiAgICBkZXNjcmlwdGlvbjogU0NPSU1BR0UgU3BlY2lmeSBhbiBpbWFnZSBuYW1lIGZvciBpbnN0YW5jZTENCiAgICBkZWZhdWx0OiBjaXJyb3MtMC4zLjEteDg2XzY0DQogIGltYWdlX25hbWVfMjoNCiAgICB0eXBlOiBzdHJpbmcNCiAgICBsYWJlbDogSW1hZ2UgTmFtZQ0KICAgIGRlc2NyaXB0aW9uOiBTQ09JTUFHRSBTcGVjaWZ5IGFuIGltYWdlIG5hbWUgZm9yIGluc3RhbmNlMg0KICAgIGRlZmF1bHQ6IGNpcnJvcy0wLjMuMS14ODZfNjQNCiAgbmV0d29ya19pZDoNCiAgICB0eXBlOiBzdHJpbmcNCiAgICBsYWJlbDogTmV0d29yayBJRA0KICAgIGRlc2NyaXB0aW9uOiBTQ09ORVRXT1JLIE5ldHdvcmsgdG8gYmUgdXNlZCBmb3IgdGhlIGNvbXB1dGUgaW5zdGFuY2UNCiAgICBoaWRkZW46IHRydWUNCiAgICBjb25zdHJhaW50czoNCiAgICAgIC0gbGVuZ3RoOiB7IG1pbjogNiwgbWF4OiA4IH0NCiAgICAgICAgZGVzY3JpcHRpb246IFBhc3N3b3JkIGxlbmd0aCBtdXN0IGJlIGJldHdlZW4gNiBhbmQgOCBjaGFyYWN0ZXJzLg0KICAgICAgLSByYW5nZTogeyBtaW46IDYsIG1heDogOCB9DQogICAgICAgIGRlc2NyaXB0aW9uOiBSYW5nZSBkZXNjcmlwdGlvbg0KICAgICAgLSBhbGxvd2VkX3ZhbHVlczoNCiAgICAgICAgLSBtMS5zbWFsbA0KICAgICAgICAtIG0xLm1lZGl1bQ0KICAgICAgICAtIG0xLmxhcmdlDQogICAgICAgIGRlc2NyaXB0aW9uOiBBbGxvd2VkIHZhbHVlcyBkZXNjcmlwdGlvbg0KICAgICAgLSBhbGxvd2VkX3BhdHRlcm46ICJbYS16QS1aMC05XSsiDQogICAgICAgIGRlc2NyaXB0aW9uOiBQYXNzd29yZCBtdXN0IGNvbnNpc3Qgb2YgY2hhcmFjdGVycyBhbmQgbnVtYmVycyBvbmx5Lg0KICAgICAgLSBhbGxvd2VkX3BhdHRlcm46ICJbQS1aXStbYS16QS1aMC05XSoiDQogICAgICAgIGRlc2NyaXB0aW9uOiBQYXNzd29yZCBtdXN0IHN0YXJ0IHdpdGggYW4gdXBwZXJjYXNlIGNoYXJhY3Rlci4NCiAgICAgIC0gY3VzdG9tX2NvbnN0cmFpbnQ6IG5vdmEua2V5cGFpcg0KICAgICAgICBkZXNjcmlwdGlvbjogQ3VzdG9tIGRlc2NyaXB0aW9uDQoNCnJlc291cmNlczoNCiAgbXlfaW5zdGFuY2UxOg0KICAgIHR5cGU6IE9TOjpOb3ZhOjpTZXJ2ZXINCiAgICBwcm9wZXJ0aWVzOg0KICAgICAgaW1hZ2U6IHsgZ2V0X3BhcmFtOiBpbWFnZV9uYW1lXzEgfQ0KICAgICAgZmxhdm9yOiBtMS5zbWFsbA0KICAgICAgbmV0d29ya3M6DQogICAgICAgIC0gbmV0d29yayA6IHsgZ2V0X3BhcmFtIDogbmV0d29ya19pZCB9DQogIG15X2luc3RhbmNlMjoNCiAgICB0eXBlOiBPUzo6Tm92YTo6U2VydmVyDQogICAgcHJvcGVydGllczoNCiAgICAgIGltYWdlOiB7IGdldF9wYXJhbTogaW1hZ2VfbmFtZV8yIH0NCiAgICAgIGZsYXZvcjogbTEudGlueQ0KICAgICAgbmV0d29ya3M6DQogICAgICAgIC0gbmV0d29yayA6IHsgZ2V0X3BhcmFtIDogbmV0d29ya19pZCB9";
- updatedPayloadData = "aGVhdF90ZW1wbGF0ZV92ZXJzaW9uOiAyMDE2LTA1LTIzDQoNCmRlc2NyaXB0aW9uOiBTaW1wbGUgdGVtcGxhdGRzYWRzYWRzYWUgdG8gZGVwbG95IGEgc3RhY2sgd2l0aCB0d28gdmlydHVhbCBtYWNoaW5lIGluc3RhbmNlcw0KDQpwYXJhbWV0ZXJzOg0KICBpbWFnZV9uYW1lXzE6DQogICAgdHlwZTogc3RyaW5nDQogICAgbGFiZWw6IEltYWdlIE5hbWUNCiAgICBkZXNjcmlwdGlvbjogU0NPSU1BR0UgU3BlY2lmeSBhbiBpbWFkc2FkYXN3Z2UgbmFtZSBmb3IgaW5zdGFuY2UxDQogICAgZGVmYXVsdDogY2lycm9zLTAuMy4xLXg4Nl82NA0KICBpbWFnZV9uYW1lXzI6DQogICAgdHlwZTogc3RyaW5nDQogICAgbGFiZWw6IEltYWdlIE5hbWUNCiAgICBkZXNjcmlwdGlvbjogU0NPSU1BR0UgU3BlY2lmeSBhbiBpbWFnZSBuYW1lIGZvciBpbnN0YW5jZTINCiAgICBkZWZhdWx0OiBjaXJyb3MtMC4zLjEteDg2XzY0DQogIG5ldHdvcmtfaWQ6DQogICAgdHlwZTogc3RyaW5nDQogICAgbGFiZWw6IE5ldHdvcmsgSUQNCiAgICBkZXNjcmlwdGlvbjogU0NPTkVUV09SSyBOZXR3b3JrIHRvIGJlIHVzZWQgZm9yIHRoZSBjb21wdXRlIGluc3RhbmNlDQogICAgaGlkZGVuOiB0cnVlDQogICAgY29uc3RyYWludHM6DQogICAgICAtIGxlbmd0aDogeyBtaW46IDYsIG1heDogOCB9DQogICAgICAgIGRlc2NyaXB0aW9uOiBQYXNzd29yZCBsZW5ndGggbXVzdCBiZSBiZXR3ZWVuIDYgYW5kIDggY2hhcmFjdGVycy4NCiAgICAgIC0gcmFuZ2U6IHsgbWluOiA2LCBtYXg6IDggfQ0KICAgICAgICBkZXNjcmlwdGlvbjogUmFuZ2UgZGVzY3JpcHRpb24NCiAgICAgIC0gYWxsb3dlZF92YWx1ZXM6DQogICAgICAgIC0gbTEuc21hbGwNCiAgICAgICAgLSBtMS5tZWRpdW0NCiAgICAgICAgLSBtMS5sYXJnZQ0KICAgICAgICBkZXNjcmlwdGlvbjogQWxsb3dlZCB2YWx1ZXMgZGVzY3JpcHRpb24NCiAgICAgIC0gYWxsb3dlZF9wYXR0ZXJuOiAiW2EtekEtWjAtOV0rIg0KICAgICAgICBkZXNjcmlwdGlvbjogUGFzc3dvcmQgbXVzdCBjb25zaXN0IG9mIGNoYXJhY3RlcnMgYW5kIG51bWJlcnMgb25seS4NCiAgICAgIC0gYWxsb3dlZF9wYXR0ZXJuOiAiW0EtWl0rW2EtekEtWjAtOV0qIg0KICAgICAgICBkZXNjcmlwdGlvbjogUGFzc3dvcmQgbXVzdCBzdGFydCB3aXRoIGFuIHVwcGVyY2FzZSBjaGFyYWN0ZXIuDQogICAgICAtIGN1c3RvbV9jb25zdHJhaW50OiBub3ZhLmtleXBhaXINCiAgICAgICAgZGVzY3JpcHRpb246IEN1c3RvbSBkZXNjcmlwdGlvbg0KDQpyZXNvdXJjZXM6DQogIG15X2luc3RhbmNlMToNCiAgICB0eXBlOiBPUzo6Tm92YTo6U2VydmVyDQogICAgcHJvcGVydGllczoNCiAgICAgIGltYWdlOiB7IGdldF9wYXJhbTogaW1hZ2VfbmFtZV8xIH0NCiAgICAgIGZsYXZvcjogbTEuc21hbGwNCiAgICAgIG5ldHdvcmtzOg0KICAgICAgICAtIG5ldHdvcmsgOiB7IGdldF9wYXJhbSA6IG5ldHdvcmtfaWQgfQ0KICBteV9pbnN0YW5jZTI6DQogICAgdHlwZTogT1M6Ok5vdmE6OlNlcnZlcg0KICAgIHByb3BlcnRpZXM6DQogICAgICBpbWFnZTogeyBnZXRfcGFyYW06IGltYWdlX25hbWVfMiB9DQogICAgICBmbGF2b3I6IG0xLnRpbnkNCiAgICAgIG5ldHdvcmtzOg0KICAgICAgICAtIG5ldHdvcmsgOiB7IGdldF9wYXJhbSA6IG5ldHdvcmtfaWQgfQ";
- timeout = 0;
- artifactLabel = normalizeArtifactLabel(artifactName);
- break;
- }
- case SHELL_SCRIPT:
- default: {// dummy
- artifactName = generateUUIDforSufix() + "testArtifact.sh";
- payloadData = "dGVzdA==";
- updatedPayloadData = "YmVzYg==";
- artifactLabel = normalizeArtifactLabel(artifactName);
- break;
- }
- }
- artifactLabel = normalizeArtifactLabel("ci" + artifactName);
-
- ArtifactReqDetails artifactDetails = null;
-
- if (!updatedPayload){
- artifactDetails = new ArtifactReqDetails(artifactName, artifactType, artifactDescription, payloadData, artifactLabel);
- }
- else artifactDetails = new ArtifactReqDetails(artifactName, artifactType, artifactDescription,
- updatedPayloadData, artifactLabel);
-
- artifactDetails.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT.getType());
- artifactDetails.setUrl(url);
- artifactDetails.setTimeout(timeout);
- artifactDetails.setArtifactDisplayName(artifactLabel);
- return artifactDetails;
- }
-
- private static String getDcaeArtifactName(ArtifactTypeEnum artifactTypeEnum, String artifactType) {
- String artifactName = null;
- switch (artifactTypeEnum) {
- case DCAE_INVENTORY_TOSCA: {
- artifactName = generateUUIDforSufix() + artifactType + "_toscaSampleArtifact.yml";
- break;
- }
- case DCAE_INVENTORY_JSON: {
- artifactName = generateUUIDforSufix() + artifactType + "_jsonSampleArtifact.json";
- break;
- }
- case DCAE_INVENTORY_POLICY: {
- artifactName = generateUUIDforSufix() + artifactType + "_emfSampleArtifact.emf";
- break;
- }
- case DCAE_INVENTORY_DOC: {
- artifactName = generateUUIDforSufix() + artifactType + "_docSampleArtifact.doc";
- break;
- }
- case DCAE_INVENTORY_BLUEPRINT: {
- artifactName = generateUUIDforSufix() + artifactType + "_bluePrintSampleArtifact.xml";
- break;
- }
- case DCAE_INVENTORY_EVENT: {
- artifactName = generateUUIDforSufix() + artifactType + "_eventSampleArtifact.xml";
- break;
- }
- }
- return artifactName;
- }
-
- // ---------------------Audit message------------------
- public static ExpectedResourceAuditJavaObject getDefaultImportResourceAuditMsgSuccess() {
-
- ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = new ExpectedResourceAuditJavaObject();
- expectedResourceAuditJavaObject.setAction(AuditingActionEnum.IMPORT_RESOURCE.getName());
- expectedResourceAuditJavaObject.setResourceName("defaultImportResourceName.yaml");
- expectedResourceAuditJavaObject.setResourceType("Resource");
- expectedResourceAuditJavaObject.setPrevVersion("");
- expectedResourceAuditJavaObject.setCurrVersion("0.1");
- expectedResourceAuditJavaObject.setModifierName(ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER).getFullName());
- expectedResourceAuditJavaObject.setModifierUid(ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER).getUserId());
- expectedResourceAuditJavaObject.setPrevState("");
- expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.toString());
- expectedResourceAuditJavaObject.setStatus("201");
- expectedResourceAuditJavaObject.setDesc("OK");
- expectedResourceAuditJavaObject.setToscaNodeType("");
- return expectedResourceAuditJavaObject;
-
- }
-
- public static ExpectedResourceAuditJavaObject getDefaultImportResourceAuditMsgFailure(ErrorInfo errorInfo, List<String> variables) {
-
- ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = new ExpectedResourceAuditJavaObject();
- expectedResourceAuditJavaObject.setAction(AuditingActionEnum.IMPORT_RESOURCE.getName());
- expectedResourceAuditJavaObject.setResourceName("");
- expectedResourceAuditJavaObject.setResourceType("Resource");
- expectedResourceAuditJavaObject.setPrevVersion("");
- expectedResourceAuditJavaObject.setCurrVersion("");
- expectedResourceAuditJavaObject.setModifierName(ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER).getFullName());
- expectedResourceAuditJavaObject.setModifierUid(ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER).getUserId());
- expectedResourceAuditJavaObject.setPrevState("");
- expectedResourceAuditJavaObject.setCurrState("");
- expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString());
- expectedResourceAuditJavaObject.setDesc(AuditValidationUtils.buildAuditDescription(errorInfo, variables));
- expectedResourceAuditJavaObject.setToscaNodeType("");
- return expectedResourceAuditJavaObject;
-
- }
-
- public static ExpectedResourceAuditJavaObject getDefaultCertificationRequestAuditMsgSuccess() {
-
- ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = new ExpectedResourceAuditJavaObject();
- expectedResourceAuditJavaObject.setAction(AuditingActionEnum.CERTIFICATION_REQUEST_RESOURCE.getName());
- expectedResourceAuditJavaObject.setResourceName("defaultResourceName");
- expectedResourceAuditJavaObject.setResourceType("Resource");
- expectedResourceAuditJavaObject.setPrevVersion("");
- expectedResourceAuditJavaObject.setCurrVersion("0.1");
- expectedResourceAuditJavaObject.setModifierName(ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER).getFullName());
- expectedResourceAuditJavaObject.setModifierUid(ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER).getUserId());
- expectedResourceAuditJavaObject.setPrevState("");
- expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.toString());
- expectedResourceAuditJavaObject.setStatus("200");
- expectedResourceAuditJavaObject.setDesc("OK");
- expectedResourceAuditJavaObject.setComment("");
- return expectedResourceAuditJavaObject;
-
- }
-
- public static ExpectedResourceAuditJavaObject getDefaultCertificationRequestAuditMsgFailure(ErrorInfo errorInfo, List<String> variables) {
-
- ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = new ExpectedResourceAuditJavaObject();
- expectedResourceAuditJavaObject.setAction(AuditingActionEnum.CERTIFICATION_REQUEST_RESOURCE.getName());
- expectedResourceAuditJavaObject.setResourceName("");
- expectedResourceAuditJavaObject.setResourceType("Resource");
- expectedResourceAuditJavaObject.setPrevVersion("0.1");
- expectedResourceAuditJavaObject.setCurrVersion("0.1");
- expectedResourceAuditJavaObject.setModifierName(ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER).getFullName());
- expectedResourceAuditJavaObject.setModifierUid(ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER).getUserId());
- expectedResourceAuditJavaObject.setPrevState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.toString());
- expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.toString());
- expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString());
- expectedResourceAuditJavaObject.setDesc(AuditValidationUtils.buildAuditDescription(errorInfo, variables));
- expectedResourceAuditJavaObject.setComment("");
- return expectedResourceAuditJavaObject;
-
- }
-
- public static ExpectedExternalAudit getDefaultExternalAuditObject(AssetTypeEnum assetType, AuditingActionEnum action, String query) {
-
- ExpectedExternalAudit expectedExternalAudit = new ExpectedExternalAudit();
- expectedExternalAudit.setACTION(action.getName());
- expectedExternalAudit.setCONSUMER_ID("ci");
- expectedExternalAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetType.getValue() + (query == null ? "" : query));
- expectedExternalAudit.setSTATUS("200");
- expectedExternalAudit.setDESC("OK");
- return expectedExternalAudit;
-
- }
-
- public static ExpectedExternalAudit getDefaultAssetListAudit(AssetTypeEnum assetType, AuditingActionEnum auditAction) {
-
- // ExpectedExternalAudit expectedAssetListAuditJavaObject = new
- // ExpectedExternalAudit();
- ExpectedExternalAudit expectedAssetListAuditJavaObject = getDefaultExternalAuditObject(assetType, auditAction, null);
- return expectedAssetListAuditJavaObject;
-
- }
-
- public static ExpectedExternalAudit getDefaultFilteredAssetListAudit(AssetTypeEnum assetType, String query) {
-
- // ExpectedExternalAudit expectedAssetListAuditJavaObject = new
- // ExpectedExternalAudit();
- ExpectedExternalAudit expectedAssetListAuditJavaObject = getDefaultExternalAuditObject(assetType, AuditingActionEnum.GET_FILTERED_ASSET_LIST, query);
- return expectedAssetListAuditJavaObject;
-
- }
-
- public static ExpectedExternalAudit getDefaultExternalArtifactAuditSuccess(AssetTypeEnum assetType, AuditingActionEnum action, ArtifactDefinition artifactDefinition, String componentUUID) {
-
- // ExpectedExternalAudit expectedExternalArtifactAudit = new
- // ExpectedExternalAudit();
-
- ExpectedExternalAudit expectedExternalArtifactAudit = getDefaultExternalAuditObject(assetType, action, null);
- expectedExternalArtifactAudit.setMODIFIER(AuditValidationUtils.getModifierString(artifactDefinition.getUpdaterFullName(), artifactDefinition.getUserIdLastUpdater()));
- expectedExternalArtifactAudit.setPREV_ARTIFACT_UUID("");
- expectedExternalArtifactAudit.setCURR_ARTIFACT_UUID(artifactDefinition.getArtifactUUID());
- expectedExternalArtifactAudit.setARTIFACT_DATA(AuditValidationUtils.buildArtifactDataAudit(artifactDefinition));
- expectedExternalArtifactAudit.setRESOURCE_URL(expectedExternalArtifactAudit.getRESOURCE_URL() + "/" + componentUUID + "/artifacts");
- return expectedExternalArtifactAudit;
-
- }
-
- public static ExpectedExternalAudit getDefaultExternalArtifactAuditSuccess(AssetTypeEnum assetType, AuditingActionEnum action, ArtifactDefinition artifactDefinition, Component component) {
-
- //ExpectedExternalAudit expectedExternalArtifactAudit = new ExpectedExternalAudit();
-
- ExpectedExternalAudit expectedExternalArtifactAudit = getDefaultExternalAuditObject(assetType, action, null);
- expectedExternalArtifactAudit.setMODIFIER(AuditValidationUtils.getModifierString(artifactDefinition.getUpdaterFullName(), artifactDefinition.getUserIdLastUpdater()));
- expectedExternalArtifactAudit.setPREV_ARTIFACT_UUID("");
- expectedExternalArtifactAudit.setCURR_ARTIFACT_UUID(artifactDefinition.getArtifactUUID());
- expectedExternalArtifactAudit.setARTIFACT_DATA(AuditValidationUtils.buildArtifactDataAudit(artifactDefinition));
- expectedExternalArtifactAudit.setRESOURCE_URL(expectedExternalArtifactAudit.getRESOURCE_URL() + "/" + component.getUUID() + "/artifacts");
- expectedExternalArtifactAudit.setRESOURCE_NAME(component.getName());
- expectedExternalArtifactAudit.setRESOURCE_TYPE(component.getComponentType().getValue());
- return expectedExternalArtifactAudit;
-
- }
-
- public static ExpectedResourceAuditJavaObject getDefaultCreateResourceExternalAPI(String resourceName) {
-
- ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = new ExpectedResourceAuditJavaObject();
- expectedResourceAuditJavaObject.setAction(AuditingActionEnum.CREATE_RESOURCE_BY_API.getName());
- expectedResourceAuditJavaObject.setResourceName(resourceName);
- expectedResourceAuditJavaObject.setResourceType("Resource");
- expectedResourceAuditJavaObject.setCONSUMER_ID("ci");
- expectedResourceAuditJavaObject.setRESOURCE_URL("/sdc/v1/catalog/resources");
- expectedResourceAuditJavaObject.setMODIFIER("");
- expectedResourceAuditJavaObject.setPrevVersion("");
- expectedResourceAuditJavaObject.setCurrVersion("0.1");
- expectedResourceAuditJavaObject.setPrevState("");
- expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.toString());
- expectedResourceAuditJavaObject.setStatus("201");
- expectedResourceAuditJavaObject.setDesc("OK");
-
- return expectedResourceAuditJavaObject;
-
-
- }
-
- public static ExpectedExternalAudit getDefaultExternalArtifactAuditSuccess(AssetTypeEnum assetType, AuditingActionEnum action, ArtifactDefinition artifactDefinition, String componentUUID, String resourceInstanceName) {
-
- ExpectedExternalAudit expectedExternalArtifactAudit = getDefaultExternalArtifactAuditSuccess(assetType, action, artifactDefinition, componentUUID);
- expectedExternalArtifactAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetType.getValue() + "/" + componentUUID + "/resourceInstances/" + resourceInstanceName + "/artifacts");
- return expectedExternalArtifactAudit;
- }
-
- public static ExpectedExternalAudit getDefaultExternalArtifactAuditFailure(AssetTypeEnum assetType, AuditingActionEnum action, ArtifactDefinition artifactDefinition, String componentUUID, ErrorInfo errorInfo, List<String> variables) {
-
- // ExpectedExternalAudit expectedExternalArtifactAudit = new
- // ExpectedExternalAudit();
-
- ExpectedExternalAudit expectedExternalArtifactAudit = getDefaultExternalAuditObject(assetType, action, null);
- expectedExternalArtifactAudit.setMODIFIER(AuditValidationUtils.getModifierString(artifactDefinition.getUpdaterFullName(), artifactDefinition.getUserIdLastUpdater()));
- expectedExternalArtifactAudit.setPREV_ARTIFACT_UUID("");
- expectedExternalArtifactAudit.setCURR_ARTIFACT_UUID(artifactDefinition.getArtifactUUID());
- expectedExternalArtifactAudit.setARTIFACT_DATA(AuditValidationUtils.buildArtifactDataAudit(artifactDefinition));
- expectedExternalArtifactAudit.setRESOURCE_URL(expectedExternalArtifactAudit.getRESOURCE_URL() + "/" + componentUUID + "/artifacts");
- expectedExternalArtifactAudit.setSTATUS(errorInfo.getCode().toString());
- expectedExternalArtifactAudit.setDESC(AuditValidationUtils.buildAuditDescription(errorInfo, variables));
- return expectedExternalArtifactAudit;
-
- }
-
- public static ExpectedExternalAudit getDefaultExternalArtifactAuditFailure(AssetTypeEnum assetType, AuditingActionEnum action, ArtifactDefinition artifactDefinition, String componentUUID, ErrorInfo errorInfo, List<String> variables,
- String resourceInstanceName) {
-
- ExpectedExternalAudit expectedExternalArtifactAudit = getDefaultExternalArtifactAuditFailure(assetType, action, artifactDefinition, componentUUID, errorInfo, variables);
- expectedExternalArtifactAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetType.getValue() + "/" + componentUUID + "/resourceInstances/" + resourceInstanceName + "/artifacts");
- return expectedExternalArtifactAudit;
- }
-
- public static ExpectedExternalAudit getFilteredAssetListAuditCategoryNotFound(AssetTypeEnum assetType, String query, String category) {
-
- // ExpectedExternalAudit expectedAssetListAuditJavaObject = new
- // ExpectedExternalAudit();
- ExpectedExternalAudit expectedAssetListAuditJavaObject = getDefaultExternalAuditObject(assetType, AuditingActionEnum.GET_FILTERED_ASSET_LIST, query);
- expectedAssetListAuditJavaObject.setSTATUS("404");
- ErrorInfo errorInfo = null;
- try {
- errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_CATEGORY_NOT_FOUND.name());
- } catch (FileNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- String desc = (errorInfo.getMessageId() + ": " + errorInfo.getMessage()).replace("%2", "category").replace("%3", category).replace("%1", "resource");
- expectedAssetListAuditJavaObject.setDESC(desc);
-
- return expectedAssetListAuditJavaObject;
-
- }
-
- public static ExpectedExternalAudit getDefaultAssetMetadataAudit(AssetTypeEnum assetType, Component component) {
-
- ExpectedExternalAudit expectedAssetListAuditJavaObject = new ExpectedExternalAudit();
- expectedAssetListAuditJavaObject = getDefaultExternalAuditObject(assetType, AuditingActionEnum.GET_ASSET_METADATA, null);
- expectedAssetListAuditJavaObject.setRESOURCE_URL(expectedAssetListAuditJavaObject.getRESOURCE_URL() + "/" + component.getUUID() + "/metadata");
- expectedAssetListAuditJavaObject.setRESOURCE_NAME(component.getName());
- expectedAssetListAuditJavaObject.setRESOURCE_TYPE(component.getComponentType().getValue());
- expectedAssetListAuditJavaObject.setSERVICE_INSTANCE_ID(component.getUUID());
- return expectedAssetListAuditJavaObject;
-
- }
-
- public static ExpectedExternalAudit getDefaultAssetMetadataAuditFailure(AssetTypeEnum assetType, String serviceUuid, String resourceType) {
-
- ExpectedExternalAudit expectedAssetListAuditJavaObject = new ExpectedExternalAudit();
- expectedAssetListAuditJavaObject = getDefaultExternalAuditObject(assetType, AuditingActionEnum.GET_ASSET_METADATA, null);
- expectedAssetListAuditJavaObject.setSTATUS("404");
- expectedAssetListAuditJavaObject.setDESC("OK");
- expectedAssetListAuditJavaObject.setRESOURCE_URL(expectedAssetListAuditJavaObject.getRESOURCE_URL() + "/" + serviceUuid + "/metadata");
- expectedAssetListAuditJavaObject.setRESOURCE_TYPE(resourceType);
- expectedAssetListAuditJavaObject.setSERVICE_INSTANCE_ID(serviceUuid);
- return expectedAssetListAuditJavaObject;
-
- }
-
- // Category/Subcategory/Group
- public static CategoryDefinition getDefaultCategory() {
- CategoryDefinition productCategoryDefinition = new CategoryDefinition();
- productCategoryDefinition.setName("CiCateg" + generateUUIDforSufix());
- return productCategoryDefinition;
- }
-
- public static SubCategoryDefinition getDefaultSubCategory() {
- SubCategoryDefinition productSubCategoryDefinition = new SubCategoryDefinition();
- productSubCategoryDefinition.setName("CiSubCateg" + generateUUIDforSufix());
- return productSubCategoryDefinition;
- }
-
- public static GroupingDefinition getDefaultGroup() {
- GroupingDefinition productGroupDefinition = new GroupingDefinition();
- productGroupDefinition.setName("CiGrouping1" + generateUUIDforSufix());
- return productGroupDefinition;
- }
-
- // Product
-
- public static ProductReqDetails getDefaultProduct() {
- return createDefaultProductReqDetails("CiProduct1", null);
- }
-
- public static ProductReqDetails getDefaultProduct(String name) {
- return createDefaultProductReqDetails(name, null);
- }
-
- public static ProductReqDetails getDefaultProduct(CategoryDefinition category) {
- List<CategoryDefinition> categories = new ArrayList<>();
- categories.add(category);
- return createDefaultProductReqDetails("CiProduct1", categories);
- }
-
- public static ProductReqDetails getDefaultProduct(String name, CategoryDefinition category) {
- List<CategoryDefinition> categories = new ArrayList<>();
- categories.add(category);
- return createDefaultProductReqDetails(name, categories);
- }
-
- public static ProductReqDetails getDefaultProduct(List<CategoryDefinition> categories) {
- return createDefaultProductReqDetails("CiProduct1", categories);
- }
-
- public static ProductReqDetails getDefaultProduct(String name, List<CategoryDefinition> categories) {
- return createDefaultProductReqDetails(name, categories);
- }
-
- private static ProductReqDetails createDefaultProductReqDetails(String name, List<CategoryDefinition> categories) {
- ProductReqDetails product = new ProductReqDetails(name);
- ArrayList<String> tags = new ArrayList<String>();
- tags.add(name);
- product.setTags(tags);
- product.setProjectCode("12345");
- product.setIcon("myIcon");
- ArrayList<String> contacts = new ArrayList<String>();
- contacts.add(ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_MANAGER1).getUserId());
- product.setContacts(contacts);
- product.setCategories(categories);
- String fullName = "This is my full name: " + name;
- product.setFullName(fullName);
- String description = "This is product description";
- product.setDescription(description);
- return product;
- }
-
- public static RequirementCapabilityRelDef getReqCapRelation(String fromCompInstId, String toCompInstId, String reqOwnerId, String capOwnerId, String capType, String reqCapName, List<CapabilityDefinition> capList,
- List<RequirementDefinition> reqList) {
- RequirementCapabilityRelDef requirementDef = new RequirementCapabilityRelDef();
- requirementDef.setFromNode(fromCompInstId);
- requirementDef.setToNode(toCompInstId);
- RelationshipInfo pair = new RelationshipInfo();
- pair.setRequirementOwnerId(reqOwnerId);
- pair.setCapabilityOwnerId(capOwnerId);
- pair.setRequirement(reqCapName);
- RelationshipImpl relationship = new RelationshipImpl();
- relationship.setType(capType);
- pair.setRelationships(relationship);
- pair.setCapabilityUid(capList.get(0).getUniqueId());
- pair.setRequirementUid(reqList.get(0).getUniqueId());
- List<CapabilityRequirementRelationship> relationships = new ArrayList<>();
- CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship();
- relationships.add(capReqRel);
- capReqRel.setRelation(pair);
- requirementDef.setRelationships(relationships);
- return requirementDef;
- }
-
- private static String generateUUIDforSufix() {
-
- String uniqueSufix = UUID.randomUUID().toString();
- String[] split = uniqueSufix.split("-");
- return uniqueSufix = split[4];
- }
-
- private static String normalizeArtifactLabel(String label) {
-
- label = label.substring(0, label.indexOf("."));
- String normalizedLabel = ValidationUtils.normalizeArtifactLabel(label);
- return normalizedLabel.substring(0, Math.min(25, normalizedLabel.length()));
-
- }
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/FileUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/FileUtils.java
deleted file mode 100644
index 5acb0e47c1..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/FileUtils.java
+++ /dev/null
@@ -1,137 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utils.general;
-
-import static org.testng.AssertJUnit.assertTrue;
-
-import java.io.File;
-import java.io.IOException;
-import java.nio.charset.StandardCharsets;
-import java.nio.file.Files;
-import java.nio.file.Paths;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.openecomp.sdc.ci.tests.utils.Decoder;
-import org.openecomp.sdc.ci.tests.utils.Utils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import fj.data.Either;
-
-public class FileUtils {
- private static final Logger LOGGER = LoggerFactory.getLogger(Utils.class.getName());
-
- public static void writeToFile(String filePath, String content) {
- try {
- Files.write(Paths.get(filePath), content.getBytes());
- } catch (IOException e) {
- LOGGER.debug(String.format("Failed to write to file '%s'", filePath), e);
- }
- }
-
- public static String getFileName(String fullyQualified) {
- String fileName = fullyQualified;
-
- int i = fullyQualified.lastIndexOf('.');
- if (i > 0) {
- fileName = fullyQualified.substring(i + 1);
- }
- return fileName;
-
- }
-
- public static Either<String, Exception> getFileContentUTF8(String filePath) {
- Either<String, Exception> eitherResult;
- try {
- String content = new String(Files.readAllBytes(Paths.get(filePath)), StandardCharsets.UTF_8);
- eitherResult = Either.left(content);
- } catch (Exception e) {
- eitherResult = Either.right(e);
- }
- return eitherResult;
- }
-
- public static List<String> getFileListFromBaseDirectoryByTestName(String testResourcesPath) {
-
- File file = new File(testResourcesPath);
- File[] listFiles = file.listFiles();
- if (listFiles != null) {
- List<String> listFileName = new ArrayList<>();
- for (File newFile : listFiles) {
- if (newFile.isFile()) {
- listFileName.add(newFile.getPath());
- }
- }
- return listFileName;
- }
- assertTrue("directory " + testResourcesPath + " is empty", false);
- return null;
- }
-
- public static String getFilePathFromListByPattern(List<String> fileList, String pattern) {
-
- for (String filePath : fileList) {
- if (filePath.contains(pattern)) {
- return filePath;
- }
- }
- return null;
- }
-
- public static String loadPayloadFileFromListUsingPosition(List<String> listFileName, String pattern,
- Boolean isBase64, int positionInList) throws IOException {
- List<String> newList = new ArrayList<>(Arrays.asList(listFileName.get(positionInList)));
- return loadPayloadFile(newList, pattern, isBase64);
- }
-
- public static String loadPayloadFile(List<String> listFileName, String pattern, Boolean isBase64)
- throws IOException {
- String fileName;
- String payload = null;
- fileName = FileUtils.getFilePathFromListByPattern(listFileName, pattern);
- LOGGER.debug("fileName: {}",fileName);
-
- if (fileName != null) {
- payload = Decoder.readFileToString(fileName);
- if (isBase64) {
- payload = Decoder.encode(payload.getBytes());
- }
- } else {
- assertTrue("file to upload not found", false);
- }
- return payload;
- }
-
- public static String getFileNameFromPath(String testResourcesPath) {
-
- File file = new File(testResourcesPath);
- String fileName = null;
- if (file.exists()) {
- return file.getName();
- } else {
- assertTrue("file to upload not found", false);
- }
- return fileName;
-
- }
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/ImportUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/ImportUtils.java
deleted file mode 100644
index 7e5a7d69a2..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/ImportUtils.java
+++ /dev/null
@@ -1,57 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utils.general;
-
-import java.io.IOException;
-import java.util.List;
-
-import org.openecomp.sdc.ci.tests.datatypes.ImportReqDetails;
-
-public class ImportUtils {
-
- public static ImportReqDetails getImportResourceDetailsByPathAndName(ImportReqDetails importReqDetails,
- String filePath, String fileName) throws IOException {
-
- // ImportReqDetails importReqDetails;
- // User sdncUserDetails;
- // String testResourcesPath;
- // ResourceReqDetails resourceDetails;
- // Config config;
- // config = Utils.getConfig();
- //
- // importReqDetails = ElementFactory.getDefaultImportResource();
- // User sdncUserDetails =
- // ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
- // ResourceReqDetails resourceDetails =
- // ElementFactory.getDefaultResource();
- // String sourceDir = config.getResourceConfigDir();
- // String testResourcesPath = sourceDir + File.separator + workDir;
- // final String workDir = "importToscaResourceByCreateUrl";
-
- List<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(filePath);
- importReqDetails.setPayloadName(fileName);
- String payloadData = FileUtils.loadPayloadFile(listFileName, fileName, true);
- importReqDetails.setPayloadData(payloadData);
-
- return importReqDetails;
- }
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/graph/GraphFileUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/graph/GraphFileUtils.java
deleted file mode 100644
index 00c51f8fbd..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/graph/GraphFileUtils.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utils.graph;
-
-import java.io.IOException;
-import java.nio.charset.Charset;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.apache.commons.io.FileUtils;
-import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
-
-import com.thinkaurelius.titan.core.TitanVertex;
-
-public class GraphFileUtils {
-
- public static final String TEMP_FILES_PATH = "src/main/resources/ci/tempFiles/%s.txt";
-
- public static void writeVerticesUIDToFile(String fileName, Iterable<TitanVertex> vertices) throws IOException {
- Path path = Paths.get(String.format(TEMP_FILES_PATH, fileName));
- Files.deleteIfExists(path);
- Path file = Files.createFile(path);
- final String newLine = System.getProperty("line.separator");
- for (TitanVertex vertex : vertices) {
- FileUtils.writeStringToFile(file.toFile(), String.valueOf(vertex.id()) + newLine, Charset.defaultCharset(), true);
- }
- }
-
- public static List<String> getVerticesIdsFromFile(String fileName) throws IOException {
- List<String> verticesUids = new ArrayList<>();
- Files.lines(Paths.get(String.format(TEMP_FILES_PATH, fileName))).forEach(verticesUids::add);
- return verticesUids;
- }
-
- private static String getUid(TitanVertex titanVertex) {
- return (String )titanVertex.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
- }
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ArtifactRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ArtifactRestUtils.java
deleted file mode 100644
index ddd9209d83..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ArtifactRestUtils.java
+++ /dev/null
@@ -1,920 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utils.rest;
-
-import static org.testng.AssertJUnit.assertNotNull;
-import static org.testng.AssertJUnit.assertTrue;
-
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.commons.codec.binary.Base64;
-import org.json.simple.JSONObject;
-import org.json.simple.JSONValue;
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.model.ArtifactDefinition;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.ci.tests.api.Urls;
-import org.openecomp.sdc.ci.tests.config.Config;
-import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
-import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
-import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
-import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest;
-import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
-import org.openecomp.sdc.ci.tests.utils.Utils;
-import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
-import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
-import org.openecomp.sdc.common.util.ValidationUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.AssertJUnit;
-
-import com.google.gson.Gson;
-
-public class ArtifactRestUtils extends BaseRestUtils {
- private static Logger logger = LoggerFactory.getLogger(ArtifactRestUtils.class.getName());
-
-
- // External API
- // Delete Artifact on rI of the asset
- public static RestResponse externalAPIDeleteArtifactOfComponentInstanceOnAsset(Component component, User user, ComponentInstance resourceInstance, String artifactUUID) throws IOException {
- Config config = Utils.getConfig();
- String resourceType = null;
- String resourceUUID = component.getUUID();
- String resourceInstanceName = resourceInstance.getNormalizedName();
-
- System.out.println(component.getComponentType());
-
- if(component.getComponentType().toString().toLowerCase().equals("resource")) {
- resourceType = "resources";
- } else {
- resourceType = "services";
- }
-
- String url = String.format(Urls.DELETE_EXTRNAL_API_DELETE_ARTIFACT_OF_COMPONENTINSTANCE_ON_ASSET, config.getCatalogBeHost(), config.getCatalogBePort(), resourceType, resourceUUID, resourceInstanceName, artifactUUID);
-
- return deleteInformationalArtifact(user, url);
- }
-
- // Delete Artifact of the asset
- public static RestResponse externalAPIDeleteArtifactOfTheAsset(Component component, User user, String artifactUUID) throws IOException {
- Config config = Utils.getConfig();
- String resourceType = null;
- String resourceUUID = component.getUUID();
-
- System.out.println(component.getComponentType());
-
- if(component.getComponentType().toString().toLowerCase().equals("resource")) {
- resourceType = "resources";
- } else {
- resourceType = "services";
- }
-
- String url = String.format(Urls.DELETE_EXTRNAL_API_DELETE_ARTIFACT_OF_ASSET, config.getCatalogBeHost(), config.getCatalogBePort(), resourceType, resourceUUID, artifactUUID);
-
- RestResponse restResponse = deleteInformationalArtifact(user, url);
-
- return restResponse;
- }
-
-
- // Update Artifact on rI of the asset
- public static RestResponse externalAPIUpdateArtifactOfComponentInstanceOnAsset(Component component, User user, ArtifactReqDetails artifactReqDetails, ComponentInstance resourceInstance, String artifactUUID) throws IOException {
- Config config = Utils.getConfig();
- String resourceType = null;
- String resourceUUID = component.getUUID();
- String resourceInstanceName = resourceInstance.getNormalizedName();
-
- System.out.println(component.getComponentType());
-
- if(component.getComponentType().toString().toLowerCase().equals("resource")) {
- resourceType = "resources";
- } else {
- resourceType = "services";
- }
-
- String url = String.format(Urls.POST_EXTERNAL_API_UPDATE_ARTIFACT_OF_COMPONENTINSTANCE_ON_ASSET, config.getCatalogBeHost(), config.getCatalogBePort(), resourceType, resourceUUID, resourceInstanceName, artifactUUID);
-
- return updateInformationalArtifact(artifactReqDetails, user, calculateChecksum(artifactReqDetails), url);
- }
-
- // Update Artifact of the asset
- public static RestResponse externalAPIUpdateArtifactOfTheAsset(Component component, User user, ArtifactReqDetails artifactReqDetails, String artifactUUID) throws IOException {
- Config config = Utils.getConfig();
- String resourceType = null;
- String resourceUUID = component.getUUID();
-
- System.out.println(component.getComponentType());
-
- if(component.getComponentType().toString().toLowerCase().equals("resource")) {
- resourceType = "resources";
- } else {
- resourceType = "services";
- }
-
- String url = String.format(Urls.POST_EXTERNAL_API_UPDATE_ARTIFACT_OF_ASSET, config.getCatalogBeHost(), config.getCatalogBePort(), resourceType, resourceUUID, artifactUUID);
-
- return updateInformationalArtifact(artifactReqDetails, user, calculateChecksum(artifactReqDetails), url);
- }
-
-
- // Upload Artifact on rI of the asset
- public static RestResponse externalAPIUploadArtifactOfComponentInstanceOnAsset(Component component, User user, ArtifactReqDetails artifactReqDetails, ComponentInstance resourceInstance) throws IOException {
- Config config = Utils.getConfig();
- String resourceType = null;
- String resourceUUID = component.getUUID();
- String resourceInstanceName = resourceInstance.getNormalizedName();
-
- System.out.println(component.getComponentType());
-
- if(component.getComponentType().toString().toLowerCase().equals("resource")) {
- resourceType = "resources";
- } else {
- resourceType = "services";
- }
-
- String url = String.format(Urls.POST_EXTERNAL_API_UPLOAD_ARTIFACT_OF_COMPONENTINSTANCE_ON_ASSET, config.getCatalogBeHost(), config.getCatalogBePort(), resourceType, resourceUUID, resourceInstanceName);
-
- return uploadInformationalArtifact(artifactReqDetails, user, calculateChecksum(artifactReqDetails), url);
- }
-
- // Upload Artifact of the asset
- public static RestResponse externalAPIUploadArtifactOfTheAsset(Component component, User user, ArtifactReqDetails artifactReqDetails) throws IOException {
- Config config = Utils.getConfig();
- String resourceType = null;
- String resourceUUID = component.getUUID();
-
- System.out.println(component.getComponentType());
-
- if(component.getComponentType().toString().toLowerCase().equals("resource")) {
- resourceType = "resources";
- } else {
- resourceType = "services";
- }
-
- String url = String.format(Urls.POST_EXTERNAL_API_UPLOAD_ARTIFACT_OF_ASSET, config.getCatalogBeHost(), config.getCatalogBePort(), resourceType, resourceUUID);
-
- return uploadInformationalArtifact(artifactReqDetails, user, calculateChecksum(artifactReqDetails), url);
- }
-
-
- // Upload Artifact of the asset with invalid checksum
- public static RestResponse externalAPIUploadArtifactWithInvalidCheckSumOfComponentInstanceOnAsset(Component component, User user, ArtifactReqDetails artifactReqDetails, ComponentInstance resourceInstance) throws IOException {
- Config config = Utils.getConfig();
- String resourceType = null;
- String resourceUUID = component.getUUID();
- String resourceInstanceName = resourceInstance.getNormalizedName();
-
- System.out.println(component.getComponentType());
-
- if(component.getComponentType().toString().toLowerCase().equals("resource")) {
- resourceType = "resources";
- } else {
- resourceType = "services";
- }
-
- String url = String.format(Urls.POST_EXTERNAL_API_UPLOAD_ARTIFACT_OF_COMPONENTINSTANCE_ON_ASSET, config.getCatalogBeHost(), config.getCatalogBePort(), resourceType, resourceUUID, resourceInstanceName);
-
- return uploadInformationalArtifact(artifactReqDetails, user, calculateChecksum(artifactReqDetails) + "123", url);
- }
-
- // Upload Artifact of the asset with invalid checksum
- public static RestResponse externalAPIUploadArtifactWithInvalidCheckSumOfTheAsset(Component component, User user, ArtifactReqDetails artifactReqDetails) throws IOException {
- Config config = Utils.getConfig();
- String resourceType = null;
- String resourceUUID = component.getUUID();
-
- System.out.println(component.getComponentType());
-
- if(component.getComponentType().toString().toLowerCase().equals("resource")) {
- resourceType = "resources";
- } else {
- resourceType = "services";
- }
-
- String url = String.format(Urls.POST_EXTERNAL_API_UPLOAD_ARTIFACT_OF_ASSET, config.getCatalogBeHost(), config.getCatalogBePort(), resourceType, resourceUUID);
-
- return uploadInformationalArtifact(artifactReqDetails, user, calculateChecksum(artifactReqDetails) + "123", url);
- }
-
-
- //
- // Testing
- //
- public static RestResponse getResourceDeploymentArtifactExternalAPI(String resourceUUID, String artifactUUID,User sdncModifierDetails, String resourceType) throws IOException {
- Config config = Utils.getConfig();
- String url = null;
-
- if (resourceType.toUpperCase().equals("SERVICE")) {
- url = String.format(Urls.GET_DOWNLOAD_SERVICE_ARTIFACT_OF_ASSET, config.getCatalogBeHost(), config.getCatalogBePort(), resourceUUID, artifactUUID);
-
- } else {
- url = String.format(Urls.GET_DOWNLOAD_RESOURCE_ARTIFACT_OF_ASSET, config.getCatalogBeHost(), config.getCatalogBePort(), resourceUUID, artifactUUID);
- }
-
- Map<String, String> headersMap = new HashMap<String,String>();
- headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId());
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), authorizationHeader);
- headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci");
-
- HttpRequest http = new HttpRequest();
-
- logger.debug("Send GET request to get Resource Assets: {}",url);
- System.out.println("Send GET request to get Resource Assets: " + url);
-
- logger.debug("Request headers: {}",headersMap);
- System.out.println("Request headers: " + headersMap);
-
- RestResponse sendGetResourceAssets = http.httpSendGet(url, headersMap);
-
- return sendGetResourceAssets;
-
- }
-
-
-
- public static RestResponse getComponentInstanceDeploymentArtifactExternalAPI(String resourceUUID, String componentNormalizedName, String artifactUUID,User sdncModifierDetails, String resourceType) throws IOException {
- Config config = Utils.getConfig();
- String url = null;
-
- if (resourceType.toLowerCase().equals("service")) {
- url = String.format(Urls.GET_DOWNLOAD_SERVICE_ARTIFACT_OF_COMPONENT_INSTANCE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceUUID, componentNormalizedName, artifactUUID);
-
- } else {
- url = String.format(Urls.GET_DOWNLOAD_RESOURCE_ARTIFACT_OF_COMPONENT_INSTANCE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceUUID, componentNormalizedName, artifactUUID);
- }
-
- Map<String, String> headersMap = new HashMap<String,String>();
- headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId());
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), authorizationHeader);
- headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci");
-
- HttpRequest http = new HttpRequest();
-
- logger.debug("Send GET request to get Resource Assets: {}",url);
- System.out.println("Send GET request to get Resource Assets: " + url);
-
- logger.debug("Request headers: {}",headersMap);
- System.out.println("Request headers: " + headersMap);
-
- RestResponse sendGetResourceAssets = http.httpSendGet(url, headersMap);
-
- return sendGetResourceAssets;
-
- }
-
-
- //*********** SERVICE ****************
- public static RestResponse getArtifactTypesList() throws IOException {
- Config config = Utils.getConfig();
- String url = String.format(Urls.GET_ALL_ARTIFACTS, config.getCatalogBeHost(), config.getCatalogBePort());
-
- return sendGet(url, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER).getUserId());
- }
-
- public static RestResponse addInformationalArtifactToService(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String serviceUid) throws IOException {
- return addInformationalArtifactToService(artifactDetails, sdncModifierDetails, serviceUid, calculateChecksum(artifactDetails));
- }
-
- public static RestResponse addInformationalArtifactToService(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String serviceUid, String checksum) throws IOException {
- Config config = Utils.getConfig();
- String url = String.format(Urls.ADD_ARTIFACT_TO_SERVICE, config.getCatalogBeHost(), config.getCatalogBePort(), serviceUid);
-
- return uploadInformationalArtifact(artifactDetails, sdncModifierDetails, checksum, url);
- }
-
- public static RestResponse downloadServiceArtifact(ServiceReqDetails service, ArtifactReqDetails artifact, User user, Map<String, String> addionalHeaders) throws Exception
- {
-
- return downloadServiceArtifact( service, artifact, user,addionalHeaders,true);
- }
-
- public static RestResponse downloadServiceArtifact(ServiceReqDetails service, ArtifactReqDetails artifact, User user, Map<String, String> addionalHeaders,boolean addEcompHeader) throws Exception
- {
- Config config = Utils.getConfig();
- String relativeUrl = encodeUrlForDownload(String.format(Urls.DISTRIB_DOWNLOAD_SERVICE_ARTIFACT_RELATIVE_URL, ValidationUtils.convertToSystemName(service.getName()), service.getVersion(), ValidationUtils.normalizeFileName(artifact.getArtifactName())));
- String fullUrl = String.format(Urls.DOWNLOAD_SERVICE_ARTIFACT_FULL_URL, config.getCatalogBeHost(),config.getCatalogBePort(), relativeUrl);
-
- return downloadArtifact(fullUrl, user, addionalHeaders,addEcompHeader);
- }
-
- public static RestResponse downloadResourceArtifact(ServiceReqDetails service, ResourceReqDetails resource, ArtifactReqDetails artifact, User user, Map<String, String> addionalHeaders) throws Exception
- {
- return downloadResourceArtifact(service, resource, artifact, user,addionalHeaders, true);
- }
-
- public static RestResponse downloadResourceArtifact(ServiceReqDetails service,ResourceReqDetails resource, ArtifactReqDetails artifact, User user, Map<String, String> addionalHeaders,boolean addEcompHeader) throws Exception
- {
- Config config = Utils.getConfig();
- String relativeUrl = encodeUrlForDownload(String.format(Urls.DISTRIB_DOWNLOAD_RESOURCE_ARTIFACT_RELATIVE_URL, ValidationUtils.convertToSystemName(service.getName()),service.getVersion(),ValidationUtils.convertToSystemName(resource.getName()), resource.getVersion(), ValidationUtils.normalizeFileName(artifact.getArtifactName())));
- String fullUrl = String.format(Urls.DOWNLOAD_RESOURCE_ARTIFACT_FULL_URL, config.getCatalogBeHost(),config.getCatalogBePort(), relativeUrl);
-
- return downloadArtifact(fullUrl, user, addionalHeaders,addEcompHeader);
- }
-
-
-
- public static RestResponse downloadResourceInstanceArtifact(String serviceUniqueId,String resourceInstanceId, User user, String artifactUniqeId) throws Exception
- {
- Config config = Utils.getConfig();
- String url = String.format(Urls.DOWNLOAD_COMPONENT_INSTANCE_ARTIFACT, config.getCatalogBeHost(),config.getCatalogBePort(), serviceUniqueId, resourceInstanceId, artifactUniqeId);
- RestResponse res = sendGet(url, user.getUserId(), null);
- return res;
- }
-
- ////
-
- //update
-
- public static RestResponse updateInformationalArtifactOfServiceByMethod(ArtifactReqDetails artifactReqDetails, String serviceUid, String artifactUid, User sdncModifierDetails, String httpMethod) throws IOException {
- return updateInformationalArtifactOfServiceByMethod(artifactReqDetails, serviceUid, artifactUid, sdncModifierDetails, httpMethod, calculateChecksum(artifactReqDetails));
- }
-
- public static RestResponse updateInformationalArtifactOfServiceByMethod(ArtifactReqDetails artifactReqDetails, String serviceUid, User sdncModifierDetails, String httpMethod) throws IOException {
- return updateInformationalArtifactOfServiceByMethod(artifactReqDetails, serviceUid, artifactReqDetails.getUniqueId(), sdncModifierDetails, httpMethod, calculateChecksum(artifactReqDetails));
- }
-
- public static RestResponse downloadResourceArtifactInternalApi(String resourceId, User user, String artifactUniqeId) throws Exception
- {
- return downloadComponentArtifactInternalApi(resourceId, user, artifactUniqeId, Urls.UI_DOWNLOAD_RESOURCE_ARTIFACT);
- }
-
- public static RestResponse downloadServiceArtifactInternalApi(String componentId, User user, String artifactUniqeId) throws Exception
- {
- return downloadComponentArtifactInternalApi(componentId, user, artifactUniqeId, Urls.UI_DOWNLOAD_SERVICE_ARTIFACT);
- }
- public static RestResponse downloadComponentArtifactInternalApi(String componentId, User user, String artifactUniqeId, String urlTemplate) throws Exception
- {
- Config config = Utils.getConfig();
- String url = String.format(urlTemplate, config.getCatalogBeHost(),config.getCatalogBePort(), componentId, artifactUniqeId);
- RestResponse res = sendGet(url, user.getUserId(), null);
- return res;
- }
-
-// public static RestResponse downloadServiceArtifactInternalApi(String resourceId, User user, String artifactUniqeId) throws Exception
-// {
-// Config config = Utils.getConfig();
-// String url = String.format(Urls.UI_DOWNLOAD_SERVICE_ARTIFACT, config.getCatalogBeHost(),config.getCatalogBePort(), resourceId, artifactUniqeId);
-// RestResponse res = sendGet(url, user.getUserId(), null);
-// return res;
-// }
-
- /*
- public static RestResponse updateInformationalArtifactPayloadOfService(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String serviceUid, String artifactUid, String checksum) throws IOException
- {
- return updateInformationalArtifactOfService(artifactDetails, sdncModifierDetails, serviceUid, artifactUid, checksum, true);
- }
-
- public static RestResponse updateInformationalArtifactMetadataOfService(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String serviceUid, String artifactUid) throws IOException
- {
- return updateInformationalArtifactOfService(artifactDetails, sdncModifierDetails, serviceUid, artifactUid, calculateChecksum(artifactDetails), false);
- }
-
- public static RestResponse updateInformationalArtifactOfService(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String serviceUid, String artifactUid, String checksum, boolean isPayloadUpdate) throws IOException
- {
- Config config = Utils.getConfig();
- Map<String, String> headersMap = getHeadersMap(sdncModifierDetails);
-
- if (isPayloadUpdate){
- headersMap.put(HttpHeaderEnum.Content_MD5.getValue(), checksum);
- }
-
- Gson gson = new Gson();
- String jsonBody = gson.toJson(artifactDetails);
-
- HttpRequest http = new HttpRequest();
-
- String url = String.format(Urls.UPDATE_OR_DELETE_ARTIFACT_OF_SERVICE, config.getCatalogBeHost(),config.getCatalogBePort(), serviceUid, artifactUid);
- RestResponse res = http.httpSendPost(url, jsonBody, headersMap);
- System.out.println("update artifact was finished with response: "+ res.getErrorCode());
- return res;
- }*/
-
-
-
- public static RestResponse updateInformationalArtifactOfServiceByMethod(ArtifactReqDetails artifactReqDetails, String serviceUid, String artifactUid, User sdncModifierDetails, String httpMethod, String checksum) throws IOException
- {
- Config config = Utils.getConfig();
-
- Map<String, String> headersMap = getHeadersMap(sdncModifierDetails);
- headersMap.put(HttpHeaderEnum.Content_MD5.getValue(), checksum);
-
- Gson gson = new Gson();
- String userBodyJson = gson.toJson(artifactReqDetails);
-
- HttpRequest http = new HttpRequest();
- String url = String.format(Urls.UPDATE_OR_DELETE_ARTIFACT_OF_SERVICE, config.getCatalogBeHost(),config.getCatalogBePort(), serviceUid, artifactUid);
- RestResponse updateResourceResponse = http.httpSendByMethod(url, httpMethod, userBodyJson, headersMap);
-// System.out.println("update artifact was finished with response: "+ updateResourceResponse.getErrorCode());
-
- return updateResourceResponse;
- }
-
-
- public static Map<String, String> getHeadersMap(User sdncModifierDetails) {
- Map<String, String> headersMap = new HashMap<String,String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptJsonHeader);
-
- try{
- headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId());
- }
- catch(Exception e)
- {
-
- }
-
- return headersMap;
- }
-
- //*********** RESOURCE ****************
- //add
- public static RestResponse addInformationalArtifactToResource(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String resourceUid) throws IOException{
- return addInformationalArtifactToResource(artifactDetails, sdncModifierDetails, resourceUid, calculateChecksum(artifactDetails));
- }
-
- public static RestResponse explicitAddInformationalArtifactToResource(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String resourceUid) throws IOException{
- Config config = Utils.getConfig();
-
-
- String url = String.format(Urls.ADD_ARTIFACT_TO_RESOURCE, config.getCatalogBeHost(),config.getCatalogBePort(), resourceUid);
-
- return uploadInformationalArtifact(artifactDetails, sdncModifierDetails, calculateChecksum(artifactDetails), url);
- }
-
-
- public static RestResponse addInformationalArtifactToResource(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String resourceUid, String checksum) throws IOException{
- Config config = Utils.getConfig();
-
- if (artifactDetails.getArtifactGroupType()!=null && artifactDetails.getArtifactGroupType().equals(ArtifactGroupTypeEnum.DEPLOYMENT.getType())){
- //YANG_XML and OTHER deployment artifact should be added through this API, not updated
- String artifactType = artifactDetails.getArtifactType();
- if (!(ArtifactTypeEnum.YANG_XML.getType().equals(artifactType) ||
- ArtifactTypeEnum.OTHER.getType().equals(artifactType) ||
- ArtifactTypeEnum.VNF_CATALOG.getType().equals(artifactType) ||
- ArtifactTypeEnum.VF_LICENSE.getType().equals(artifactType) ||
- ArtifactTypeEnum.VENDOR_LICENSE.getType().equals(artifactType) ||
- ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType().equals(artifactType) ||
- ArtifactTypeEnum.MODEL_QUERY_SPEC.getType().equals(artifactType) ||
- ArtifactTypeEnum.APPC_CONFIG.getType().equals(artifactType))){
- //return updateInformationalArtifactToResource(artifactDetails, sdncModifierDetails, resourceUid);
- }
- }
- String url = String.format(Urls.ADD_ARTIFACT_TO_RESOURCE, config.getCatalogBeHost(),config.getCatalogBePort(), resourceUid);
-
- return uploadInformationalArtifact(artifactDetails, sdncModifierDetails, checksum, url);
- }
- //update
- public static RestResponse updateInformationalArtifactToResource(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String resourceUid) throws IOException{
- return updateInformationalArtifactToResource(artifactDetails, sdncModifierDetails, resourceUid, calculateChecksum(artifactDetails));
- }
-
- public static RestResponse updateInformationalArtifactToResource(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String resourceUid, String checksum) throws IOException {
- Config config = Utils.getConfig();
- if (artifactDetails.getArtifactGroupType()!=null && artifactDetails.getArtifactGroupType().equals("DEPLOYMENT")){
- RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceUid );
- Resource resourceRespJavaObject = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
- Map<String, ArtifactDefinition> deploymentArtifacts = resourceRespJavaObject.getDeploymentArtifacts();
- ArtifactDefinition artifactDefinition = deploymentArtifacts.get(artifactDetails.getArtifactLabel());
- artifactDetails.setUniqueId(artifactDefinition.getUniqueId());
- artifactDetails.setArtifactLabel(artifactDefinition.getArtifactLabel());
-
- }
-
- String url = String.format(Urls.UPDATE_OR_DELETE_ARTIFACT_OF_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceUid, artifactDetails.getUniqueId());
-
- return uploadInformationalArtifact(artifactDetails, sdncModifierDetails, calculateChecksum(artifactDetails), url);
- }
-
- public static RestResponse uploadArtifactToPlaceholderOnResource(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String resourceUid, String placeHolderLabel) throws IOException {
- Config config = Utils.getConfig();
- if (artifactDetails.getArtifactLabel() != null && !artifactDetails.getArtifactLabel().isEmpty()){
- RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceUid );
- Resource resourceRespJavaObject = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
- Map<String, ArtifactDefinition> deploymentArtifacts = resourceRespJavaObject.getDeploymentArtifacts();
- ArtifactDefinition artifactDefinition = deploymentArtifacts.get(artifactDetails.getArtifactLabel());
- AssertJUnit.assertNotNull(artifactDefinition);
- artifactDetails.setUniqueId(artifactDefinition.getUniqueId());
- artifactDetails.setArtifactLabel(artifactDefinition.getArtifactLabel());
-
- }
-
- String url = String.format(Urls.UPDATE_OR_DELETE_ARTIFACT_OF_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceUid, artifactDetails.getUniqueId());
-
- return uploadInformationalArtifact(artifactDetails, sdncModifierDetails, calculateChecksum(artifactDetails), url);
- }
-
- public static RestResponse updateArtifactToResourceInstance(ArtifactDefinition artifactDefinition, User sdncModifierDetails, String resourceInstanceId, String serviceId) throws IOException {
- Config config = Utils.getConfig();
- String url = String.format(Urls.UPDATE_RESOURCE_INSTANCE_ARTIFACT, config.getCatalogBeHost(), config.getCatalogBePort(), serviceId, resourceInstanceId, artifactDefinition.getUniqueId());
- return updateDeploymentArtifact(artifactDefinition, sdncModifierDetails, url);
- }
-
- public static RestResponse updateDeploymentArtifactToResource(ArtifactDefinition artifact, User sdncModifierDetails, String resourceUid) throws IOException {
- Config config = Utils.getConfig();
- String url = String.format(Urls.UPDATE_OR_DELETE_ARTIFACT_OF_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceUid, artifact.getUniqueId());
-
- return updateDeploymentArtifact(artifact, sdncModifierDetails, url);
- }
- public static RestResponse updateDeploymentArtifactToResource(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String resourceUid) throws IOException {
- Config config = Utils.getConfig();
- String url = String.format(Urls.UPDATE_OR_DELETE_ARTIFACT_OF_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceUid, artifactDetails.getUniqueId());
-
- return updateDeploymentArtifact(artifactDetails, sdncModifierDetails, url);
- }
-
-
- public static RestResponse updateDeploymentArtifactToRI(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String resourceInstanceId, String serviceId) throws IOException {
- Config config = Utils.getConfig();
- String url = String.format(Urls.UPDATE_RESOURCE_INSTANCE_HEAT_ENV_PARAMS, config.getCatalogBeHost(), config.getCatalogBePort(), serviceId, resourceInstanceId, artifactDetails.getUniqueId());
- return updateDeploymentArtifact(artifactDetails, sdncModifierDetails, url);
- }
- public static RestResponse updateDeploymentArtifactToRI(ArtifactDefinition artifactDetails, User sdncModifierDetails, String resourceInstanceId, String serviceId) throws IOException {
- Config config = Utils.getConfig();
- String url = String.format(Urls.UPDATE_RESOURCE_INSTANCE_HEAT_ENV_PARAMS, config.getCatalogBeHost(), config.getCatalogBePort(), serviceId, resourceInstanceId, artifactDetails.getUniqueId());
- return updateDeploymentArtifact(artifactDetails, sdncModifierDetails, url);
- }
-
- //delete
- public static RestResponse deleteArtifactFromResourceInstance (ArtifactDefinition artifactDefinition, User sdncModifierDetails, String resourceUid, String serviceId) throws IOException{
- Config config = Utils.getConfig();
- String url = String.format(Urls.DELETE_RESOURCE_INSTANCE_ARTIFACT, config.getCatalogBeHost(), config.getCatalogBePort(), serviceId, resourceUid, artifactDefinition.getUniqueId());
- return sendDelete(url, sdncModifierDetails.getUserId());
- }
-
- public static RestResponse deleteInformationalArtifactFromResource(String resourceUid, ArtifactReqDetails artifactDetails, User sdncModifierDetails) throws IOException{
- return deleteInformationalArtifactFromResource( resourceUid, artifactDetails.getUniqueId(), sdncModifierDetails);
- }
-
- public static RestResponse deleteInformationalArtifactFromResource( String resourceUid, String artifactId, User sdncModifierDetails) throws IOException{
- Config config = Utils.getConfig();
- String url = String.format(Urls.UPDATE_OR_DELETE_ARTIFACT_OF_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceUid, artifactId);
- return sendDelete(url, sdncModifierDetails.getUserId());
- }
-
- public static RestResponse deleteServiceApiArtifact(ArtifactReqDetails artifactDetails, String serviceUniqueId, User user) throws Exception
- {
- Config config = Utils.getConfig();
- String url = String.format(Urls.UPDATE_DELETE_SERVICE_API_ARTIFACT, config.getCatalogBeHost(),config.getCatalogBePort(), serviceUniqueId, artifactDetails.getUniqueId());
- RestResponse res = sendDelete(url, user.getUserId());
- logger.debug("Deleting api artifact was finished with response: {}",res.getErrorCode());
- logger.debug("Response body: {}",res.getResponseMessage());
- return res;
- }
-
- //*************** RESOURCE INSTANCE **************
- /**
- * Add DCAE artifacts to resource instance.
- * @param artifactDetails
- * @param sdncModifierDetails
- * @param resourceInstanceId
- * @param serviceId
- * @return
- * @throws IOException
- */
- public static RestResponse addArtifactToResourceInstance(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String resourceInstanceId, String serviceId) throws IOException {
- Config config = Utils.getConfig();
- String url = String.format(Urls.ADD_RESOURCE_INSTANCE_ARTIFACT, config.getCatalogBeHost(), config.getCatalogBePort(), serviceId,resourceInstanceId, artifactDetails.getUniqueId());
- return addArtifactToInstance(artifactDetails, sdncModifierDetails, calculateChecksum(artifactDetails), url);
- }
-
- //*************** COMPONENT **************
-
- public static RestResponse uploadDeploymentArtifact(ArtifactReqDetails artifactDetails, Component component, User sdncModifierDetails) throws IOException {
- Config config = Utils.getConfig();
- Map<String, String> additionalHeaders = null;
- String checksum = ResponseParser.calculateMD5Header(artifactDetails);
- additionalHeaders = new HashMap<String, String>();
- additionalHeaders.put(HttpHeaderEnum.Content_MD5.getValue(), checksum);
-
- ComponentTypeEnum componentType = component.getComponentType();
-
- String url = null;
-
- switch (componentType){
-
- case RESOURCE:
- {
- url = String.format(Urls.UPDATE_OR_DELETE_ARTIFACT_OF_SERVICE, config.getCatalogBeHost(),config.getCatalogBePort(), component.getUniqueId(), artifactDetails.getUniqueId());
-
- break;
- }
- case SERVICE: {
-
- break;
- }
-
- case PRODUCT: {
-
- break;
- }
-
- default: {//dummy
- assertTrue("failed on enum selection", false);
-
- break;
- }
- }
-
-
-
-
- Gson gson = new Gson();
- String jsonBody = gson.toJson(artifactDetails);
-// System.out.println("ArtifactDetails: "+ jsonBody);
-
- RestResponse res = sendPost(url, jsonBody, sdncModifierDetails.getUserId(), acceptHeaderData, additionalHeaders);
- if (res.getErrorCode() == STATUS_CODE_SUCCESS) {
- artifactDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(res));
- }
-// System.out.println("Add artifact was finished with response: "+ res.getErrorCode());
- return res;
- }
-
- public static RestResponse uploadArtifact(ArtifactReqDetails artifactDetails, Component component, User sdncModifierDetails) throws IOException {
- Config config = Utils.getConfig();
- List<String> placeHolderlst = Utils.getListOfResPlaceHoldersDepArtTypes();
- Map<String, String> additionalHeaders = null;
- String checksum = null;
- String url= null;
-//
-//
-// if (artifactDetails.getArtifactGroupType() != null
-// && artifactDetails.getArtifactGroupType().equals("DEPLOYMENT")
-// && placeHolderlst.contains(artifactDetails.getArtifactType())) {
-// Map<String, ArtifactDefinition> deploymentArtifacts = component.getDeploymentArtifacts();
-// ArtifactDefinition artifactDefinition = deploymentArtifacts.get(artifactDetails.getArtifactLabel());
-// artifactDetails.setUniqueId(artifactDefinition.getUniqueId());
-// artifactDetails.setArtifactLabel(artifactDefinition.getArtifactLabel());
-// checksum = ResponseParser.calculateMD5Header(artifactDetails);
-// additionalHeaders = new HashMap<String, String>();
-// additionalHeaders.put(HttpHeaderEnum.Content_MD5.getValue(), checksum);
-// url = String.format(Urls.UPDATE_ARTIFACT_OF_COMPONENT, config.getCatalogBeHost(),
-// config.getCatalogBePort(), ComponentTypeEnum.findParamByType(component.getComponentType()),
-// component.getUniqueId(), artifactDetails.getUniqueId());
-// }
-//
-// else {
- checksum = ResponseParser.calculateMD5Header(artifactDetails);
- additionalHeaders = new HashMap<String, String>();
- additionalHeaders.put(HttpHeaderEnum.Content_MD5.getValue(), checksum);
- url = String.format(Urls.UPLOAD_DELETE_ARTIFACT_OF_COMPONENT, config.getCatalogBeHost(),
- config.getCatalogBePort(), ComponentTypeEnum.findParamByType(component.getComponentType()),
- component.getUniqueId(), artifactDetails.getUniqueId());
-// }
-
- Gson gson = new Gson();
- String jsonBody = gson.toJson(artifactDetails);
-// System.out.println("ArtifactDetails: "+ jsonBody);
-
- RestResponse res = sendPost(url, jsonBody, sdncModifierDetails.getUserId(), acceptHeaderData, additionalHeaders);
- if (res.getErrorCode() == STATUS_CODE_SUCCESS) {
- artifactDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(res));
- }
-// System.out.println("Add artifact was finished with response: "+ res.getErrorCode());
- return res;
- }
-
-
-
-
- //*************** PRIVATE **************
- private static RestResponse deleteInformationalArtifact(User sdncModifierDetails, String url) throws IOException {
- Map<String, String> additionalHeaders = null;
-
- additionalHeaders = new HashMap<String, String>();
-
-
- additionalHeaders.put(HttpHeaderEnum.AUTHORIZATION.getValue(), authorizationHeader);
- additionalHeaders.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci");
-
- return sendDelete(url, sdncModifierDetails.getUserId(), additionalHeaders);
-
-// Gson gson = new Gson();
-//// System.out.println("ArtifactDetails: "+ jsonBody);
-// String jsonBody = gson.toJson(artifactDetails);
-//
-// RestResponse res = sendPost(url, jsonBody, sdncModifierDetails.getUserId(), acceptHeaderData, additionalHeaders);
-// if ((res.getErrorCode() == STATUS_CODE_SUCCESS) || (res.getErrorCode() == STATUS_CODE_CREATED)) {
-// artifactDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(res));
-// }
-//// System.out.println("Add artifact was finished with response: "+ res.getErrorCode());
-// return res;
- }
-
- private static RestResponse updateInformationalArtifact(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String checksum, String url) throws IOException {
- return uploadInformationalArtifact(artifactDetails, sdncModifierDetails, checksum, url);
- }
-
- private static RestResponse uploadInformationalArtifact(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String checksum, String url) throws IOException {
- Map<String, String> additionalHeaders = null;
- if (checksum != null && !checksum.isEmpty()) {
- additionalHeaders = new HashMap<String, String>();
- additionalHeaders.put(HttpHeaderEnum.Content_MD5.getValue(), checksum);
- }
-
- additionalHeaders.put(HttpHeaderEnum.AUTHORIZATION.getValue(), authorizationHeader);
- additionalHeaders.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci");
-
- Gson gson = new Gson();
-// System.out.println("ArtifactDetails: "+ jsonBody);
- String jsonBody = gson.toJson(artifactDetails);
-
- RestResponse res = sendPost(url, jsonBody, sdncModifierDetails.getUserId(), acceptHeaderData, additionalHeaders);
- if ((res.getErrorCode() == STATUS_CODE_SUCCESS) || (res.getErrorCode() == STATUS_CODE_CREATED)) {
- artifactDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(res));
- }
-// System.out.println("Add artifact was finished with response: "+ res.getErrorCode());
- return res;
- }
-
- private static RestResponse addArtifactToInstance(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String checksum, String url) throws IOException {
- Map<String, String> additionalHeaders = null;
- additionalHeaders = new HashMap<String, String>();
- if (checksum != null && !checksum.isEmpty()) {
- additionalHeaders = new HashMap<String, String>();
- additionalHeaders.put(HttpHeaderEnum.Content_MD5.getValue(), checksum);
- }
- additionalHeaders.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json, text/plain, */*");
- additionalHeaders.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json;charset=UTF-8");
-
- Gson gson = new Gson();
- String jsonBody = gson.toJson(artifactDetails);
-
- RestResponse res = sendPost(url, jsonBody, sdncModifierDetails.getUserId(), "application/json, text/plain, */*", additionalHeaders);
- if (res.getErrorCode() == STATUS_CODE_SUCCESS) {
- artifactDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(res));
- }
- return res;
- }
-
- private static RestResponse updateDeploymentArtifact(ArtifactDefinition artifactDefinition, User sdncModifierDetails, String url) throws IOException {
- Map<String, String> additionalHeaders = null;
- additionalHeaders = new HashMap<String, String>();
- additionalHeaders.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json, text/plain, */*");
- additionalHeaders.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json;charset=UTF-8");
-
- Gson gson = new Gson();
- String jsonBody = gson.toJson(artifactDefinition);
-
- RestResponse res = sendPost(url, jsonBody, sdncModifierDetails.getUserId(), "application/json, text/plain, */*", additionalHeaders);
- return res;
- }
-
- private static RestResponse updateDeploymentArtifact(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String url) throws IOException {
- Map<String, String> additionalHeaders = null;
-
- additionalHeaders = new HashMap<String, String>();
- additionalHeaders.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json, text/plain, */*");
- additionalHeaders.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json;charset=UTF-8");
-// additionalHeaders.put(HttpHeaderEnum..getValue(), "application/json;charset=UTF-8");
-
-
- Gson gson = new Gson();
- String jsonBody = gson.toJson(artifactDetails);
-// System.out.println("ArtifactDetails: "+ jsonBody);
-
- RestResponse res = sendPost(url, jsonBody, sdncModifierDetails.getUserId(), "application/json, text/plain, */*", additionalHeaders);
- if (res.getErrorCode() == STATUS_CODE_SUCCESS) {
- artifactDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(res));
- }
-// System.out.println("Add artifact was finished with response: "+ res.getErrorCode());
- return res;
- }
-
- private static RestResponse downloadArtifact(String url, User user, Map<String, String> addionalHeaders,boolean addEcompHeader) throws IOException
- {
- if(addEcompHeader){
- addionalHeaders.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), ecomp);
- }
- return downloadArtifact(url, user, addionalHeaders, acceptOctetStream);
- }
-
- private static RestResponse downloadArtifact(String url, User user, Map<String, String> addionalHeaders, String accept) throws IOException
- {
- addionalHeaders.put(HttpHeaderEnum.ACCEPT.getValue(), accept);
-
- RestResponse res = sendGet(url, user.getUserId(), addionalHeaders);
-// System.out.println("download artifact was finished with response: "+ res.getErrorCode());
-// System.out.println("response is: " + res.getResponse());
- return res;
- }
-
- private static Map<String,Map<String,Object>> getArtifactsListFromResponse(String jsonResponse, String fieldOfArtifactList){
- JSONObject object = (JSONObject)JSONValue.parse(jsonResponse);
- Map<String,Map<String,Object>> map = (Map<String,Map<String,Object>>)object.get(fieldOfArtifactList);
- return map;
- }
-
- public static String calculateChecksum(ArtifactReqDetails artifactDetails) {
- String checksum = null;
- if (artifactDetails.getPayload() != null) {
- checksum = ResponseParser.calculateMD5Header(artifactDetails);
- }
- return checksum;
- }
-
- public static String encodeUrlForDownload(String url){
-
- return url.replaceAll(" ", "%20");
- }
-
- public static String getPartialUrlByArtifactName(ServiceReqDetails serviceDetails,String serviceVersion ,String artifactName){
- return encodeUrlForDownload(String.format(Urls.DISTRIB_DOWNLOAD_SERVICE_ARTIFACT_RELATIVE_URL, ValidationUtils.convertToSystemName(serviceDetails.getName()), serviceVersion, artifactName));
- }
-
- public static String getUniqueIdOfArtifact(RestResponse createResponse, String artifactField, String requieredArtifactLabel) throws Exception
- {
- Map<String, Object> artifact = getArtifactFromRestResponse(createResponse, artifactField, requieredArtifactLabel);
- assertNotNull(artifact);
- return artifact.get("uniqueId").toString();
- }
-
- public static Map<String, Object> getArtifactFromRestResponse(RestResponse response, String artifactField, String requieredArtifactLabel)
- {
- Map<String, Map<String, Object>> map = getArtifactsListFromResponse(response.getResponse(), artifactField);
- return map.get(requieredArtifactLabel);
- }
-
-
-
- public static RestResponse updateInformationalArtifactPayloadOfService(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String serviceUid, String artifactUid) throws IOException
- {
- return updateInformationalArtifactPayloadOfService(artifactDetails, sdncModifierDetails, serviceUid, artifactUid, calculateMD5Header(artifactDetails));
- }
-
- private static RestResponse updateInformationalArtifactPayloadOfService(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String serviceUid, String artifactUid, String checksum) throws IOException
- {
- return updateInformationalArtifactOfService(artifactDetails, sdncModifierDetails, serviceUid, artifactUid, checksum, true);
- }
-
- private static RestResponse updateInformationalArtifactOfService(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String serviceUid, String artifactUid, String checksum, boolean isPayloadUpdate) throws IOException
- {
- Config config = Utils.getConfig();
- Map<String, String> headersMap = prepareHeadersMap(sdncModifierDetails.getUserId());
-
- if (isPayloadUpdate){
- headersMap.put(HttpHeaderEnum.Content_MD5.getValue(), checksum);
- }
-
- Gson gson = new Gson();
- String jsonBody = gson.toJson(artifactDetails);
-
- HttpRequest http = new HttpRequest();
-
- String url = String.format(Urls.UPDATE_OR_DELETE_ARTIFACT_OF_SERVICE, config.getCatalogBeHost(),config.getCatalogBePort(), serviceUid, artifactUid);
- RestResponse res = http.httpSendPost(url, jsonBody, headersMap);
-// System.out.println("update artifact was finished with response: "+ res.getErrorCode());
- return res;
- }
-
- public static String calculateMD5Header(ArtifactReqDetails artifactDetails)
- {
- Gson gson = new Gson();
- String jsonBody = gson.toJson(artifactDetails);
- // calculate MD5 for json body
- return calculateMD5(jsonBody);
-
- }
-
- public static String calculateMD5 (String data){
- String calculatedMd5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(data);
- // encode base-64 result
- byte[] encodeBase64 = Base64.encodeBase64(calculatedMd5.getBytes());
- String encodeBase64Str = new String(encodeBase64);
- return encodeBase64Str;
-
- }
-
-
-
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/AssetRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/AssetRestUtils.java
deleted file mode 100644
index 7cee913b0d..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/AssetRestUtils.java
+++ /dev/null
@@ -1,557 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utils.rest;
-
-import static org.testng.AssertJUnit.assertNotNull;
-import static org.testng.AssertJUnit.assertTrue;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-
-import org.apache.http.HttpResponse;
-import org.apache.http.client.methods.HttpGet;
-import org.apache.http.impl.client.CloseableHttpClient;
-import org.apache.http.impl.client.HttpClients;
-import org.codehaus.jackson.map.ObjectMapper;
-import org.openecomp.sdc.be.datatypes.enums.AssetTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
-import org.openecomp.sdc.be.model.ArtifactDefinition;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.Service;
-import org.openecomp.sdc.ci.tests.api.Urls;
-import org.openecomp.sdc.ci.tests.config.Config;
-import org.openecomp.sdc.ci.tests.datatypes.ArtifactAssetStructure;
-import org.openecomp.sdc.ci.tests.datatypes.AssetStructure;
-import org.openecomp.sdc.ci.tests.datatypes.ResourceAssetStructure;
-import org.openecomp.sdc.ci.tests.datatypes.ResourceDetailedAssetStructure;
-import org.openecomp.sdc.ci.tests.datatypes.ResourceInstanceAssetStructure;
-import org.openecomp.sdc.ci.tests.datatypes.ServiceAssetStructure;
-import org.openecomp.sdc.ci.tests.datatypes.ServiceDetailedAssetStructure;
-import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
-import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest;
-import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
-import org.openecomp.sdc.ci.tests.utils.Utils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.gson.Gson;
-import com.google.gson.JsonArray;
-import com.google.gson.JsonElement;
-import com.google.gson.JsonObject;
-import com.google.gson.JsonParser;
-
-public class AssetRestUtils extends BaseRestUtils {
- static Gson gson = new Gson();
- static ObjectMapper objectMapper = new ObjectMapper();
-
- private static Logger logger = LoggerFactory.getLogger(UserRestUtils.class.getName());
-
- static final String contentTypeHeaderData = "application/json";
- static final String acceptHeaderDate = "application/json";
- static final String basicAuthentication = "Basic Y2k6MTIzNDU2";
- // /sdc/v1/catalog/{services/resources}/{componentUUID}/artifacts/{artifactUUID}
- static final String COMPONENT_ARTIFACT_URL = "/sdc/v1/catalog/%s/%s/artifacts/%s";
- // /sdc/v1/catalog/{services/resources}/{componentUUID}/resourceInstances/{resourceInstanceName}/artifacts/{artifactUUID}
- static final String RESOURCE_INSTANCE_ARTIFACT_URL = "/sdc/v1/catalog/%s/%s/resourceInstances/%s/artifacts/%s";
-
- public static HttpResponse getComponentToscaModel(AssetTypeEnum assetType, String uuid) throws IOException {
- Config config = Utils.getConfig();
- CloseableHttpClient httpclient = HttpClients.createDefault();
- String url = String.format(Urls.GET_TOSCA_MODEL, config.getCatalogBeHost(), config.getCatalogBePort(),
- assetType.getValue(), uuid);
- HttpGet httpGet = new HttpGet(url);
-
- httpGet.addHeader(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci");
- httpGet.addHeader(HttpHeaderEnum.AUTHORIZATION.getValue(), basicAuthentication);
-
- logger.debug("Send GET request to get Tosca model: {}",url);
-
- return httpclient.execute(httpGet);
- }
-
- public static RestResponse getRestResponseComponentToscaModel(AssetTypeEnum assetType, String uuid) throws IOException {
- Config config = Utils.getConfig();
-
- String url = String.format(Urls.GET_TOSCA_MODEL, config.getCatalogBeHost(), config.getCatalogBePort(),
- assetType.getValue(), uuid);
-
- Map<String, String> headersMap = new HashMap<String,String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), authorizationHeader);
- headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci");
-
- HttpRequest http = new HttpRequest();
-
- logger.debug("Send GET request to get Resource Assets: {}",url);
- System.out.println("Send GET request to get Resource Assets: " + url);
-
- logger.debug("Request headers: {}",headersMap);
- System.out.println("Request headers: " + headersMap);
-
- RestResponse sendGetResourceAssets = http.httpSendGet(url, headersMap);
-
- return sendGetResourceAssets;
-
- }
-
- public static RestResponse getComponentListByAssetType(boolean isBasicAuthentication, AssetTypeEnum assetType,
- String... filterArrayString) throws IOException {
- Config config = Utils.getConfig();
- Map<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
- if (isBasicAuthentication) {
- headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), basicAuthentication);
- }
- headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci");
-
- HttpRequest http = new HttpRequest();
- String url = String.format(Urls.GET_ASSET_LIST, config.getCatalogBeHost(), config.getCatalogBePort(),
- assetType.getValue());
- if (filterArrayString != null && filterArrayString.length > 0) {
- url = buildUrlWithFilter(url, filterArrayString);
- }
-
- RestResponse sendGetResourceAssets = http.httpSendGet(url, headersMap);
-
- return sendGetResourceAssets;
- }
-
- public static RestResponse getFilteredComponentList(AssetTypeEnum assetType, String query) throws IOException {
- Config config = Utils.getConfig();
- Map<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
- headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), basicAuthentication);
- headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci");
-
- HttpRequest http = new HttpRequest();
-
- String url = String.format(Urls.GET_FILTERED_ASSET_LIST, config.getCatalogBeHost(), config.getCatalogBePort(),
- assetType.getValue(), query);
-
- logger.debug("Send GET request to get Resource Assets: {}",url);
- logger.debug("Request headers: {}",headersMap);
-
- RestResponse sendGetResourceAssets = http.httpSendGet(url, headersMap);
-
- return sendGetResourceAssets;
- }
-
- public static String buildUrlWithFilter(String url, String[] filterArrayString) {
- StringBuilder sb = new StringBuilder();
- int length = filterArrayString.length;
- int count = 0;
- for (String filterString : filterArrayString) {
- sb.append(filterString);
- count++;
- if (length != count) {
- sb.append("&");
- }
- }
- return url + "?" + sb;
- }
-
- public static RestResponse getAssetMetadataByAssetTypeAndUuid(boolean isBasicAuthentication,
- AssetTypeEnum assetType, String uuid) throws IOException {
-
- Config config = Utils.getConfig();
- Map<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
- if (isBasicAuthentication) {
- headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), basicAuthentication);
- }
- headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci");
-
- HttpRequest http = new HttpRequest();
- String url = String.format(Urls.GET_ASSET_METADATA, config.getCatalogBeHost(), config.getCatalogBePort(),
- assetType.getValue(), uuid);
-
- logger.debug("Send GET request to get Resource Assets: {}",url);
- logger.debug("Request headers: {}",headersMap);
-
- RestResponse sendGetResourceAssets = http.httpSendGet(url, headersMap);
-
- return sendGetResourceAssets;
- }
-
- public static List<ResourceAssetStructure> getResourceAssetList(RestResponse assetResponse) {
- List<ResourceAssetStructure> resourceAssetList = new ArrayList<>();
-
- JsonElement jelement = new JsonParser().parse(assetResponse.getResponse());
- JsonArray componenetArray = (JsonArray) jelement;
- for (JsonElement jElement : componenetArray) {
- ResourceAssetStructure resource = gson.fromJson(jElement, ResourceAssetStructure.class);
- resourceAssetList.add(resource);
- }
- return resourceAssetList;
- }
-
- public static ResourceDetailedAssetStructure getResourceAssetMetadata(RestResponse assetResponse) {
-
- List<ResourceInstanceAssetStructure> resourcesList = new ArrayList<>();
- List<ArtifactAssetStructure> artifactsList = new ArrayList<>();
- ResourceDetailedAssetStructure resourceAssetMetadata = new ResourceDetailedAssetStructure();
- String response = assetResponse.getResponse();
-
- JsonObject jObject = (JsonObject) new JsonParser().parse(response);
- resourceAssetMetadata = gson.fromJson(jObject, ResourceDetailedAssetStructure.class);
-
- setResourceInstanceAssetList(resourcesList, jObject);
- resourceAssetMetadata.setResources(resourcesList);
-
- setArtifactAssetList(artifactsList, jObject);
- resourceAssetMetadata.setArtifacts(artifactsList);
-
- return resourceAssetMetadata;
- }
-
- public static void generalMetadataFieldsValidatior(AssetStructure assetMetadata, Component component) {
-
- assertTrue("Expected resourceUuid is " + component.getUUID() + " actual: " + assetMetadata.getUuid(),
- assetMetadata.getUuid().equals(component.getUUID()));
- assertTrue(
- "Expected resourceInvariantUuid is " + component.getInvariantUUID() + " actual: "
- + assetMetadata.getInvariantUUID(),
- assetMetadata.getInvariantUUID().equals(component.getInvariantUUID()));
- assertTrue("Expected asset name is " + component.getName() + " actual: " + assetMetadata.getName(),
- assetMetadata.getName().equals(component.getName()));
- assertTrue("Expected asset version is " + component.getVersion() + " actual: " + assetMetadata.getVersion(),
- assetMetadata.getVersion().equals(component.getVersion()));
- assertTrue(
- "Expected asset lastUpdaterUserId is " + component.getLastUpdaterUserId() + " actual: "
- + assetMetadata.getLastUpdaterUserId(),
- assetMetadata.getLastUpdaterUserId().equals(component.getLastUpdaterUserId()));
- assertNotNull("Expected asset toscaModel is null", assetMetadata.getToscaModelURL());
- assertTrue(
- "Expected asset category is " + component.getCategories().get(0).getName() + " actual: "
- + assetMetadata.getCategory(),
- assetMetadata.getCategory().equals(component.getCategories().get(0).getName()));
- assertTrue(
- "Expected asset lifeCycleState is " + component.getLifecycleState() + " actual: "
- + assetMetadata.getLifecycleState(),
- assetMetadata.getLifecycleState().equals(component.getLifecycleState().toString()));
-
- }
-
- public static void resourceMetadataValidatior(ResourceDetailedAssetStructure resourceAssetMetadata,
- Resource resource, AssetTypeEnum assetType) {
-
- generalMetadataFieldsValidatior(resourceAssetMetadata, resource);
- assertTrue(
- "Expected asset lastUpdaterFullName is " + resource.getLastUpdaterFullName() + " actual: "
- + resourceAssetMetadata.getLastUpdaterFullName(),
- resourceAssetMetadata.getLastUpdaterFullName().equals(resource.getLastUpdaterFullName()));
- assertTrue(
- "Expected asset subCategory is " + resource.getCategories().get(0).getSubcategories().get(0).getName()
- + " actual: " + resourceAssetMetadata.getSubCategory(),
- resourceAssetMetadata.getSubCategory()
- .equals(resource.getCategories().get(0).getSubcategories().get(0).getName()));
- assertTrue(
- "Expected asset toscaResourceName is " + resource.getToscaResourceName() + " actual: "
- + resourceAssetMetadata.getToscaResourceName(),
- resourceAssetMetadata.getToscaResourceName().equals(resource.getToscaResourceName()));
- assertTrue(
- "Expected asset resourceType is " + resource.getResourceType() + " actual: "
- + resourceAssetMetadata.getResourceType(),
- resourceAssetMetadata.getResourceType().equals(resource.getResourceType().toString()));
- resourceInstanceAssetValidator(resourceAssetMetadata.getResources(), resource, assetType);
- // resourceInstanceAssetValidator(resourceAssetMetadata.getResources(),
- // resource);
- artifactAssetValidator(resourceAssetMetadata.getArtifacts(), resource, assetType);
-
- }
-
- public static void serviceMetadataValidatior(ServiceDetailedAssetStructure serviceAssetMetadata, Service service,
- AssetTypeEnum assetType) {
-
- generalMetadataFieldsValidatior(serviceAssetMetadata, service);
- assertTrue(
- "Expected asset lastUpdaterFullName is " + service.getLastUpdaterFullName() + " actual: "
- + serviceAssetMetadata.getLastUpdaterFullName(),
- serviceAssetMetadata.getLastUpdaterFullName().equals(service.getLastUpdaterFullName()));
- assertTrue(
- "Expected asset distributionStatus is " + service.getDistributionStatus() + " actual: "
- + serviceAssetMetadata.getDistributionStatus(),
- serviceAssetMetadata.getDistributionStatus().equals(service.getDistributionStatus().toString()));
- resourceInstanceAssetValidator(serviceAssetMetadata.getResources(), service, assetType);
- // resourceInstanceAssetValidator(serviceAssetMetadata.getResources(),
- // service);
- artifactAssetValidator(serviceAssetMetadata.getArtifacts(), service, assetType);
-
- }
-
- private static void artifactAssetValidator(List<ArtifactAssetStructure> artifactAssetStructureList,
- Component component, AssetTypeEnum assetType) {
- Map<String, ArtifactDefinition> componentDeploymentArtifacts = component.getDeploymentArtifacts();
- validateArtifactMetadata(componentDeploymentArtifacts, artifactAssetStructureList, component.getUUID(),
- assetType, null);
- }
-
- private static void validateArtifactMetadata(Map<String, ArtifactDefinition> componentDeploymentArtifacts,
- List<ArtifactAssetStructure> artifactAssetStructureList, String componentUuid, AssetTypeEnum assetType,
- String resourceInstanceName) {
-
- for (Entry<String, ArtifactDefinition> componentDeploymentArtifact : componentDeploymentArtifacts.entrySet()) {
- ArtifactAssetStructure artifactAssetStructure = getArtifactMetadata(artifactAssetStructureList,
- componentDeploymentArtifact.getValue().getArtifactUUID());
- ArtifactDefinition componentDeploymentArtifactValue = componentDeploymentArtifact.getValue();
- if (artifactAssetStructure != null) {
- assertTrue(
- "Expected artifact asset artifactName is " + componentDeploymentArtifactValue.getArtifactName()
- + " actual: " + artifactAssetStructure.getArtifactName(),
- componentDeploymentArtifactValue.getArtifactName()
- .equals(artifactAssetStructure.getArtifactName()));
- assertTrue(
- "Expected artifact asset Type is " + componentDeploymentArtifactValue.getArtifactType()
- + " actual: " + artifactAssetStructure.getArtifactType(),
- componentDeploymentArtifactValue.getArtifactType()
- .equals(artifactAssetStructure.getArtifactType()));
- // assertNotNull("Expected artifact asset resourceInvariantUUID
- // is null",
- // resourceInstanceAssetStructure.getResourceInvariantUUID());
- // String expectedArtifactUrl = "/sdc/v1/catalog/" +
- // assetType.getValue() + "/" + componentUuid + "/artifacts/" +
- // componentDeploymentArtifactValue.getArtifactUUID();
- String expectedArtifactUrl = "";
- if (resourceInstanceName == null) {
- expectedArtifactUrl = String.format(COMPONENT_ARTIFACT_URL, assetType.getValue(), componentUuid,
- componentDeploymentArtifactValue.getArtifactUUID());
- } else {
- expectedArtifactUrl = String.format(RESOURCE_INSTANCE_ARTIFACT_URL, assetType.getValue(),
- componentUuid, resourceInstanceName, componentDeploymentArtifactValue.getArtifactUUID());
- }
-
- assertTrue(
- "Expected artifact asset URL is " + expectedArtifactUrl + " actual: "
- + artifactAssetStructure.getArtifactURL(),
- artifactAssetStructure.getArtifactURL().equals(expectedArtifactUrl));
- assertTrue(
- "Expected artifact asset description is " + componentDeploymentArtifactValue.getDescription()
- + " actual: " + artifactAssetStructure.getArtifactDescription(),
- componentDeploymentArtifactValue.getDescription().toString()
- .equals(artifactAssetStructure.getArtifactDescription()));
- assertTrue(
- "Expected artifact asset checkSum is " + componentDeploymentArtifactValue.getArtifactChecksum()
- + " actual: " + artifactAssetStructure.getArtifactChecksum(),
- componentDeploymentArtifactValue.getArtifactChecksum()
- .equals(artifactAssetStructure.getArtifactChecksum()));
- assertTrue(
- "Expected artifact asset version is " + componentDeploymentArtifactValue.getArtifactVersion()
- + " actual: " + artifactAssetStructure.getArtifactVersion(),
- componentDeploymentArtifactValue.getArtifactVersion()
- .equals(artifactAssetStructure.getArtifactVersion()));
- if (componentDeploymentArtifactValue.getTimeout() > 0) {
- assertTrue(
- "Expected artifact asset timeout is " + componentDeploymentArtifactValue.getTimeout()
- + " actual: " + artifactAssetStructure.getArtifactTimeout(),
- componentDeploymentArtifactValue.getTimeout()
- .equals(artifactAssetStructure.getArtifactTimeout()));
- }
-
- } else {
- assertTrue("artifact asset with UUID" + componentDeploymentArtifact.getValue().getArtifactUUID()
- + " not found in get Metadata response", false);
- }
- }
-
- }
-
- private static ArtifactAssetStructure getArtifactMetadata(List<ArtifactAssetStructure> artifactAssetStructureList,
- String artifactUUID) {
- for (ArtifactAssetStructure artifactAssetStructure : artifactAssetStructureList) {
- if (artifactAssetStructure.getArtifactUUID().equals(artifactUUID)) {
- return artifactAssetStructure;
- }
- }
- return null;
- }
-
- private static void resourceInstanceAssetValidator(
- List<ResourceInstanceAssetStructure> resourceInstanceAssetStructures, Component component,
- AssetTypeEnum assetType) {
-
- List<ComponentInstance> componentInstances = component.getComponentInstances();
- if (componentInstances != null) {
- for (ComponentInstance componentInstance : componentInstances) {
- ResourceInstanceAssetStructure resourceInstanceAssetStructure = getResourceInstanceMetadata(
- resourceInstanceAssetStructures, componentInstance.getName());
- if (resourceInstanceAssetStructure != null) {
- assertTrue(
- "Expected RI asset resourceName is " + componentInstance.getComponentName() + " actual: "
- + resourceInstanceAssetStructure.getResourceName(),
- componentInstance.getComponentName()
- .equals(resourceInstanceAssetStructure.getResourceName()));
- assertTrue(
- "Expected RI asset Name is " + componentInstance.getName() + " actual: "
- + resourceInstanceAssetStructure.getResourceInstanceName(),
- componentInstance.getName()
- .equals(resourceInstanceAssetStructure.getResourceInstanceName()));
- assertNotNull("Expected RI asset resourceInvariantUUID is null",
- resourceInstanceAssetStructure.getResourceInvariantUUID());
- assertTrue(
- "Expected RI asset resourceVersion is " + componentInstance.getComponentVersion()
- + " actual: " + resourceInstanceAssetStructure.getResourceVersion(),
- componentInstance.getComponentVersion()
- .equals(resourceInstanceAssetStructure.getResourceVersion()));
- assertTrue(
- "Expected RI asset resourceType is " + componentInstance.getOriginType() + " actual: "
- + resourceInstanceAssetStructure.getResoucreType(),
- componentInstance.getOriginType().toString()
- .equals(resourceInstanceAssetStructure.getResoucreType()));
- assertTrue(
- "Expected RI asset resourceUUID is " + componentInstance.getComponentUid() + " actual: "
- + resourceInstanceAssetStructure.getResourceUUID(),
- componentInstance.getComponentUid()
- .equals(resourceInstanceAssetStructure.getResourceUUID()));
- validateArtifactMetadata(componentInstance.getDeploymentArtifacts(),
- resourceInstanceAssetStructure.getArtifacts(), component.getUUID(), assetType,
- componentInstance.getNormalizedName());
- // validateArtifactMetadata(componentInstance.getDeploymentArtifacts(),
- // resourceInstanceAssetStructure.getArtifacts(),
- // component.getUUID(), AssetTypeEnum.RESOURCES);
- } else {
- assertTrue("resourceInstance asset with UUID" + componentInstance.getComponentUid()
- + " not found in get Metadata response", false);
- }
- }
- }
-
- }
-
- // private static ResourceInstanceAssetStructure
- // getResourceInstanceMetadata(List<ResourceInstanceAssetStructure>
- // resourceInstanceAssetStructures, String componentUid) {
- private static ResourceInstanceAssetStructure getResourceInstanceMetadata(
- List<ResourceInstanceAssetStructure> resourceInstanceAssetStructures, String name) {
- for (ResourceInstanceAssetStructure resourceInstanceAssetStructure : resourceInstanceAssetStructures) {
- if (resourceInstanceAssetStructure.getResourceInstanceName().equals(name)) {
- return resourceInstanceAssetStructure;
- }
- }
- return null;
- }
-
- public static ServiceDetailedAssetStructure getServiceAssetMetadata(RestResponse assetResponse) {
-
- List<ResourceInstanceAssetStructure> resourcesList = new ArrayList<>();
- List<ArtifactAssetStructure> artifactsList = new ArrayList<>();
- ServiceDetailedAssetStructure serviceAssetMetadata;
-
- JsonObject jObject = (JsonObject) new JsonParser().parse(assetResponse.getResponse());
- serviceAssetMetadata = gson.fromJson(jObject, ServiceDetailedAssetStructure.class);
-
- setResourceInstanceAssetList(resourcesList, jObject);
- serviceAssetMetadata.setResources(resourcesList);
-
- setArtifactAssetList(artifactsList, jObject);
- serviceAssetMetadata.setArtifacts(artifactsList);
-
- return serviceAssetMetadata;
- }
-
- public static void setArtifactAssetList(List<ArtifactAssetStructure> artifactsList, JsonObject jObject) {
- JsonArray artifactsArray = jObject.getAsJsonArray("artifacts");
- if (artifactsArray != null) {
- for (JsonElement jElement : artifactsArray) {
- ArtifactAssetStructure artifact = gson.fromJson(jElement, ArtifactAssetStructure.class);
- artifactsList.add(artifact);
- }
- }
- }
-
- public static void setResourceInstanceAssetList(List<ResourceInstanceAssetStructure> resourcesList,
- JsonObject jObject) {
- JsonArray resourcesArray = jObject.getAsJsonArray("resources");
- if (resourcesArray != null) {
- for (JsonElement jElement : resourcesArray) {
- ResourceInstanceAssetStructure resource = gson.fromJson(jElement, ResourceInstanceAssetStructure.class);
- resourcesList.add(resource);
- }
- }
- }
-
- public static List<ServiceAssetStructure> getServiceAssetList(RestResponse assetResponse) {
- List<ServiceAssetStructure> serviceAssetList = new ArrayList<>();
-
- JsonElement jelement = new JsonParser().parse(assetResponse.getResponse());
- JsonArray componenetArray = (JsonArray) jelement;
- for (JsonElement jElement : componenetArray) {
- ServiceAssetStructure service = gson.fromJson(jElement, ServiceAssetStructure.class);
- serviceAssetList.add(service);
- }
- return serviceAssetList;
- }
-
- public static List<String> getResourceNamesList(List<ResourceAssetStructure> resourceAssetList) {
- List<String> assetNamesList = new ArrayList<>();
- for (ResourceAssetStructure resourceAsset : resourceAssetList) {
- assetNamesList.add(resourceAsset.getName());
- }
- return assetNamesList;
- }
-
- public static List<String> getServiceNamesList(List<ServiceAssetStructure> serviceAssetList) {
- List<String> assetNamesList = new ArrayList<>();
- for (ServiceAssetStructure serviceAsset : serviceAssetList) {
- assetNamesList.add(serviceAsset.getName());
- }
- return assetNamesList;
- }
-
- public static void checkResourceTypeInObjectList(List<ResourceAssetStructure> resourceAssetList,
- ResourceTypeEnum resourceType) {
- for (ResourceAssetStructure resourceAsset : resourceAssetList) {
- assertTrue(
- "Expected resourceType is " + resourceType.toString() + " actual: "
- + resourceAsset.getResourceType(),
- resourceAsset.getResourceType().equals(resourceType.toString()));
- }
- }
-
- public static void checkComponentTypeInObjectList(List<ResourceAssetStructure> resourceAssetList,
- ComponentTypeEnum componentType) {
- ComponentTypeEnum actualComponentType;
- for (ResourceAssetStructure resourceAsset : resourceAssetList) {
- actualComponentType = detectComponentType(resourceAsset);
- assertTrue(
- "Expected componentType is " + componentType.getValue() + " actual: " + actualComponentType.getValue(),
- actualComponentType.equals(componentType));
- }
- }
-
- private static ComponentTypeEnum detectComponentType(ResourceAssetStructure resourceAsset) {
- String resourceType = resourceAsset.getResourceType();
- if(ResourceTypeEnum.getType(resourceType) !=null){
- return ComponentTypeEnum.RESOURCE;
- }
- return null;
- }
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/BaseRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/BaseRestUtils.java
deleted file mode 100644
index 080583b901..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/BaseRestUtils.java
+++ /dev/null
@@ -1,263 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utils.rest;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.commons.codec.binary.Base64;
-import org.apache.http.HttpEntity;
-import org.apache.http.client.methods.CloseableHttpResponse;
-import org.apache.http.client.methods.HttpPost;
-import org.apache.http.impl.client.CloseableHttpClient;
-import org.apache.http.impl.client.HttpClients;
-import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
-import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest;
-import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
-import org.openecomp.sdc.ci.tests.utils.validation.BaseValidationUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class BaseRestUtils extends BaseValidationUtils {
- public static final String contentTypeHeaderData = "application/json";
- public static final String acceptHeaderData = "application/json";
- public static final String acceptJsonHeader = "application/json";
- public static final String acceptOctetHeader = "application/octet-stream";
- public static final String authorizationHeader = "Basic " + Base64.encodeBase64String("ci:123456".getBytes());
- public static final String acceptOctetStream = "application/octet-stream";
- public static final String ecomp = "ecomp";
- public static final String authorizationPrefixString = "Basic ";
-
- public static final String RESOURCE_COMPONENT_TYPE = "resources";
- public static final String PRODUCT_COMPONENT_TYPE = "products";
- public static final String SERVICE_COMPONENT_TYPE = "services";
-
- public static final int STATUS_CODE_SUCCESS = 200;
- public static final int STATUS_CODE_CREATED = 201;
- public static final int STATUS_CODE_DELETE = 204;
- public static final int STATUS_CODE_NOT_FOUND = 404;
- public static final int STATUS_CODE_SUCCESS_NO_CONTENT = 204;
- public static final int STATUS_CODE_SUCCESS_DELETE = 204;
- public static final int STATUS_CODE_INVALID_CONTENT = 400;
- public static final int STATUS_CODE_MISSING_DATA = 400;
- public static final int STATUS_CODE_MISSING_INFORMATION = 403;
- public static final int STATUS_CODE_RESTRICTED_ACCESS = 403;
- public static final int STATUS_CODE_ALREADY_EXISTS = 409;
- public static final int STATUS_CODE_RESTRICTED_OPERATION = 409;
- public static final int STATUS_CODE_COMPONENT_NAME_EXCEEDS_LIMIT = 400;
- public static final int STATUS_CODE_MISSING_COMPONENT_NAME = 400;
- public static final int STATUS_CODE_UNSUPPORTED_ERROR = 400;
- public static final int STATUS_CODE_IMPORT_SUCCESS = 201;
- public static final int STATUS_CODE_UPDATE_SUCCESS = 200;
- public static final int RESTRICTED_OPERATION = 409;
- public static final int STATUS_CODE_GET_SUCCESS = 200;
-
- public static final String SUCCESS_MESSAGE = "OK";
- private static Logger logger = LoggerFactory.getLogger(BaseRestUtils.class.getName());
-
- private static byte[] encodeBase64;
-
- // ************* PRIVATE METHODS ************************
-
- protected static Map<String, String> prepareHeadersMap(String userId) {
- return prepareHeadersMap(userId, acceptHeaderData);
- }
-
- protected static Map<String, String> prepareHeadersMap(String userId, String accept) {
- Map<String, String> headersMap = new HashMap<String, String>();
- if (contentTypeHeaderData != null) {
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- }
- if (accept != null) {
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), accept);
- }
- if (userId != null) {
- headersMap.put(HttpHeaderEnum.USER_ID.getValue(), userId);
- }
-
- return headersMap;
- }
-
- // send request
- // GET
- protected static RestResponse sendGet(String url, String userId) throws IOException {
- return sendGet(url, userId, null);
- }
-
- protected static RestResponse sendGet(String url, String userId, Map<String, String> additionalHeaders)
- throws IOException {
- Map<String, String> headersMap = prepareHeadersMap(userId);
- if (additionalHeaders != null) {
- headersMap.putAll(additionalHeaders);
- }
-
- HttpRequest http = new HttpRequest();
- RestResponse getResourceResponse = http.httpSendGet(url, headersMap);
- return getResourceResponse;
- }
-
- public static RestResponse sendGetAndRemoveHeaders(String url, String userId, List<String> headersToRemove)
- throws IOException {
- Map<String, String> headersMap = prepareHeadersMap(userId);
- if (headersToRemove != null) {
- for (String header : headersToRemove) {
- headersMap.remove(header);
- }
- }
-
- HttpRequest http = new HttpRequest();
- RestResponse getResourceResponse = http.httpSendGet(url, headersMap);
- return getResourceResponse;
- }
-
- // PUT
- protected static RestResponse sendPut(String url, String userBodyJson, String userId, String cont)
- throws IOException {
- Map<String, String> headersMap = prepareHeadersMap(userId, cont);
-
- HttpRequest http = new HttpRequest();
- RestResponse updateResourceResponse = http.httpSendByMethod(url, "PUT", userBodyJson, headersMap);
- return updateResourceResponse;
- }
-
- // POST
- public static RestResponse sendPost(String url, String userBodyJson, String userId, String accept)
- throws IOException {
- return sendPost(url, userBodyJson, userId, accept, null);
- }
-
- protected static RestResponse sendPost(String url, String userBodyJson, String userId, String accept,
- Map<String, String> additionalHeaders) throws IOException {
- Map<String, String> headersMap = prepareHeadersMap(userId, accept);
- if (additionalHeaders != null) {
- headersMap.putAll(additionalHeaders);
- }
- HttpRequest http = new HttpRequest();
- RestResponse postResourceResponse = http.httpSendPost(url, userBodyJson, headersMap);
- return postResourceResponse;
- }
-
- // used form complex requests like import categories..
- protected static RestResponse sendPost(String url, HttpEntity entity, String userId, String accept)
- throws IOException {
- RestResponse postResponse = new RestResponse();
- CloseableHttpResponse response = null;
- CloseableHttpClient client = null;
- try {
- client = HttpClients.createDefault();
- HttpPost httpPost = new HttpPost(url);
-
- httpPost.addHeader("USER_ID", userId);
- httpPost.setEntity(entity);
- response = client.execute(httpPost);
- HttpEntity responseEntity = response.getEntity();
- int statusCode = response.getStatusLine().getStatusCode();
-
- postResponse.setErrorCode(statusCode);
- StringBuffer sb = new StringBuffer();
- try {
- BufferedReader in = new BufferedReader(new InputStreamReader(responseEntity.getContent()));
- String inputLine;
- while ((inputLine = in.readLine()) != null) {
- sb.append(inputLine);
- }
- in.close();
- } catch (Exception e) {
- logger.debug("response body is null");
- }
- postResponse.setResponse(sb.toString());
- } finally {
- try {
- if (response != null) {
- response.close();
- }
-
- } catch (IOException e) {
- logger.debug("failed to close client or response: ", e);
- }
- try {
- if (client != null) {
- client.close();
- }
- } catch (IOException e) {
- logger.debug("failed to close client or response: ", e);
- }
- }
- return postResponse;
- }
-
- // DELETE
- protected static RestResponse sendDelete(String url, String userId) throws IOException {
- return sendDelete(url, userId, null);
- }
-
- protected static RestResponse sendDelete(String url, String userId, Map<String, String> additionalHeaders) throws IOException {
- Map<String, String> headersMap = prepareHeadersMap(userId);
- if (additionalHeaders != null) {
- headersMap.putAll(additionalHeaders);
- }
-
- HttpRequest http = new HttpRequest();
- RestResponse deleteResourceResponse = http.httpSendDelete(url, headersMap);
- return deleteResourceResponse;
- }
-
- /*
- * // ------ protected static Boolean checkErrorCode(RestResponse
- * deleteResponse) { if (deleteResponse.getErrorCode() ==
- * STATUS_CODE_SUCCESS || deleteResponse.getErrorCode() ==
- * STATUS_CODE_DELETE) { return true; } return false; }
- *
- * // *** STATUS CODE VALIDATION UTIITIES **** public static void
- * checkStatusCode(RestResponse response, String assertMessage, boolean AND,
- * int... statuses) { int statusCode = response.getErrorCode(); for (int
- * status : statuses) { if (AND && statusCode != status) {
- * Assert.fail(assertMessage + " status: " + statusCode); } else if
- * (statusCode == status) { return; } } if (!AND) {
- * Assert.fail(assertMessage + " status: " + statusCode); } }
- *
- * public static void checkDeleteResponse(RestResponse response) {
- * checkStatusCode(response,"delete request failed",false,STATUS_CODE_DELETE
- * ,STATUS_CODE_NOT_FOUND, STATUS_CODE_SUCCESS); // STATUS_CODE_SUCCESS for
- * deActivate user }
- *
- * public static void checkCreateResponse(RestResponse response) {
- * checkStatusCode(response, "create request failed", false,
- * STATUS_CODE_CREATED); }
- */
- public static String encodeUrlForDownload(String url) {
- return url.replaceAll(" ", "%20");
- }
-
- public static Map<String, String> addAuthorizeHeader(String userName, String password) {
- String userCredentials = userName + ":" + password;
- encodeBase64 = Base64.encodeBase64(userCredentials.getBytes());
- String encodedUserCredentials = authorizationPrefixString + new String(encodeBase64);
- Map<String, String> authorizationHeader = new HashMap<String, String>();
- authorizationHeader.put(HttpHeaderEnum.AUTHORIZATION.getValue(), encodedUserCredentials);
- return authorizationHeader;
- }
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CatalogRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CatalogRestUtils.java
deleted file mode 100644
index 528e82a9f5..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CatalogRestUtils.java
+++ /dev/null
@@ -1,87 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utils.rest;
-
-import java.io.IOException;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-
-import org.openecomp.sdc.ci.tests.api.Urls;
-import org.openecomp.sdc.ci.tests.config.Config;
-import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
-import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
-import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
-import org.openecomp.sdc.ci.tests.utils.Utils;
-
-public class CatalogRestUtils extends BaseRestUtils {
-
- public static RestResponse getAbstractResources() throws IOException {
-
- Config config = Utils.getConfig();
- String url = String.format(Urls.GET_ALL_ABSTRACT_RESOURCES, config.getCatalogBeHost(),
- config.getCatalogBePort());
-
- return sendGet(url, UserRoleEnum.DESIGNER.getUserId());
- }
-
- public static RestResponse getCatalog() throws IOException {
- return getCatalog(UserRoleEnum.DESIGNER.getUserId());
- }
-
- public static RestResponse getCatalog(String userId) throws IOException {
- Config config = Utils.getConfig();
- String url = String.format(Urls.GET_CATALOG_DATA, config.getCatalogBeHost(), config.getCatalogBePort());
- return sendGet(url, userId);
- }
-
- public static RestResponse getCatalog(String userId, List<String> excludeList) throws IOException {
- Config config = Utils.getConfig();
- String url = String.format(Urls.GET_CATALOG_DATA, config.getCatalogBeHost(), config.getCatalogBePort());
- StringBuilder sb = new StringBuilder();
- sb.append(url).append("?");
- Optional.ofNullable(excludeList).orElse(Collections.emptyList()).forEach(type -> sb.append("excludeTypes="+type+"&"));
- return sendGet(sb.toString(), userId);
- }
-
- public static RestResponse getAllCategoriesTowardsCatalogBe() throws IOException {
-
- Config config = Utils.getConfig();
- String url = String.format(Urls.GET_ALL_CATEGORIES, config.getCatalogBeHost(), config.getCatalogBePort(),
- BaseRestUtils.RESOURCE_COMPONENT_TYPE);
-
- return sendGet(url, UserRoleEnum.DESIGNER.getUserId());
- }
-
- public static RestResponse getAllCategoriesTowardsCatalogFeWithUuid(String uuid) throws IOException {
-
- Config config = Utils.getConfig();
- String url = String.format(Urls.GET_ALL_CATEGORIES_FE, config.getCatalogFeHost(), config.getCatalogFePort(),
- BaseRestUtils.RESOURCE_COMPONENT_TYPE);
-
- Map<String, String> additionalHeaders = new HashMap<String, String>();
- additionalHeaders.put(HttpHeaderEnum.X_ECOMP_REQUEST_ID_HEADER.getValue(), uuid);
-
- return sendGet(url, UserRoleEnum.DESIGNER.getUserId(), additionalHeaders);
- }
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CategoryRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CategoryRestUtils.java
deleted file mode 100644
index f5791efbb3..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CategoryRestUtils.java
+++ /dev/null
@@ -1,308 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utils.rest;
-
-import java.io.IOException;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.http.entity.mime.MultipartEntityBuilder;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.model.category.CategoryDefinition;
-import org.openecomp.sdc.be.model.category.GroupingDefinition;
-import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
-import org.openecomp.sdc.ci.tests.api.Urls;
-import org.openecomp.sdc.ci.tests.config.Config;
-import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest;
-import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
-import org.openecomp.sdc.ci.tests.utils.Utils;
-
-import com.google.gson.Gson;
-import com.google.gson.reflect.TypeToken;
-
-public class CategoryRestUtils extends BaseRestUtils {
-
- private static final int STATUS_CODE_CREATED = 201;
-
- private static Gson gson = new Gson();
-
- public static RestResponse createCategory(CategoryDefinition categoryDefinition, User sdncModifierDetails,
- String categoryType) throws Exception {
- Config config = Utils.getConfig();
- String url = String.format(Urls.CREATE_CATEGORY, config.getCatalogBeHost(), config.getCatalogBePort(),
- categoryType);
- String bodyJson = gson.toJson(categoryDefinition);
- RestResponse addCategoryResponse = BaseRestUtils.sendPost(url, bodyJson, sdncModifierDetails.getUserId(),
- acceptHeaderData);
- if (addCategoryResponse.getErrorCode().intValue() == STATUS_CODE_CREATED)
- categoryDefinition.setUniqueId(
- ResponseParser.getValueFromJsonResponse(addCategoryResponse.getResponse(), "uniqueId"));
- return addCategoryResponse;
- }
-
- // GET categories
- public static RestResponse getAllCategories(User sdncModifierDetails, String categoryType) throws Exception {
- Config config = Utils.getConfig();
- String url = String.format(Urls.GET_ALL_CATEGORIES, config.getCatalogBeHost(), config.getCatalogBePort(),
- categoryType);
- String userId = sdncModifierDetails.getUserId();
- Map<String, String> headersMap = prepareHeadersMap(userId);
- HttpRequest http = new HttpRequest();
- // System.out.println(url);
- RestResponse getCategotyResponse = http.httpSendGet(url, headersMap);
- return getCategotyResponse;
- }
-
- public static RestResponse getAllCategoriesTowardsFe(User sdncModifierDetails, String categoryType)
- throws Exception {
- Config config = Utils.getConfig();
- String url = String.format(Urls.GET_ALL_CATEGORIES_FE, config.getCatalogFeHost(), config.getCatalogFePort(),
- categoryType);
- String userId = sdncModifierDetails.getUserId();
- Map<String, String> headersMap = prepareHeadersMap(userId);
- HttpRequest http = new HttpRequest();
- // System.out.println(url);
- RestResponse getCategotyResponse = http.httpSendGet(url, headersMap);
- return getCategotyResponse;
- }
-
- // Delete Category
- public static RestResponse deleteCategory(String categoryId, String userId, String categoryType)
- throws Exception {
- Config config = Utils.getConfig();
- String url = String.format(Urls.DELETE_CATEGORY, config.getCatalogBeHost(), config.getCatalogBePort(),
- categoryType, categoryId);
- url = url.replace("#", "%23"); // HEX
- url = url.replace(" ", "%20"); // HEX
- RestResponse deleteCategoryResponse = sendDelete(url, userId);
- return deleteCategoryResponse;
- }
-
- public static RestResponse createSubCategory(SubCategoryDefinition subCategory, CategoryDefinition parentCategory,
- User sdncModifierDetails, String categoryType) throws Exception {
- // categoryType = service/resource/product
- Config config = Utils.getConfig();
- String url = String.format(Urls.CREATE_SUB_CATEGORY, config.getCatalogBeHost(), config.getCatalogBePort(),
- categoryType, parentCategory.getUniqueId());
- String bodyJson = gson.toJson(subCategory);
- RestResponse createSubCategoryPost = BaseRestUtils.sendPost(url, bodyJson, sdncModifierDetails.getUserId(),
- acceptHeaderData);
- if (createSubCategoryPost.getErrorCode().intValue() == STATUS_CODE_CREATED)
- subCategory.setUniqueId(
- ResponseParser.getValueFromJsonResponse(createSubCategoryPost.getResponse(), "uniqueId"));
-
- return createSubCategoryPost;
- }
-
- public static RestResponse deleteSubCategory(String subCategoryId, String categoryId, String psUserId,
- String categoryType) throws Exception {
- Config config = Utils.getConfig();
- String url = String.format(Urls.DELETE_SUB_CATEGORY, config.getCatalogBeHost(), config.getCatalogBePort(),
- categoryType, categoryId, subCategoryId);
- url = url.replace("#", "%23"); // HEX
- url = url.replace(" ", "%20"); // HEX
- RestResponse deleteSubCategoryResponse = sendDelete(url, psUserId);
- return deleteSubCategoryResponse;
- }
-
- public static RestResponse deleteGrouping(String groupId, String subCategoryId, String categoryId, String psUserId,
- String categoryType) throws Exception {
-
- Config config = Utils.getConfig();
- String url = String.format(Urls.DELETE_GROUPING, config.getCatalogBeHost(), config.getCatalogBePort(),
- categoryType, categoryId, subCategoryId, groupId);
- url = url.replace("#", "%23"); // HEX
- url = url.replace(" ", "%20"); // HEX
- RestResponse deleteGroupResponse = sendDelete(url, psUserId);
- return deleteGroupResponse;
- }
-
- public static RestResponse createServiceCategoryHttpCspAtuUidIsMissing(CategoryDefinition categoryDataDefinition,
- User sdncModifierDetails) throws Exception {
-
- Config config = Utils.getConfig();
- String url = String.format(Urls.CREATE_CATEGORY, config.getCatalogBeHost(), config.getCatalogBePort(),
- SERVICE_COMPONENT_TYPE);
-
- Map<String, String> headersMap = prepareHeadersMap(sdncModifierDetails.getUserId());
- headersMap.remove("USER_ID");
- Gson gson = new Gson();
- String userBodyJson = gson.toJson(categoryDataDefinition);
- HttpRequest http = new HttpRequest();
- // System.out.println(url);
- // System.out.println(userBodyJson);
- RestResponse createCatergoryResponse = http.httpSendPost(url, userBodyJson, headersMap);
- return createCatergoryResponse;
- }
-
- public static RestResponse createSubCategoryHttpCspAtuUidIsMissing(SubCategoryDefinition subCategory,
- CategoryDefinition parentCategory, User sdncModifierDetails, String categoryType) throws Exception {
- // categoryType = service/resource/product
- Config config = Utils.getConfig();
- String url = String.format(Urls.CREATE_SUB_CATEGORY, config.getCatalogBeHost(), config.getCatalogBePort(),
- categoryType, parentCategory.getUniqueId());
- String userId = sdncModifierDetails.getUserId();
- Map<String, String> headersMap = prepareHeadersMap(userId);
- headersMap.remove("USER_ID");
- Gson gson = new Gson();
- String subCatJson = gson.toJson(subCategory);
- HttpRequest http = new HttpRequest();
- // System.out.println(url);
- // System.out.println(subCatJson);
- RestResponse addCategoryResponse = http.httpSendPost(url, subCatJson, headersMap);
- return addCategoryResponse;
- }
-
- public static RestResponse deleteCatergoryHttpCspAtuUidIsMissing(CategoryDefinition categoryDataDefinition,
- User sdncModifierDetails) throws Exception {
-
- Config config = Utils.getConfig();
- String url = String.format(Urls.DELETE_CONSUMER, config.getCatalogBeHost(), config.getCatalogBePort(),
- categoryDataDefinition.getName());
-
- String userId = sdncModifierDetails.getUserId();
- Map<String, String> headersMap = prepareHeadersMap(userId);
- headersMap.remove("USER_ID");
- Gson gson = new Gson();
- String userBodyJson = gson.toJson(categoryDataDefinition);
- HttpRequest http = new HttpRequest();
- // System.out.println(url);
- // System.out.println(userBodyJson);
- RestResponse deleteCategotyResponse = http.httpSendDelete(url, headersMap);
- return deleteCategotyResponse;
- }
-
- public static RestResponse createGrouping(GroupingDefinition grouping, SubCategoryDefinition subCategory,
- CategoryDefinition parentCategory, User sdncModifierDetails, String categoryType) throws Exception {
- Config config = Utils.getConfig();
- String url = String.format(Urls.CREATE_GROUPING, config.getCatalogBeHost(), config.getCatalogBePort(),
- categoryType, parentCategory.getUniqueId(), subCategory.getUniqueId());
- String bodyJson = gson.toJson(grouping);
- RestResponse addGroupingResponse = BaseRestUtils.sendPost(url, bodyJson, sdncModifierDetails.getUserId(),
- acceptHeaderData);
- return addGroupingResponse;
- }
-
- public static RestResponse importCategories(MultipartEntityBuilder mpBuilder, String userId) throws IOException {
- Config config = Utils.getConfig();
- String url = String.format(Urls.IMPORT_CATEGORIES, config.getCatalogBeHost(), config.getCatalogBePort());
-
- RestResponse importResponse = BaseRestUtils.sendPost(url, mpBuilder.build(), userId, acceptHeaderData);
- return importResponse;
- }
-
- public static int getMatchingCategoriesNum(RestResponse getAllCategoryRest, CategoryDefinition categoryDefinition) {
- String response = getAllCategoryRest.getResponse();
- Gson gson = new Gson();
- List<CategoryDefinition> categoryDefinitions = gson.fromJson(response,
- new TypeToken<List<CategoryDefinition>>() {
- }.getType());
- int categoriesNum = 0;
- String catName = categoryDefinition.getName();
- for (CategoryDefinition elem : categoryDefinitions) {
- if (elem.getName().equals(catName)) {
- categoryDefinition.setUniqueId(elem.getUniqueId());
- categoriesNum++;
- }
- }
-
- return categoriesNum;
- }
-
- public static int getMatchingSubCategoriesNum(RestResponse getAllCategoryRest, String parentCategoryId,
- SubCategoryDefinition expectedSubCategoryDefinition) {
-
- String response = getAllCategoryRest.getResponse();
- Gson gson = new Gson();
- List<CategoryDefinition> categoryDefinitions = gson.fromJson(response,
- new TypeToken<List<CategoryDefinition>>() {
- }.getType());
- int subCatNum = 0;
- String subCatName = expectedSubCategoryDefinition.getName();
- for (CategoryDefinition elem : categoryDefinitions) {
- if (elem.getUniqueId().equals(parentCategoryId)) {
- List<SubCategoryDefinition> subCategories = elem.getSubcategories();
- if (subCategories != null) {
- for (SubCategoryDefinition subCategoryDataDefinition : subCategories) {
- if (subCatName.equals(subCategoryDataDefinition.getName())) {
- expectedSubCategoryDefinition.setUniqueId(subCategoryDataDefinition.getUniqueId());
- subCatNum++;
- }
- }
- }
-
- }
- }
- return subCatNum;
- }
-
- public static int getMatchingGroupingNum(RestResponse getAllCategoryRest, String parentCategoryId,
- String subCategoryId, GroupingDefinition expectedGroupingDefinition) {
-
- String response = getAllCategoryRest.getResponse();
- Gson gson = new Gson();
- List<CategoryDefinition> categoryDefinitions = gson.fromJson(response,
- new TypeToken<List<CategoryDefinition>>() {
- }.getType());
- int groupingNum = 0;
- String groupingName = expectedGroupingDefinition.getName();
- for (CategoryDefinition elem : categoryDefinitions) {
- if (elem.getUniqueId().equals(parentCategoryId)) {
- List<SubCategoryDefinition> subCategories = elem.getSubcategories();
- if (subCategories != null) {
- for (SubCategoryDefinition subCategoryDataDefinition : subCategories) {
- // if
- // (subCategoryId.equals(subCategoryDataDefinition.getUniqueId()))
- // {
- if (subCategoryId.equals(subCategoryDataDefinition.getUniqueId())
- && subCategoryDataDefinition.getGroupings() != null) {
- List<GroupingDefinition> grouping = subCategoryDataDefinition.getGroupings();
- for (GroupingDefinition groupingDataDefinition : grouping) {
- if (groupingName.equals(groupingDataDefinition.getName())) {
- expectedGroupingDefinition.setUniqueId(groupingDataDefinition.getUniqueId());
- groupingNum++;
- }
- }
-
- }
- }
- }
-
- }
- }
- return groupingNum;
- }
-
- public enum CategoryAuditJsonKeysEnum {
- ACTION("ACTION"), MODIFIER("MODIFIER"), CATEGORY_NAME("CATEGORY_NAME"), SUB_CATEGORY_NAME("SUB_CATEGORY_NAME"), GROUPING_NAME("GROUPING_NAME"), RESOURCE_TYPE("RESOURCE_TYPE"), ECOMP_USER("ECOMP_USER"), STATUS("STATUS"), DESCRIPTION("DESCRIPTION"), DETAILS("DETAILS");
-
- private String auditJsonKeyName;
-
- private CategoryAuditJsonKeysEnum(String auditJsonKeyName) {
- this.auditJsonKeyName = auditJsonKeyName;
- }
-
- public String getAuditJsonKeyName() {
- return auditJsonKeyName.toLowerCase();
- }
- }
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CommonRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CommonRestUtils.java
deleted file mode 100644
index e691efdbca..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CommonRestUtils.java
+++ /dev/null
@@ -1,22 +0,0 @@
-package org.openecomp.sdc.ci.tests.utils.rest;
-
-import org.openecomp.sdc.ci.tests.api.Urls;
-import org.openecomp.sdc.ci.tests.config.Config;
-import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
-import org.openecomp.sdc.ci.tests.utils.Utils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class CommonRestUtils extends BaseRestUtils {
-
- private static Logger logger = LoggerFactory.getLogger(CommonRestUtils.class.getName());
-
- public static RestResponse getHealthCheck() throws Exception {
-
- Config config = Utils.getConfig();
- String url = String.format(Urls.GET_HEALTH_CHECK_VIA_PROXY, config.getCatalogFeHost(), config.getCatalogFePort());
-
- return sendGet(url, null);
-
- }
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ComponentInstanceRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ComponentInstanceRestUtils.java
deleted file mode 100644
index 21332a253c..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ComponentInstanceRestUtils.java
+++ /dev/null
@@ -1,304 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utils.rest;
-
-import static org.testng.Assert.assertTrue;
-
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.ComponentInstanceProperty;
-import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.ci.tests.api.Urls;
-import org.openecomp.sdc.ci.tests.config.Config;
-import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
-import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
-import org.openecomp.sdc.ci.tests.utils.Utils;
-
-import com.google.gson.Gson;
-
-public class ComponentInstanceRestUtils extends BaseRestUtils {
- public static String acceptHeaderDate = "application/json";
- static Config config = Config.instance();
- public static Gson gson = new Gson();
-
- // 'componentType' can be 'services' or 'resources'
-
- public static RestResponse createComponentInstance(ComponentInstanceReqDetails componentInstanceReqDetails,
- User sdncModifierDetails, Component component) throws Exception {
- return createComponentInstance(componentInstanceReqDetails, sdncModifierDetails, component.getUniqueId(),
- component.getComponentType());
- }
-
- public static RestResponse createComponentInstance(ComponentInstanceReqDetails componentInstanceReqDetails,
- User sdncModifierDetails, String componentId, ComponentTypeEnum componentType) throws Exception {
-
- return createComponentInstance(componentInstanceReqDetails, sdncModifierDetails, componentId,
- ComponentTypeEnum.findParamByType(componentType));
- }
-
- public static RestResponse createComponentInstance(ComponentInstanceReqDetails componentInstanceReqDetails,
- User sdncModifierDetails, String componentId, String componentType) throws Exception {
- Config config = Utils.getConfig();
- String userId = sdncModifierDetails.getUserId();
- String serviceBodyJson = gson.toJson(componentInstanceReqDetails);
- String url = String.format(Urls.CREATE_COMPONENT_INSTANCE, config.getCatalogBeHost(), config.getCatalogBePort(),
- componentType, componentId);
- RestResponse createResourceInstance = sendPost(url, serviceBodyJson, userId, acceptHeaderData);
- if (createResourceInstance.getErrorCode().equals(BaseRestUtils.STATUS_CODE_CREATED)) {
- String uniqueId = ResponseParser.getValueFromJsonResponse(createResourceInstance.getResponse(), "uniqueId");
- componentInstanceReqDetails.setUniqueId(uniqueId);
- // Gson gson = new Gson();
- // ResourceInstanceReqDetails fromJson =
- // gson.fromJson(createResourceInstance.getResponse(),
- // ResourceInstanceReqDetails.class);
- // componentInstanceReqDetails.setUniqueId(fromJson.getUniqueId());
- }
- return createResourceInstance;
- }
-
- public static RestResponse getComponentInstances(ComponentTypeEnum type, String componentId, User user)
- throws IOException {
-
- Config config = Utils.getConfig();
-
- Map<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderData);
- headersMap.put(HttpHeaderEnum.USER_ID.getValue(), user.getUserId());
-
- String url = String.format(Urls.GET_COMPONENT_INSTANCES, config.getCatalogBeHost(), config.getCatalogBePort(),
- ComponentTypeEnum.findParamByType(type), componentId);
-
- RestResponse sendGetServerRequest = sendGet(url, user.getUserId(), headersMap);
-
- return sendGetServerRequest;
-
- }
-
- public static RestResponse getComponentInstancePropertiesByID(ComponentTypeEnum type, String componentId, String resourceInstanceId, User user)
- throws IOException {
-
- Config config = Utils.getConfig();
-
- Map<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderData);
- headersMap.put(HttpHeaderEnum.USER_ID.getValue(), user.getUserId());
-
- String url = String.format(Urls.GET_COMPONENT_INSTANCE_PROPERTIES_BY_ID, config.getCatalogBeHost(), config.getCatalogBePort(),
- ComponentTypeEnum.findParamByType(type), componentId, resourceInstanceId);
-
- return sendGet(url, user.getUserId(), headersMap);
-
- }
-
- public static RestResponse deleteComponentInstance(User sdncModifierDetails, String componentId,
- String resourceInstanceId, ComponentTypeEnum componentType) throws Exception {
-
- return deleteComponentInstance(sdncModifierDetails, componentId, resourceInstanceId,
- ComponentTypeEnum.findParamByType(componentType));
- }
-
- public static RestResponse deleteComponentInstance(User sdncModifierDetails, String componentId,
- String resourceInstanceId, String componentTypeString) throws Exception {
- Config config = Utils.getConfig();
- String userId = sdncModifierDetails.getUserId();
- String url = String.format(Urls.DELETE_COMPONENT_INSTANCE, config.getCatalogBeHost(), config.getCatalogBePort(),
- componentTypeString, componentId, resourceInstanceId);
- RestResponse sendCreateUserRequest = sendDelete(url, userId);
- return sendCreateUserRequest;
- }
-
- public static RestResponse updateComponentInstance(ComponentInstanceReqDetails componentInstanceReqDetails,
- User sdncModifierDetails, String componentId, ComponentTypeEnum componentType) throws IOException {
-
- Config config = Utils.getConfig();
- String userId = sdncModifierDetails.getUserId();
- String serviceBodyJson = gson.toJson(componentInstanceReqDetails);
- String url = String.format(Urls.UPDATE_COMPONENT_INSTANCE, config.getCatalogBeHost(), config.getCatalogBePort(),
- ComponentTypeEnum.findParamByType(componentType), componentId,
- componentInstanceReqDetails.getUniqueId());
- RestResponse updateResourceInstance = sendPost(url, serviceBodyJson, userId, acceptHeaderData);
- return updateResourceInstance;
- }
- public static RestResponse updateComponentInstance(ComponentInstance componentInstance,
- User sdncModifierDetails, String componentId, ComponentTypeEnum componentType) throws IOException {
-
- Config config = Utils.getConfig();
- String userId = sdncModifierDetails.getUserId();
- String serviceBodyJson = gson.toJson(componentInstance);
- String url = String.format(Urls.UPDATE_COMPONENT_INSTANCE, config.getCatalogBeHost(), config.getCatalogBePort(),
- ComponentTypeEnum.findParamByType(componentType), componentId,
- componentInstance.getUniqueId());
- RestResponse updateResourceInstance = sendPost(url, serviceBodyJson, userId, acceptHeaderData);
- return updateResourceInstance;
- }
-
- public static RestResponse updateMultipleComponentInstance(
- List<ComponentInstanceReqDetails> componentInstanceReqDetailsList, User sdncModifierDetails,
- String componentId, ComponentTypeEnum componentType) throws IOException {
- Config config = Utils.getConfig();
- String userId = sdncModifierDetails.getUserId();
- String serviceBodyJson = gson.toJson(componentInstanceReqDetailsList.toArray());
- String url = String.format(Urls.UPDATE_MULTIPLE_COMPONENT_INSTANCE, config.getCatalogBeHost(),
- config.getCatalogBePort(), ComponentTypeEnum.findParamByType(componentType), componentId);
- RestResponse updateResourceInstance = sendPost(url, serviceBodyJson, userId, acceptHeaderData);
- return updateResourceInstance;
- }
-
- public static RestResponse associateInstances(RequirementCapabilityRelDef relation, User sdncModifierDetails,
- String componentId, ComponentTypeEnum componentTypeEnum) throws IOException {
-
- Config config = Utils.getConfig();
-
- String componentType = "";
- switch (componentTypeEnum) {
- case RESOURCE:
- componentType = ComponentTypeEnum.RESOURCE_PARAM_NAME;
- break;
- case SERVICE:
- componentType = ComponentTypeEnum.SERVICE_PARAM_NAME;
- break;
- default:
- break;
- }
- String serviceBodyJson = gson.toJson(relation);
- String url = String.format(Urls.ASSOCIATE_RESOURCE_INSTANCE, config.getCatalogBeHost(),
- config.getCatalogBePort(), componentType, componentId);
-
- RestResponse associateInstance = sendPost(url, serviceBodyJson, sdncModifierDetails.getUserId(),
- acceptHeaderData);
- return associateInstance;
-
- }
-
- public static RestResponse dissociateInstances(RequirementCapabilityRelDef relation, User sdncModifierDetails,
- String componentId, ComponentTypeEnum componentTypeEnum) throws IOException {
-
- Config config = Utils.getConfig();
-
- String componentType = "";
- switch (componentTypeEnum) {
- case RESOURCE:
- componentType = ComponentTypeEnum.RESOURCE_PARAM_NAME;
- break;
- case SERVICE:
- componentType = ComponentTypeEnum.SERVICE_PARAM_NAME;
- break;
- default:
- break;
- }
- String serviceBodyJson = gson.toJson(relation);
- String url = String.format(Urls.DISSOCIATE_RESOURCE_INSTANCE, config.getCatalogBeHost(),
- config.getCatalogBePort(), componentType, componentId);
-
- RestResponse associateInstance = sendPut(url, serviceBodyJson, sdncModifierDetails.getUserId(),
- acceptHeaderData);
- return associateInstance;
-
- }
-
- public static void checkComponentInstanceType(RestResponse response, String expectedComponentType) {
- String actualComponentType = ResponseParser.getComponentTypeFromResponse(response);
- assertTrue(expectedComponentType.equals(actualComponentType),
- "Failed. expected: " + expectedComponentType + ", actual: " + actualComponentType + "/");
- }
-
- public static RestResponse updatePropertyValueOnResourceInstance(Component component, ComponentInstance instDetails,
- User user, ComponentInstanceProperty updatedInstanceProperty) throws IOException {
-
- Config config = Utils.getConfig();
-
- Map<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderData);
- headersMap.put(HttpHeaderEnum.USER_ID.getValue(), user.getUserId());
-
- String url = String.format(Urls.UPDATE_PROPERTY_TO_RESOURCE_INSTANCE, config.getCatalogBeHost(),
- config.getCatalogBePort(), ComponentTypeEnum.findParamByType(component.getComponentType()),
- component.getUniqueId(), instDetails.getUniqueId());
- String body = gson.toJson(updatedInstanceProperty);
-
- RestResponse sendGetServerRequest = sendPost(url, body, user.getUserId(), acceptHeaderData);
- return sendGetServerRequest;
-
- }
-
- public static RestResponse changeComponentInstanceVersion(Component container,
- ComponentInstance componentInstanceToReplace, Component newInstance, User sdncModifierDetails)
- throws Exception {
-
- return changeComponentInstanceVersion(container.getUniqueId(), componentInstanceToReplace, newInstance,
- sdncModifierDetails, container.getComponentType());
- }
-
- public static RestResponse changeComponentInstanceVersion(String containerUID,
- ComponentInstance componentInstanceToReplace, Component component, User sdncModifierDetails,
- ComponentTypeEnum componentType) throws IOException {
-
- Config config = Utils.getConfig();
- String resourceUid = ("{\"componentUid\":\"" + component.getUniqueId() + "\"}");
- String url = String.format(Urls.CHANGE_RESOURCE_INSTANCE_VERSION, config.getCatalogBeHost(),
- config.getCatalogBePort(), ComponentTypeEnum.findParamByType(componentType), containerUID,
- componentInstanceToReplace.getUniqueId());
- RestResponse changeResourceInstanceVersion = sendPost(url, resourceUid, sdncModifierDetails.getUserId(),
- acceptHeaderData);
-
- if (changeResourceInstanceVersion.getErrorCode() == 200
- || changeResourceInstanceVersion.getErrorCode() == 201) {
- Gson gson = new Gson();
- // ResourceInstanceReqDetails
- // convertResourceInstanceResponseToJavaObject =
- // ResponseParser.convertResourceInstanceResponseToJavaObject(createResourceInstance.getResponse());
- ComponentInstanceReqDetails fromJson = gson.fromJson(changeResourceInstanceVersion.getResponse(),
- ComponentInstanceReqDetails.class);
-
- componentInstanceToReplace.setUniqueId(fromJson.getUniqueId());
-
- }
-
- return changeResourceInstanceVersion;
-
- }
-
- public static RestResponse changeComponentInstanceVersion(String componentUniqueId,
- String serviceInstanceToReplaceUniqueId, String serviceUniqueId, User sdncModifierDetails,
- ComponentTypeEnum componentType) throws IOException {
- Config config = Utils.getConfig();
- String resourceUid = ("{\"componentUid\":\"" + serviceUniqueId + "\"}");
- String url = String.format(Urls.CHANGE_RESOURCE_INSTANCE_VERSION, config.getCatalogBeHost(),
- config.getCatalogBePort(), ComponentTypeEnum.findParamByType(componentType), componentUniqueId,
- serviceInstanceToReplaceUniqueId);
- RestResponse changeResourceInstanceVersion = sendPost(url, resourceUid, sdncModifierDetails.getUserId(),
- acceptHeaderData);
- return changeResourceInstanceVersion;
-
- }
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ComponentRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ComponentRestUtils.java
deleted file mode 100644
index 8237819d7a..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ComponentRestUtils.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utils.rest;
-
-import java.io.IOException;
-
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.model.CapReqDef;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.ci.tests.api.Urls;
-import org.openecomp.sdc.ci.tests.config.Config;
-import org.openecomp.sdc.ci.tests.datatypes.ComponentReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.ProductReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
-import org.openecomp.sdc.ci.tests.utils.Utils;
-
-public class ComponentRestUtils extends BaseRestUtils {
- public static RestResponse getComponentRequirmentsCapabilities(User sdncModifierDetails,
- ComponentReqDetails componentReqDetails) throws IOException {
- Config config = Utils.getConfig();
- ComponentTypeEnum componentType = null;
- if (componentReqDetails instanceof ResourceReqDetails) {
- componentType = ComponentTypeEnum.RESOURCE;
- } else if (componentReqDetails instanceof ServiceReqDetails) {
- componentType = ComponentTypeEnum.SERVICE;
- } else if (componentReqDetails instanceof ProductReqDetails) {
- componentType = ComponentTypeEnum.PRODUCT;
- }
- String url = String.format(Urls.GET_COMPONENT_REQUIRMENTS_CAPABILITIES, config.getCatalogBeHost(),
- config.getCatalogBePort(), ComponentTypeEnum.findParamByType(componentType),
- componentReqDetails.getUniqueId());
- return sendGet(url, sdncModifierDetails.getUserId());
- }
-
- public static CapReqDef getAndParseComponentRequirmentsCapabilities(User user, ComponentReqDetails componentDetails)
- throws IOException {
- RestResponse getComponentReqCap = getComponentRequirmentsCapabilities(user, componentDetails);
- ResourceRestUtils.checkSuccess(getComponentReqCap);
- CapReqDef capReqDef = ResponseParser.parseToObject(getComponentReqCap.getResponse(), CapReqDef.class);
- return capReqDef;
- }
-
- public static RestResponse validateConformanceLevel(String uuid, String userId) throws Exception {
- Config config = Utils.getConfig();
- String url = String.format(Urls.VALIDATE_CONFORMANCE_LEVEL, config.getCatalogBeHost(), config.getCatalogBePort(), "services", uuid);
-
- RestResponse res = sendGet(url, userId);
- return res;
- }
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ConsumerRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ConsumerRestUtils.java
deleted file mode 100644
index 71735d5a4a..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ConsumerRestUtils.java
+++ /dev/null
@@ -1,245 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utils.rest;
-
-import static org.testng.AssertJUnit.assertEquals;
-
-import java.util.Map;
-
-import org.codehaus.jackson.map.ObjectMapper;
-import org.openecomp.sdc.be.datatypes.elements.ConsumerDataDefinition;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.ci.tests.api.Urls;
-import org.openecomp.sdc.ci.tests.config.Config;
-import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest;
-import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
-import org.openecomp.sdc.ci.tests.utils.Utils;
-
-import com.google.gson.Gson;
-
-public class ConsumerRestUtils extends BaseRestUtils {
-
- public static final int STATUS_CODE_SUCCESS = 200;
- public static final int STATUS_CODE_CREATED = 201;
- public static final int STATUS_CODE_DELETE = 204;
- public static final int STATUS_CODE_NOT_FOUND = 404;
- Utils utils = new Utils();
- private static Long expectedsLastupdatedtime;
- private static Long expectedLastAuthenticationTime;
-
- public static RestResponse createConsumer(ConsumerDataDefinition consumerDataDefinition, User sdncModifierDetails)
- throws Exception {
-
- Config config = Utils.getConfig();
- String url = String.format(Urls.CREATE_CONSUMER, config.getCatalogBeHost(), config.getCatalogBePort());
-
- String userId = sdncModifierDetails.getUserId();
-
- Map<String, String> headersMap = prepareHeadersMap(userId);
-
- Gson gson = new Gson();
- String userBodyJson = gson.toJson(consumerDataDefinition);
-
- HttpRequest http = new HttpRequest();
- // System.out.println(url);
- // System.out.println(userBodyJson);
- RestResponse createConsumerResponse = http.httpSendPost(url, userBodyJson, headersMap);
- if (createConsumerResponse.getErrorCode() == STATUS_CODE_CREATED) {
- ConsumerDataDefinition getConsumerDataObject = parseComsumerResp(createConsumerResponse);
- consumerDataDefinition
- .setConsumerDetailsLastupdatedtime(getConsumerDataObject.getConsumerDetailsLastupdatedtime());
- consumerDataDefinition
- .setConsumerLastAuthenticationTime(getConsumerDataObject.getConsumerLastAuthenticationTime());
- consumerDataDefinition.setLastModfierAtuid(getConsumerDataObject.getLastModfierAtuid());
- }
- return createConsumerResponse;
- }
-
- public static RestResponse createConsumerHttpCspAtuUidIsMissing(ConsumerDataDefinition consumerDataDefinition,
- User sdncModifierDetails) throws Exception {
-
- Config config = Utils.getConfig();
- String url = String.format(Urls.CREATE_CONSUMER, config.getCatalogBeHost(), config.getCatalogBePort());
-
- String userId = sdncModifierDetails.getUserId();
- Map<String, String> headersMap = prepareHeadersMap(userId);
- headersMap.remove("USER_ID");
- Gson gson = new Gson();
- String userBodyJson = gson.toJson(consumerDataDefinition);
- HttpRequest http = new HttpRequest();
- // System.out.println(url);
- // System.out.println(userBodyJson);
- RestResponse createConsumerResponse = http.httpSendPost(url, userBodyJson, headersMap);
- if (createConsumerResponse.getErrorCode() == STATUS_CODE_CREATED) {
- ConsumerDataDefinition getConsumerDataObject = parseComsumerResp(createConsumerResponse);
- consumerDataDefinition
- .setConsumerDetailsLastupdatedtime(getConsumerDataObject.getConsumerDetailsLastupdatedtime());
- consumerDataDefinition
- .setConsumerLastAuthenticationTime(getConsumerDataObject.getConsumerLastAuthenticationTime());
- consumerDataDefinition.setLastModfierAtuid(getConsumerDataObject.getLastModfierAtuid());
- }
- return createConsumerResponse;
- }
-
- public static RestResponse deleteConsumerHttpCspAtuUidIsMissing(ConsumerDataDefinition consumerDataDefinition,
- User sdncModifierDetails) throws Exception {
-
- Config config = Utils.getConfig();
- String url = String.format(Urls.DELETE_CONSUMER, config.getCatalogBeHost(), config.getCatalogBePort(),
- consumerDataDefinition.getConsumerName());
-
- String userId = sdncModifierDetails.getUserId();
- Map<String, String> headersMap = prepareHeadersMap(userId);
- headersMap.remove("USER_ID");
- Gson gson = new Gson();
- String userBodyJson = gson.toJson(consumerDataDefinition);
- HttpRequest http = new HttpRequest();
- // System.out.println(url);
- // System.out.println(userBodyJson);
- RestResponse deleteConsumerResponse = http.httpSendDelete(url, headersMap);
- return deleteConsumerResponse;
- }
-
- public static ConsumerDataDefinition parseComsumerResp(RestResponse restResponse) throws Exception {
-
- String bodyToParse = restResponse.getResponse();
- ObjectMapper mapper = new ObjectMapper();
- try {
- ConsumerDataDefinition component = mapper.readValue(bodyToParse, ConsumerDataDefinition.class);
- return component;
- } catch (Exception e) {
- e.printStackTrace();
- }
-
- return null;
- }
-
- public static RestResponse deleteConsumer(ConsumerDataDefinition consumerDataDefinition, User sdncModifierDetails)
- throws Exception {
-
- Config config = Utils.getConfig();
- String url = String.format(Urls.DELETE_CONSUMER, config.getCatalogBeHost(), config.getCatalogBePort(),
- consumerDataDefinition.getConsumerName());
-
- String userId = sdncModifierDetails.getUserId();
-
- Map<String, String> headersMap = prepareHeadersMap(userId);
- HttpRequest http = new HttpRequest();
- // System.out.println(url);
- RestResponse deleteConsumerResponse = http.httpSendDelete(url, headersMap);
- return deleteConsumerResponse;
- }
-
- public static RestResponse getConsumer(ConsumerDataDefinition consumerDataDefinition, User sdncModifierDetails)
- throws Exception {
-
- Config config = Utils.getConfig();
- String url = String.format(Urls.GET_CONSUMER, config.getCatalogBeHost(), config.getCatalogBePort(),
- consumerDataDefinition.getConsumerName());
-
- String userId = sdncModifierDetails.getUserId();
-
- Map<String, String> headersMap = prepareHeadersMap(userId);
- HttpRequest http = new HttpRequest();
- // System.out.println(url);
- RestResponse getConsumerResponse = http.httpSendGet(url, headersMap);
- return getConsumerResponse;
- }
-
- public static void validateConsumerReqVsResp(ConsumerDataDefinition consumerDefinition,
- ConsumerDataDefinition getConsumerDataObject) {
-
- String expected;
-
- expected = consumerDefinition.getConsumerName();
- assertEquals("consumer name - ", expected, getConsumerDataObject.getConsumerName());
-
- expected = consumerDefinition.getConsumerPassword().toLowerCase();
- assertEquals("consumer password - ", expected, getConsumerDataObject.getConsumerPassword());
-
- expected = consumerDefinition.getLastModfierAtuid();
- assertEquals("consumer Last Modfier Atuid - ", expected, getConsumerDataObject.getLastModfierAtuid());
-
- expected = consumerDefinition.getConsumerSalt();
- assertEquals("consumer Salt - ", expected, getConsumerDataObject.getConsumerSalt());
-
- expectedsLastupdatedtime = consumerDefinition.getConsumerDetailsLastupdatedtime();
- assertEquals("consumer Last updated time - ", expectedsLastupdatedtime,
- getConsumerDataObject.getConsumerDetailsLastupdatedtime());
-
- expectedLastAuthenticationTime = consumerDefinition.getConsumerLastAuthenticationTime();
- assertEquals("consumer Last authentication time - ", expectedLastAuthenticationTime,
- getConsumerDataObject.getConsumerLastAuthenticationTime());
- }
-
- ///// New
- public enum EcompConsumerAuditJsonKeysEnum {
- ACTION("ACTION"), MODIFIER("MODIFIER"), ECOMP_USER("ECOMP_USER"), STATUS("STATUS"), DESC("DESCRIPTION");
- private String auditJsonKeyName;
-
- private EcompConsumerAuditJsonKeysEnum(String auditJsonKeyName) {
- this.auditJsonKeyName = auditJsonKeyName;
- }
-
- public String getAuditJsonKeyName() {
- return auditJsonKeyName.toLowerCase();
- }
- }
-
- /*
- * protected void resourceArtifatAuditSuccess(String action,
- * ArtifactReqDetails artifact, ResourceReqDetails resourceDetails , User
- * user) throws Exception { ExpectedResourceAuditJavaObject
- * expectedResourceAuditJavaObject =
- * Convertor.constructFieldsForAuditValidation(resourceDetails,
- * resourceDetails.getVersion(), user); String auditAction = action;
- * expectedResourceAuditJavaObject.setAction(auditAction);
- * expectedResourceAuditJavaObject.setPrevState("");
- * expectedResourceAuditJavaObject.setPrevVersion("");
- * expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.
- * NOT_CERTIFIED_CHECKOUT).toString());
- * expectedResourceAuditJavaObject.setStatus("200");
- * expectedResourceAuditJavaObject.setDesc("OK");
- * expectedResourceAuditJavaObject.setArtifactName(artifact.getArtifactName(
- * )); AuditUtils.validateAudit(expectedResourceAuditJavaObject,
- * auditAction, null); }
- */
-
- /*
- * protected void resourceArtifatValidateAuditWithErrorMessage(String
- * actionStatus, ResourceReqDetails resourceDetails, String auditAction,
- * String setCurrState, Object ... variables)throws Exception { ErrorInfo
- * errorInfo = utils.parseYaml(actionStatus);
- * ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject =
- * Convertor.constructFieldsForAuditValidation(resourceDetails,
- * resourceDetails.getVersion(), sdncUserDetails);
- * expectedResourceAuditJavaObject.setAction(auditAction);
- * expectedResourceAuditJavaObject.setPrevState("");
- * expectedResourceAuditJavaObject.setPrevVersion("");
- * expectedResourceAuditJavaObject.setCurrState(setCurrState);
- * expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString())
- * ;
- * expectedResourceAuditJavaObject.setDesc(errorInfo.getAuditDesc(variables)
- * ); expectedResourceAuditJavaObject.setArtifactName("");
- * AuditUtils.validateAudit(expectedResourceAuditJavaObject, auditAction,
- * null); }
- */
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/EcompUserRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/EcompUserRestUtils.java
deleted file mode 100644
index ec40c13894..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/EcompUserRestUtils.java
+++ /dev/null
@@ -1,252 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utils.rest;
-
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.openecomp.portalsdk.core.restful.domain.EcompRole;
-import org.openecomp.portalsdk.core.restful.domain.EcompUser;
-import org.openecomp.sdc.ci.tests.api.Urls;
-import org.openecomp.sdc.ci.tests.config.Config;
-import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
-import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest;
-import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
-import org.openecomp.sdc.ci.tests.run.StartTest;
-import org.openecomp.sdc.ci.tests.utils.Utils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.gson.Gson;
-
-public class EcompUserRestUtils extends BaseRestUtils {
-
- static Gson gson = new Gson();
- private static Logger logger = LoggerFactory.getLogger(UserRestUtils.class.getName());
-
- static String contentTypeHeaderData = "application/json";
- static String acceptHeaderDate = "application/json";
- static String ecompUsername = "12345";
- static String ecompPassword = "12345";
-
- public EcompUserRestUtils() {
- super();
-
- StartTest.enableLogger();
- }
-
- public static RestResponse pushUser(EcompUser ecompUser) throws IOException {
- Config config = Utils.getConfig();
-
- Map<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
- headersMap.put(HttpHeaderEnum.ECOMP_USERNAME.getValue(), ecompUsername);
- headersMap.put(HttpHeaderEnum.ECOMP_PASSWORD.getValue(), ecompPassword);
-
- String userBodyJson = gson.toJson(ecompUser);
-
- HttpRequest http = new HttpRequest();
- String url = String.format(Urls.ECOMP_PUSH_USER, config.getCatalogBeHost(), config.getCatalogBePort());
-
- logger.debug("Send POST request to create user: {}",url);
- logger.debug("User body: {}",userBodyJson);
- logger.debug("User headers: {}",headersMap);
-
- RestResponse sendPushUserResponse = http.httpSendPost(url, userBodyJson, headersMap);
-
- return sendPushUserResponse;
- }
-
- /*
- * loginId - equals to userId
- */
- public static RestResponse editUser(String loginId, EcompUser ecompUser) throws IOException {
- Config config = Utils.getConfig();
-
- Map<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
- headersMap.put(HttpHeaderEnum.ECOMP_USERNAME.getValue(), ecompUsername);
- headersMap.put(HttpHeaderEnum.ECOMP_PASSWORD.getValue(), ecompPassword);
-
- String userBodyJson = gson.toJson(ecompUser);
-
- HttpRequest http = new HttpRequest();
- String url = String.format(Urls.ECOMP_EDIT_USER, config.getCatalogBeHost(), config.getCatalogBePort(), loginId);
-
- logger.debug("Send POST request to edit user: {}",url);
- logger.debug("User body: {}",userBodyJson);
- logger.debug("User headers: {}",headersMap);
-
- RestResponse sendEditUserResponse = http.httpSendPost(url, userBodyJson, headersMap);
-
- return sendEditUserResponse;
- }
-
- /*
- * loginId - equals to userId
- */
- public static RestResponse getUser(String loginId) throws IOException {
- Config config = Utils.getConfig();
-
- Map<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
- headersMap.put(HttpHeaderEnum.ECOMP_USERNAME.getValue(), ecompUsername);
- headersMap.put(HttpHeaderEnum.ECOMP_PASSWORD.getValue(), ecompPassword);
-
- HttpRequest http = new HttpRequest();
- String url = String.format(Urls.ECOMP_GET_USER, config.getCatalogBeHost(), config.getCatalogBePort(), loginId);
-
- logger.debug("Send GET request to get user: {}",url);
- logger.debug("User headers: {}",headersMap);
-
- RestResponse sendGetUserRequest = http.httpSendGet(url, headersMap);
-
- return sendGetUserRequest;
- }
-
- public static RestResponse getAllUsers() throws IOException {
- Config config = Utils.getConfig();
-
- Map<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
- headersMap.put(HttpHeaderEnum.ECOMP_USERNAME.getValue(), ecompUsername);
- headersMap.put(HttpHeaderEnum.ECOMP_PASSWORD.getValue(), ecompPassword);
-
- HttpRequest http = new HttpRequest();
- String url = String.format(Urls.ECOMP_GET_ALL_USERS, config.getCatalogBeHost(), config.getCatalogBePort());
-
- logger.debug("Send POST request to get all users: {}",url);
- logger.debug("User headers: {}",headersMap);
-
- RestResponse sendGetAllUsersRequest = http.httpSendGet(url, headersMap);
-
- return sendGetAllUsersRequest;
- }
-
- public static RestResponse getAllAvailableRoles() throws IOException {
- Config config = Utils.getConfig();
-
- Map<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
- headersMap.put(HttpHeaderEnum.ECOMP_USERNAME.getValue(), ecompUsername);
- headersMap.put(HttpHeaderEnum.ECOMP_PASSWORD.getValue(), ecompPassword);
-
- HttpRequest http = new HttpRequest();
- String url = String.format(Urls.ECOMP_GET_ALL_AVAILABLE_ROLES, config.getCatalogBeHost(),
- config.getCatalogBePort());
-
- logger.debug("Send GET request to get all available roles: {}",url);
- logger.debug("User headers: {}",headersMap);
-
- RestResponse sendUpdateUserRequest = http.httpSendGet(url, headersMap);
-
- return sendUpdateUserRequest;
- }
-
- /*
- * loginId - equals to userId
- */
- public static RestResponse pushUserRoles(String loginId, List<EcompRole> roles) throws IOException {
- Config config = Utils.getConfig();
-
- Map<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
- headersMap.put(HttpHeaderEnum.ECOMP_USERNAME.getValue(), ecompUsername);
- headersMap.put(HttpHeaderEnum.ECOMP_PASSWORD.getValue(), ecompPassword);
-
- String roleBodyJson = gson.toJson(roles);
-
- HttpRequest http = new HttpRequest();
- String url = String.format(Urls.ECOMP_PUSH_USER_ROLES, config.getCatalogBeHost(), config.getCatalogBePort(),
- loginId);
-
- logger.debug("Send POST request to push user role: {}",url);
- logger.debug("Roles body: {}",roleBodyJson);
- logger.debug("Request headers: {}",headersMap);
-
- RestResponse sendpushUserRolesResponse = http.httpSendPost(url, roleBodyJson, headersMap);
-
- return sendpushUserRolesResponse;
- }
-
- /*
- * loginId - equals to userId
- */
- public static RestResponse getUserRoles(String loginId) throws IOException {
- Config config = Utils.getConfig();
-
- Map<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
- headersMap.put(HttpHeaderEnum.ECOMP_USERNAME.getValue(), ecompUsername);
- headersMap.put(HttpHeaderEnum.ECOMP_PASSWORD.getValue(), ecompPassword);
-
- HttpRequest http = new HttpRequest();
- String url = String.format(Urls.ECOMP_GET_USER_ROLES, config.getCatalogBeHost(), config.getCatalogBePort(),
- loginId);
-
- logger.debug("Send GET request to get user roles: {}",url);
- logger.debug("User headers: {}",headersMap);
-
- RestResponse sendGetUserRolesRequest = http.httpSendGet(url, headersMap);
-
- return sendGetUserRolesRequest;
- }
-
- // TODO !!!!!!!!!!!!!!
- /*
- * Ask Eli if implementation of users is needed DELETE ECOMP USER
- */
-
- /*
- * public static void main(String[] args) { EcompUser ecompUser = new
- * EcompUser(); ecompUser.setFirstName("Test");
- * ecompUser.setLastName("Testovich");
- * ecompUser.setEmail("ttes@intl.sdc.com"); ecompUser.setLoginId("tt0004");
- * ecompUser.setActive(true);
- *
- * EcompRole roleToUpdate = new EcompRole(); roleToUpdate.setId(new
- * Long(6)); roleToUpdate.setName("PRODUCT_STRATEGIST"); List<EcompRole>
- * listOfRoles = new LinkedList<>(); listOfRoles.add(roleToUpdate);
- *
- * try {
- * System.out.println("\n-----------------------------\n Testing pushUser");
- * System.out.println(pushUser(ecompUser));
- * System.out.println("\n-----------------------------\n Testing editUser");
- * System.out.println("\n-----------------------------\n Testing getUser");
- * // System.out.println(getUser(ecompUser.getLoginId())); System.out.
- * println("\n-----------------------------\n Testing getAllUsers"); //
- * System.out.println(getAllUsers()); System.out.
- * println("\n-----------------------------\n Testing getAllAvailableRoles"
- * ); // System.out.println(getAllAvailableRoles().toString()); System.out.
- * println("\n-----------------------------\n Testing pushUserRoles"); //
- * println("\n-----------------------------\n Testing getUserRoles"); //
- * TODO Auto-generated catch block e.printStackTrace(); } }
- */
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/GroupRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/GroupRestUtils.java
deleted file mode 100644
index d79c8e002c..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/GroupRestUtils.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utils.rest;
-
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.Map;
-
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.ci.tests.api.Urls;
-import org.openecomp.sdc.ci.tests.config.Config;
-import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
-import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
-import org.openecomp.sdc.ci.tests.utils.Utils;
-
-import com.google.gson.Gson;
-
-public class GroupRestUtils extends BaseRestUtils {
- public static String acceptHeaderDate = "application/json";
- static Config config = Config.instance();
- public static Gson gson = new Gson();
-
- public static RestResponse getGroupById(Component component, String groupId, User user) throws IOException {
-
- Config config = Utils.getConfig();
-
- Map<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderData);
- headersMap.put(HttpHeaderEnum.USER_ID.getValue(), user.getUserId());
-
- String url = String.format(Urls.GET_GROUP_BY_ID, config.getCatalogBeHost(), config.getCatalogBePort(),
- ComponentTypeEnum.findParamByType(component.getComponentType()), component.getUniqueId(), groupId);
-
- RestResponse sendGetServerRequest = sendGet(url, user.getUserId(), headersMap);
-
- return sendGetServerRequest;
-
- }
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ImportRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ImportRestUtils.java
deleted file mode 100644
index 407141622e..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ImportRestUtils.java
+++ /dev/null
@@ -1,399 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utils.rest;
-
-import static org.testng.AssertJUnit.assertEquals;
-import static org.testng.AssertJUnit.assertNotNull;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.StringWriter;
-import java.nio.file.FileSystems;
-import java.nio.file.Files;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-
-import org.apache.commons.io.IOUtils;
-import org.apache.http.HttpEntity;
-import org.apache.http.client.ClientProtocolException;
-import org.apache.http.client.methods.CloseableHttpResponse;
-import org.apache.http.client.methods.HttpPost;
-import org.apache.http.entity.ContentType;
-import org.apache.http.entity.mime.MultipartEntityBuilder;
-import org.apache.http.entity.mime.content.FileBody;
-import org.apache.http.entity.mime.content.StringBody;
-import org.apache.http.impl.client.CloseableHttpClient;
-import org.apache.http.impl.client.HttpClients;
-import org.codehaus.jettison.json.JSONException;
-import org.openecomp.sdc.be.dao.rest.HttpRestClient;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.ci.tests.api.Urls;
-import org.openecomp.sdc.ci.tests.config.Config;
-import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo;
-import org.openecomp.sdc.ci.tests.datatypes.enums.ImportTestTypesEnum;
-import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum;
-import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
-import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest;
-import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
-import org.openecomp.sdc.ci.tests.utils.Utils;
-import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
-import org.openecomp.sdc.common.rest.api.RestResponseAsByteArray;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class ImportRestUtils extends BaseRestUtils {
-
- private static Logger log = LoggerFactory.getLogger(ImportRestUtils.class.getName());
- private static Properties downloadCsarHeaders = new Properties();
-
- static {
- downloadCsarHeaders.put("Accept", "application/octet-stream");
- }
-
- @SuppressWarnings("unused")
- private static Integer importNormativeResource(NormativeTypesEnum resource, UserRoleEnum userRole)
- throws IOException {
- Config config = Utils.getConfig();
- CloseableHttpResponse response = null;
- MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
-
- mpBuilder.addPart("resourceZip", new FileBody(getTestZipFile(resource.getFolderName())));
- mpBuilder.addPart("resourceMetadata",
- new StringBody(getTestJsonStringOfFile(resource.getFolderName(), resource.getFolderName() + ".json"),
- ContentType.APPLICATION_JSON));
-
- String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE, config.getCatalogBeHost(),
- config.getCatalogBePort());
-
- CloseableHttpClient client = HttpClients.createDefault();
- try {
- HttpPost httpPost = new HttpPost(url);
- httpPost.addHeader("USER_ID", userRole.getUserId());
- httpPost.setEntity(mpBuilder.build());
- response = client.execute(httpPost);
- return response.getStatusLine().getStatusCode();
- } finally {
- closeResponse(response);
- closeHttpClient(client);
-
- }
- }
-
- /*
- * public static RestResponse importResourceByName(String resourceName, User
- * user) throws IOException { Config config = Utils.getConfig();
- * CloseableHttpResponse response = null; MultipartEntityBuilder mpBuilder =
- * MultipartEntityBuilder.create();
- *
- * mpBuilder.addPart("resourceZip", new
- * FileBody(getTestZipFile(resourceName)));
- * mpBuilder.addPart("resourceMetadata", new
- * StringBody(getTestJsonStringOfFile(resourceName, resourceName + ".json"),
- * ContentType.APPLICATION_JSON));
- *
- * String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE,
- * config.getCatalogBeHost(), config.getCatalogBePort());
- *
- * CloseableHttpClient client = HttpClients.createDefault(); try { HttpPost
- * httpPost = new HttpPost(url); RestResponse restResponse = new
- * RestResponse(); httpPost.addHeader("USER_ID", user.getUserId());
- * httpPost.setEntity(mpBuilder.build()); response =
- * client.execute(httpPost); HttpEntity entity = response.getEntity();
- * String responseBody = null; if (entity != null) { InputStream instream =
- * entity.getContent(); StringWriter writer = new StringWriter();
- * IOUtils.copy(instream, writer); responseBody = writer.toString(); try {
- *
- * } finally { instream.close(); } }
- *
- * restResponse.setErrorCode(response.getStatusLine().getStatusCode());
- * restResponse.setResponse(responseBody); if (restResponse.getErrorCode()
- * == STATUS_CODE_CREATED ){
- *
- * }
- *
- * return restResponse;
- *
- * } finally { closeResponse(response); closeHttpClient(client);
- *
- * }
- *
- * }
- */
-
- public static RestResponse importResourceByName(ResourceReqDetails resourceDetails, User importer)
- throws Exception {
- Config config = Utils.getConfig();
- CloseableHttpResponse response = null;
- MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
-
- mpBuilder.addPart("resourceZip", new FileBody(getTestZipFile(resourceDetails.getName())));
- mpBuilder.addPart("resourceMetadata",
- new StringBody(getTestJsonStringOfFile(resourceDetails.getName(), resourceDetails.getName() + ".json"),
- ContentType.APPLICATION_JSON));
-
- String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE, config.getCatalogBeHost(),
- config.getCatalogBePort());
-
- CloseableHttpClient client = HttpClients.createDefault();
- try {
- HttpPost httpPost = new HttpPost(url);
- RestResponse restResponse = new RestResponse();
- httpPost.addHeader("USER_ID", importer.getUserId());
- httpPost.setEntity(mpBuilder.build());
- response = client.execute(httpPost);
- HttpEntity entity = response.getEntity();
- String responseBody = null;
- if (entity != null) {
- InputStream instream = entity.getContent();
- StringWriter writer = new StringWriter();
- IOUtils.copy(instream, writer);
- responseBody = writer.toString();
- try {
-
- } finally {
- instream.close();
- }
- }
-
- restResponse.setErrorCode(response.getStatusLine().getStatusCode());
- restResponse.setResponse(responseBody);
-
- if (restResponse.getErrorCode() == STATUS_CODE_CREATED) {
- resourceDetails.setUUID(ResponseParser.getUuidFromResponse(restResponse));
- resourceDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(restResponse));
- resourceDetails.setVersion(ResponseParser.getVersionFromResponse(restResponse));
- resourceDetails.setCreatorUserId(importer.getUserId());
- resourceDetails.setCreatorFullName(importer.getFullName());
- }
-
- return restResponse;
-
- } finally {
- closeResponse(response);
- closeHttpClient(client);
-
- }
-
- }
-
- public static RestResponse importNewResourceByName(String resourceName, UserRoleEnum userRole) throws IOException {
- Config config = Utils.getConfig();
-
- MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
-
- mpBuilder.addPart("resourceZip", new FileBody(getTestZipFile(resourceName)));
- mpBuilder.addPart("resourceMetadata", new StringBody(
- getTestJsonStringOfFile(resourceName, resourceName + ".json"), ContentType.APPLICATION_JSON));
- HttpEntity requestEntity = mpBuilder.build();
- String url = String.format(Urls.IMPORT_USER_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort());
- Map<String, String> headers = new HashMap<String, String>();
- headers.put("USER_ID", userRole.getUserId());
-
- return HttpRequest.sendHttpPostWithEntity(requestEntity, url, headers);
- }
-
- public static RestResponse importNormativeResourceByName(String resourceName, UserRoleEnum userRole)
- throws IOException {
- Config config = Utils.getConfig();
-
- MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
-
- mpBuilder.addPart("resourceZip", new FileBody(getTestZipFile(resourceName)));
- mpBuilder.addPart("resourceMetadata", new StringBody(
- getTestJsonStringOfFile(resourceName, resourceName + ".json"), ContentType.APPLICATION_JSON));
- HttpEntity requestEntity = mpBuilder.build();
- String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE, config.getCatalogBeHost(),
- config.getCatalogBePort());
- Map<String, String> headers = new HashMap<String, String>();
- headers.put("USER_ID", userRole.getUserId());
-
- return HttpRequest.sendHttpPostWithEntity(requestEntity, url, headers);
- }
-
- public static RestResponse importTestResource(ImportTestTypesEnum resource, UserRoleEnum userRole)
- throws IOException {
- Config config = Utils.getConfig();
- CloseableHttpResponse response = null;
- MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
-
- mpBuilder.addPart("resourceZip", new FileBody(getTestZipFile(resource.getFolderName())));
- mpBuilder.addPart("resourceMetadata",
- new StringBody(getTestJsonStringOfFile(resource.getFolderName(), resource.getFolderName() + ".json"),
- ContentType.APPLICATION_JSON));
-
- String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE, config.getCatalogBeHost(),
- config.getCatalogBePort());
-
- CloseableHttpClient client = HttpClients.createDefault();
- try {
- HttpPost httpPost = new HttpPost(url);
- RestResponse restResponse = new RestResponse();
- httpPost.addHeader("USER_ID", UserRoleEnum.ADMIN.getUserId());
- httpPost.setEntity(mpBuilder.build());
- response = client.execute(httpPost);
- HttpEntity entity = response.getEntity();
- String responseBody = null;
- if (entity != null) {
- InputStream instream = entity.getContent();
- StringWriter writer = new StringWriter();
- IOUtils.copy(instream, writer);
- responseBody = writer.toString();
- try {
-
- } finally {
- instream.close();
- }
- }
-
- restResponse.setErrorCode(response.getStatusLine().getStatusCode());
- // restResponse.setResponse(response.getEntity().toString());
- restResponse.setResponse(responseBody);
- return restResponse;
- } finally {
- closeResponse(response);
- closeHttpClient(client);
-
- }
- }
-
- public static Boolean removeNormativeTypeResource(NormativeTypesEnum current)
- throws FileNotFoundException, IOException, ClientProtocolException {
- User user = new User(UserRoleEnum.ADMIN.getFirstName(), UserRoleEnum.ADMIN.getLastName(),
- UserRoleEnum.ADMIN.getUserId(), null, null, null);
- RestResponse deleteResponse = ResourceRestUtils.deleteResourceByNameAndVersion(user, current.getNormativeName(),
- "1.0");
- if (deleteResponse.getErrorCode() == 200) {
- return true;
- }
- return false;
- }
-
- public static void validateImportTestTypesResp(ImportTestTypesEnum currResource, RestResponse restResponse)
- throws IOException, JSONException {
-
- // assertTrue( status != ResourceUtils.STATUS_CODE_IMPORT_SUCCESS );
-
- ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(currResource.getActionStatus().name());
-
- assertNotNull("check response object is not null after create service", restResponse);
- assertNotNull("check error code exists in response after create service", restResponse.getErrorCode());
- assertEquals("Check response code after create service", errorInfo.getCode(), restResponse.getErrorCode());
-
- // validate create service response vs actual
- List<String> variables = (currResource.getErrorParams() != null ? currResource.getErrorParams()
- : new ArrayList<String>());
- if (restResponse.getErrorCode() != 200) {
- ErrorValidationUtils.checkBodyResponseOnError(currResource.getActionStatus().name(), variables,
- restResponse.getResponse());
- }
- }
-
- private static String getTestJsonStringOfFile(String folderName, String fileName) throws IOException {
- // String sourceDir = "src/test/resources/CI/importResourceTests";
- Config config = Utils.getConfig();
- String sourceDir = config.getImportResourceTestsConfigDir();
- java.nio.file.Path filePath = FileSystems.getDefault().getPath(sourceDir + File.separator + folderName,
- fileName);
- byte[] fileContent = Files.readAllBytes(filePath);
- String content = new String(fileContent);
- return content;
- }
-
- private static File getTestZipFile(String elementName) throws IOException {
- Config config = Utils.getConfig();
- String sourceDir = config.getImportResourceTestsConfigDir();
- java.nio.file.Path filePath = FileSystems.getDefault().getPath(sourceDir + File.separator + elementName,
- "normative-types-new-" + elementName + ".zip");
- return filePath.toFile();
- }
-
- private static void closeHttpClient(CloseableHttpClient client) {
- try {
- if (client != null) {
- client.close();
- }
- } catch (IOException e) {
- log.debug("failed to close client or response: ", e);
- }
- }
-
- private static void closeResponse(CloseableHttpResponse response) {
- try {
- if (response != null) {
- response.close();
- }
- } catch (IOException e) {
- log.debug("failed to close client or response: {}", e);
- }
- }
-
- public static RestResponseAsByteArray getCsar(String csarUid, User sdncModifierDetails) throws Exception {
-
- Config config = Utils.getConfig();
- String url = String.format(Urls.GET_CSAR_USING_SIMULATOR, config.getCatalogBeHost(), config.getCatalogBePort(),
- csarUid);
-
- String userId = sdncModifierDetails.getUserId();
- Map<String, String> headersMap = prepareHeadersMap(userId);
- HttpRestClient httpRestClient = new HttpRestClient();
-
- for (Map.Entry<String, String> mapEntry : headersMap.entrySet()) {
-
- downloadCsarHeaders.put(mapEntry.getKey(), mapEntry.getValue());
- }
- RestResponseAsByteArray doGetAsByteArray = httpRestClient.doGetAsByteArray(url, downloadCsarHeaders);
- // RestResponse getCsar = http.httpSendGet(url, headersMap);
-
- return doGetAsByteArray;
-
- }
-
- private static File getGroupTypeZipFile(String elementName) throws IOException {
- Config config = Utils.getConfig();
- String sourceDir = config.getImportResourceTestsConfigDir();
- sourceDir += File.separator + ".." + File.separator + "importTypesTest" + File.separator;
- java.nio.file.Path filePath = FileSystems.getDefault().getPath(sourceDir + File.separator + elementName,
- elementName + ".zip");
- return filePath.toFile();
- }
-
- public static RestResponse importNewGroupTypeByName(String groupTypeName, UserRoleEnum userRole)
- throws IOException {
- Config config = Utils.getConfig();
-
- MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
-
- mpBuilder.addPart("groupTypesZip", new FileBody(getGroupTypeZipFile(groupTypeName)));
- HttpEntity requestEntity = mpBuilder.build();
- String url = String.format(Urls.IMPORT_GROUP_TYPE, config.getCatalogBeHost(), config.getCatalogBePort());
- Map<String, String> headers = new HashMap<String, String>();
- headers.put("USER_ID", userRole.getUserId());
-
- return HttpRequest.sendHttpPostWithEntity(requestEntity, url, headers);
- }
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/InputsRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/InputsRestUtils.java
deleted file mode 100644
index de7be077d1..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/InputsRestUtils.java
+++ /dev/null
@@ -1,122 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utils.rest;
-
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.ComponentInstInputsMap;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.ci.tests.api.Urls;
-import org.openecomp.sdc.ci.tests.config.Config;
-import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
-import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
-import org.openecomp.sdc.ci.tests.utils.Utils;
-import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.gson.Gson;
-
-/**
- * RestUtils for inputs
- *
- * @author il0695
- *
- */
-public class InputsRestUtils extends BaseRestUtils {
-
- @SuppressWarnings("unused")
- private static Logger logger = LoggerFactory.getLogger(InputsRestUtils.class.getName());
-
- /**
- * Add inputs to service
- *
- * @param component
- * @param inputs
- * @param userRole
- * @return {@link org.openecomp.sdc.ci.tests.datatypes.http.RestResponse}
- * @throws Exception
- */
- public static RestResponse addInput(Component component, ComponentInstInputsMap inputs, UserRoleEnum userRole) throws Exception {
- Config config = Utils.getConfig();
- String url = String.format(Urls.ADD_INPUTS, config.getCatalogBeHost(), config.getCatalogBePort(), ComponentTypeEnum.findParamByType(component.getComponentType()), component.getUniqueId());
- String json = new Gson().toJson(inputs);
- return sendPost(url, json, userRole.getUserId(), acceptHeaderData);
- }
-
- /**
- * Get all Component inputs
- *
- * @param component
- * @return {@link org.openecomp.sdc.ci.tests.datatypes.http.RestResponse}
- * @throws Exception
- */
- public static RestResponse getComponentInputs(Component component) throws Exception {
- Config config = Utils.getConfig();
- //services/{componentId}/inputs
- String url = String.format(Urls.GET_COMPONENT_INPUTS, config.getCatalogBeHost(), config.getCatalogBePort(), component.getUniqueId());
- return sendGet(url, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER).getUserId());
- }
-
- /**
- * Get all inputs of component instance
- *
- * @param parentComponent
- * @param componentInstance
- * @return {@link org.openecomp.sdc.ci.tests.datatypes.http.RestResponse}
- * @throws Exception
- */
- public static RestResponse getComponentInstanceInputs(Component parentComponent, ComponentInstance componentInstance) throws Exception {
- Config config = Utils.getConfig();
- //{componentType}/{componentId}/componentInstances/{instanceId}/{originComonentUid}/inputs
- String url = String.format(Urls.GET_COMPONENT_INSTANCE_INPUTS, config.getCatalogBeHost(), config.getCatalogBePort(), ComponentTypeEnum.findParamByType(parentComponent.getComponentType()), parentComponent.getUniqueId(), componentInstance.getUniqueId(), componentInstance.getComponentUid());
- return sendGet(url, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER).getUserId());
- }
-
- /**
- * Delete input from component
- *
- * @param parentComponent
- * @param inputId
- * @return {@link org.openecomp.sdc.ci.tests.datatypes.http.RestResponse}
- * @throws Exception
- */
- public static RestResponse deleteInputFromComponent(Component parentComponent, String inputId) throws Exception {
- return deleteInputFromComponent(ComponentTypeEnum.findParamByType(parentComponent.getComponentType()), parentComponent.getUniqueId(), inputId);
- }
-
- /**
- * Delete input from component
- *
- * @param componentType
- * @param componentId
- * @param inputUniqueId
- * @return {@link org.openecomp.sdc.ci.tests.datatypes.http.RestResponse}
- * @throws Exception
- */
- public static RestResponse deleteInputFromComponent(String componentType, String componentId, String inputUniqueId) throws Exception {
- Config config = Utils.getConfig();
- //{componentType}/{componentId}/delete/{inputId}/input
- String url = String.format(Urls.DELETE_INPUT_BY_ID, config.getCatalogBeHost(), config.getCatalogBePort(), componentType, componentId, inputUniqueId);
- return sendDelete(url, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER).getUserId());
- }
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/LifecycleRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/LifecycleRestUtils.java
deleted file mode 100644
index a5b8c7a4bf..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/LifecycleRestUtils.java
+++ /dev/null
@@ -1,410 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utils.rest;
-
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.Map;
-
-import org.json.simple.JSONObject;
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.DistributionStatusEnum;
-import org.openecomp.sdc.be.model.LifecycleStateEnum;
-import org.openecomp.sdc.be.model.Product;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.ci.tests.api.Urls;
-import org.openecomp.sdc.ci.tests.config.Config;
-import org.openecomp.sdc.ci.tests.datatypes.ProductReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
-import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
-import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
-import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest;
-import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
-import org.openecomp.sdc.ci.tests.utils.Utils;
-import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class LifecycleRestUtils extends BaseRestUtils {
- private static Logger logger = LoggerFactory.getLogger(LifecycleRestUtils.class.getName());
- public static final String COMMENT = "comment";
-
- public static RestResponse changeResourceState(ResourceReqDetails resourceDetails, User sdncModifierDetails,
- String version, LifeCycleStatesEnum LifeCycleStatesEnum) throws IOException {
- return changeResourceState(resourceDetails, sdncModifierDetails, LifeCycleStatesEnum,
- createLifecycleCommentJson(COMMENT));
- }
-
- public static RestResponse changeResourceState(ResourceReqDetails resourceDetails, User sdncModifierDetails,
- String version, LifeCycleStatesEnum LifeCycleStatesEnum, String LifecycleChangeInfo) throws IOException {
-
- return changeResourceState(resourceDetails, sdncModifierDetails, LifeCycleStatesEnum, LifecycleChangeInfo);
-
- }
-
- public static RestResponse changeResourceState(ResourceReqDetails resourceDetails, User sdncModifierDetails,
- LifeCycleStatesEnum LifeCycleStatesEnum) throws IOException {
-
- return changeResourceState(resourceDetails, sdncModifierDetails, LifeCycleStatesEnum,
- createLifecycleCommentJson(COMMENT));
-
- }
-
- public static RestResponse changeResourceState(ResourceReqDetails resourceDetails, String modifierUserId,
- LifeCycleStatesEnum LifeCycleStatesEnum) throws IOException {
- User user = new User();
- user.setUserId(modifierUserId);
- return changeResourceState(resourceDetails, user, LifeCycleStatesEnum, createLifecycleCommentJson(COMMENT));
- }
-
- private static RestResponse changeResourceState(ResourceReqDetails resourceDetails, User sdncModifierDetails,
- LifeCycleStatesEnum LifeCycleStatesEnum, String LifecycleChangeInfo) throws IOException {
- Config config = Utils.getConfig();
- String url = String.format(Urls.CHANGE_RESOURCE_LIFECYCLE_STATE, config.getCatalogBeHost(),
- config.getCatalogBePort(), resourceDetails.getUniqueId(), LifeCycleStatesEnum);
- // System.out.println("url: " + url);
-
- RestResponse LifeCycleStatesEnumResourceResponse = sendPost(url, LifecycleChangeInfo,
- sdncModifierDetails.getUserId(), acceptHeaderData);
- if (LifeCycleStatesEnumResourceResponse.getErrorCode() == STATUS_CODE_SUCCESS) {
- String stateFromJsonResponse = ResponseParser
- .getValueFromJsonResponse(LifeCycleStatesEnumResourceResponse.getResponse(), "lifecycleState");
- resourceDetails.setVersion(ResponseParser.getVersionFromResponse(LifeCycleStatesEnumResourceResponse));
- resourceDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(LifeCycleStatesEnumResourceResponse));
- if (stateFromJsonResponse != null) {
- resourceDetails.setLifecycleState(LifecycleStateEnum.valueOf(stateFromJsonResponse));
- }
- }
- return LifeCycleStatesEnumResourceResponse;
- }
-
- public static RestResponse changeExternalResourceState(String uuid, User sdncModifierDetails, LifeCycleStatesEnum lifeCycleStatesEnum) throws IOException {
- String url = String.format(Urls.CHANGE_RESOURCE_LIFECYCLE_STATE_EXTERNAL_API, "localhost", "8080", uuid, lifeCycleStatesEnum);
- String userId = sdncModifierDetails.getUserId();
- Map<String, String> headersMap = new HashMap<>();
- headersMap.put(HttpHeaderEnum.CACHE_CONTROL.getValue(), "no-cache");
- headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), "Basic dGVzdDoxMjM0NTY=");
- headersMap.put("X-ECOMP-InstanceID", "test");
- return sendPost(url, createLifecycleCommentJson(COMMENT), userId, acceptHeaderData,headersMap);
- }
-
- public static RestResponse changeExternalServiceState(ServiceReqDetails serviceDetails, User sdncModifierDetails, LifeCycleStatesEnum lifeCycleStatesEnum) throws IOException {
- String url = String.format(Urls.CHANGE_SERVICE_LIFECYCLE_STATE_EXTERNAL_API, "localhost", "8080", serviceDetails.getUUID(), lifeCycleStatesEnum);
- String userId = sdncModifierDetails.getUserId();
- Map<String, String> headersMap = new HashMap<>();
- headersMap.put(HttpHeaderEnum.CACHE_CONTROL.getValue(), "no-cache");
- headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), "Basic dGVzdDoxMjM0NTY=");
- headersMap.put("X-ECOMP-InstanceID", "test");
- RestResponse lifeCycleStatesEnumServiceResponse = sendPost(url, createLifecycleCommentJson(COMMENT), userId, acceptHeaderData,headersMap);
-
- if (lifeCycleStatesEnumServiceResponse.getErrorCode() == STATUS_CODE_SUCCESS) {
- String serviceUniqueId = ResponseParser
- .getValueFromJsonResponse(lifeCycleStatesEnumServiceResponse.getResponse(), "uniqueId");
- serviceDetails.setUniqueId(serviceUniqueId);
- String serviceVersion = ResponseParser
- .getValueFromJsonResponse(lifeCycleStatesEnumServiceResponse.getResponse(), "version");
- serviceDetails.setVersion(serviceVersion);
- String stateFromJsonResponse = ResponseParser
- .getValueFromJsonResponse(lifeCycleStatesEnumServiceResponse.getResponse(), "lifecycleState");
- serviceDetails.setLifecycleState(LifecycleStateEnum.valueOf(stateFromJsonResponse));
- }
- return lifeCycleStatesEnumServiceResponse;
- }
-
- public static RestResponse changeServiceState(ServiceReqDetails serviceDetails, User sdncModifierDetails,
- String version, LifeCycleStatesEnum LifeCycleStatesEnum) throws Exception {
- {
- return changeServiceState(serviceDetails, sdncModifierDetails, version, LifeCycleStatesEnum,
- createLifecycleCommentJson(COMMENT));
- }
- }
-
- public static RestResponse changeServiceState(ServiceReqDetails serviceDetails, User sdncModifierDetails,
- LifeCycleStatesEnum LifeCycleStatesEnum) throws Exception {
- {
- return changeServiceState(serviceDetails, sdncModifierDetails, null, LifeCycleStatesEnum,
- createLifecycleCommentJson(COMMENT));
- }
- }
-
- public static RestResponse changeServiceState(ServiceReqDetails serviceDetails, User sdncModifierDetails,
- LifeCycleStatesEnum LifeCycleStatesEnum, String lifecycleChangeInfo) throws Exception {
- {
- return changeServiceState(serviceDetails, sdncModifierDetails, null, LifeCycleStatesEnum,
- lifecycleChangeInfo);
- }
- }
-
- public static RestResponse changeServiceState(ServiceReqDetails serviceDetails, User sdncModifierDetails,
- String version, LifeCycleStatesEnum LifeCycleStatesEnum, String lifecycleChangeInfo) throws Exception {
-
- Config config = Utils.getConfig();
- Map<String, String> headersMap = prepareHeadersMap(sdncModifierDetails);
- HttpRequest http = new HttpRequest();
- String url = String.format(Urls.CHANGE_SERVICE_LIFECYCLE_STATE, config.getCatalogBeHost(),
- config.getCatalogBePort(), serviceDetails.getUniqueId(), LifeCycleStatesEnum);
- // System.out.println("url: " + url);
- RestResponse LifeCycleStatesEnumServiceResponse = http.httpSendPost(url, lifecycleChangeInfo, headersMap);
- if (LifeCycleStatesEnumServiceResponse.getErrorCode() == STATUS_CODE_SUCCESS) {
- String serviceUniqueId = ResponseParser
- .getValueFromJsonResponse(LifeCycleStatesEnumServiceResponse.getResponse(), "uniqueId");
- serviceDetails.setUniqueId(serviceUniqueId);
- String serviceVersion = ResponseParser
- .getValueFromJsonResponse(LifeCycleStatesEnumServiceResponse.getResponse(), "version");
- serviceDetails.setVersion(serviceVersion);
- String stateFromJsonResponse = ResponseParser
- .getValueFromJsonResponse(LifeCycleStatesEnumServiceResponse.getResponse(), "lifecycleState");
- serviceDetails.setLifecycleState(LifecycleStateEnum.valueOf(stateFromJsonResponse));
- }
- return LifeCycleStatesEnumServiceResponse;
- }
-
- public static RestResponse changeProductState(Product product, User sdncModifierDetails,
- LifeCycleStatesEnum LifeCycleStatesEnum, String lifecycleChangeInfo) throws Exception {
- {
- return _changeProductState(product, sdncModifierDetails, LifeCycleStatesEnum, lifecycleChangeInfo);
- }
- }
-
- public static RestResponse changeProductState(Product product, User sdncModifierDetails,
- LifeCycleStatesEnum LifeCycleStatesEnum) throws Exception {
- {
- return _changeProductState(product, sdncModifierDetails, LifeCycleStatesEnum, COMMENT);
- }
- }
-
- public static RestResponse changeProductState(ProductReqDetails productDetails, User sdncModifierDetails,
- LifeCycleStatesEnum LifeCycleStatesEnum) throws Exception {
- Config config = Utils.getConfig();
- String url = String.format(Urls.CHANGE_PRODUCT_LIFECYCLE_STATE, config.getCatalogBeHost(),
- config.getCatalogBePort(), productDetails.getUniqueId(), LifeCycleStatesEnum);
- RestResponse LifeCycleStatesEnumServiceResponse = sendPost(url, createLifecycleCommentJson(COMMENT),
- sdncModifierDetails.getUserId(), acceptHeaderData);
- if (LifeCycleStatesEnumServiceResponse.getErrorCode() == STATUS_CODE_SUCCESS) {
- String productUniqueId = ResponseParser
- .getValueFromJsonResponse(LifeCycleStatesEnumServiceResponse.getResponse(), "uniqueId");
- productDetails.setUniqueId(productUniqueId);
- String productVersion = ResponseParser
- .getValueFromJsonResponse(LifeCycleStatesEnumServiceResponse.getResponse(), "version");
- productDetails.setVersion(productVersion);
- String newLifecycleState = ResponseParser
- .getValueFromJsonResponse(LifeCycleStatesEnumServiceResponse.getResponse(), "lifecycleState");
- productDetails.setLifecycleState(LifecycleStateEnum.valueOf(newLifecycleState));
- }
- return LifeCycleStatesEnumServiceResponse;
-
- }
-
- public static RestResponse changeComponentState(Component component, User sdncModifierDetails,
- LifeCycleStatesEnum LifeCycleStatesEnum) throws Exception {
- Config config = Utils.getConfig();
- String url = String.format(Urls.CHANGE_COMPONENT_LIFECYCLE_STATE, config.getCatalogBeHost(),
- config.getCatalogBePort(), ComponentTypeEnum.findParamByType(component.getComponentType()),
- component.getUniqueId(), LifeCycleStatesEnum);
- RestResponse LifeCycleStatesEnumServiceResponse = sendPost(url, createLifecycleCommentJson(COMMENT),
- sdncModifierDetails.getUserId(), acceptHeaderData);
- if (LifeCycleStatesEnumServiceResponse.getErrorCode() == STATUS_CODE_SUCCESS) {
- String productUniqueId = ResponseParser
- .getValueFromJsonResponse(LifeCycleStatesEnumServiceResponse.getResponse(), "uniqueId");
- component.setUniqueId(productUniqueId);
- String productVersion = ResponseParser
- .getValueFromJsonResponse(LifeCycleStatesEnumServiceResponse.getResponse(), "version");
- component.setVersion(productVersion);
- String newLifecycleState = ResponseParser
- .getValueFromJsonResponse(LifeCycleStatesEnumServiceResponse.getResponse(), "lifecycleState");
- component.setLifecycleState(LifecycleStateEnum.valueOf(newLifecycleState));
- }
- return LifeCycleStatesEnumServiceResponse;
-
- }
-
- public static RestResponse certifyResource(ResourceReqDetails resourceDetails) throws Exception {
- RestResponse restResponseResource = LifecycleRestUtils.changeResourceState(resourceDetails,
- ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), LifeCycleStatesEnum.CHECKIN);
- // if (restResponseResource.getErrorCode() == 200){
- restResponseResource = LifecycleRestUtils.changeResourceState(resourceDetails,
- ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), LifeCycleStatesEnum.CERTIFICATIONREQUEST);
- // }else
- // return restResponseResource;
- User testerDetails = ElementFactory.getDefaultUser(UserRoleEnum.TESTER);
- if (restResponseResource.getErrorCode() == 200) {
- restResponseResource = LifecycleRestUtils.changeResourceState(resourceDetails, testerDetails,
- LifeCycleStatesEnum.STARTCERTIFICATION);
- } else
- return restResponseResource;
- if (restResponseResource.getErrorCode() == 200) {
- restResponseResource = LifecycleRestUtils.changeResourceState(resourceDetails, testerDetails,
- LifeCycleStatesEnum.CERTIFY);
- if (restResponseResource.getErrorCode() == 200) {
- String newVersion = ResponseParser.getVersionFromResponse(restResponseResource);
- resourceDetails.setVersion(newVersion);
- resourceDetails.setLifecycleState(LifecycleStateEnum.CERTIFIED);
- resourceDetails.setLastUpdaterUserId(testerDetails.getUserId());
- resourceDetails.setLastUpdaterFullName(testerDetails.getFullName());
- String uniqueIdFromRresponse = ResponseParser.getUniqueIdFromResponse(restResponseResource);
- resourceDetails.setUniqueId(uniqueIdFromRresponse);
- }
- }
- return restResponseResource;
- }
-
- public static RestResponse certifyService(ServiceReqDetails serviceDetails) throws Exception {
- RestResponse restResponseService = LifecycleRestUtils.changeServiceState(serviceDetails,
- ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), LifeCycleStatesEnum.CHECKIN);
- // if (restResponseService.getErrorCode() == 200){
- restResponseService = LifecycleRestUtils.changeServiceState(serviceDetails,
- ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), LifeCycleStatesEnum.CERTIFICATIONREQUEST);
- // }else
- // return restResponseService;
- if (restResponseService.getErrorCode() == 200) {
- restResponseService = LifecycleRestUtils.changeServiceState(serviceDetails,
- ElementFactory.getDefaultUser(UserRoleEnum.TESTER), LifeCycleStatesEnum.STARTCERTIFICATION);
- } else
- return restResponseService;
- if (restResponseService.getErrorCode() == 200) {
- User testerDetails = ElementFactory.getDefaultUser(UserRoleEnum.TESTER);
- restResponseService = LifecycleRestUtils.changeServiceState(serviceDetails, testerDetails,
- LifeCycleStatesEnum.CERTIFY);
- if (restResponseService.getErrorCode() == 200) {
- String newVersion = ResponseParser.getVersionFromResponse(restResponseService);
- serviceDetails.setVersion(newVersion);
- serviceDetails.setLifecycleState(LifecycleStateEnum.CERTIFIED);
- serviceDetails.setLastUpdaterUserId(testerDetails.getUserId());
- serviceDetails.setLastUpdaterFullName(testerDetails.getFullName());
- String uniqueIdFromRresponse = ResponseParser.getUniqueIdFromResponse(restResponseService);
- serviceDetails.setUniqueId(uniqueIdFromRresponse);
- }
- }
- return restResponseService;
- }
-
- private static RestResponse _changeProductState(Product product, User sdncModifierDetails,
- LifeCycleStatesEnum LifeCycleStatesEnum, String lifecycleChangeInfo) throws Exception {
-
- Config config = Utils.getConfig();
- String url = String.format(Urls.CHANGE_PRODUCT_LIFECYCLE_STATE, config.getCatalogBeHost(),
- config.getCatalogBePort(), product.getUniqueId(), LifeCycleStatesEnum);
- RestResponse LifeCycleStatesEnumServiceResponse = sendPost(url, createLifecycleCommentJson(lifecycleChangeInfo),
- sdncModifierDetails.getUserId(), acceptHeaderData);
-
- return LifeCycleStatesEnumServiceResponse;
- }
-
- public static String createLifecycleCommentJson(String commentContent) {
- String res = null;
- if (commentContent != null) {
- res = "{\"userRemarks\": \"" + commentContent + "\"}";
- }
- return res;
- }
-
- public static void checkLCS_Response(RestResponse response) {
- checkStatusCode(response, "change lifecycle request failed", false, STATUS_CODE_SUCCESS);
- }
-
- private static Map<String, String> prepareHeadersMap(User sdncModifierDetails) {
- Map<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderData);
- headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId());
- return headersMap;
- }
-
- public static RestResponse changeDistributionStatus(ServiceReqDetails serviceDetails, String version, User user,
- String userRemarks, DistributionStatusEnum reqDistributionStatus) throws Exception {
- String uniqueId = serviceDetails.getUniqueId();
- Config config = Utils.getConfig();
- String environmentName = "PROD-Andreys-Only";
-// String environmentName = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getEnvironments().get(0);
- DistributionStatusEnum distributionStatusEnum = DistributionStatusEnum.findState(reqDistributionStatus.getValue());
- switch(distributionStatusEnum){
- case DISTRIBUTION_APPROVED:
- return sendApproveDistribution(user, uniqueId, userRemarks);
- case DISTRIBUTED:
- String url = String.format(Urls.ACTIVATE_DISTRIBUTION, config.getCatalogBeHost(), config.getCatalogBePort(), uniqueId, environmentName);
- return sendDistrState(user, userRemarks, url);
- case DISTRIBUTION_REJECTED:
- return rejectDistribution(user, userRemarks, uniqueId);
- default:
- return null;
-
- }
-
-// if (reqDistributionStatus == DistributionStatusEnum.DISTRIBUTION_APPROVED) {
-// return sendApproveDistribution(user, uniqueId, userRemarks);
-// } else if (reqDistributionStatus == DistributionStatusEnum.DISTRIBUTION_REJECTED) {
-// return rejectDistribution(user, userRemarks, uniqueId);
-// } else if (reqDistributionStatus == DistributionStatusEnum.DISTRIBUTED) {
-// Config config = Utils.getConfig();
-// // String url =
-// // String.format("http://%s:%s/sdc2/rest/v1/catalog/services/%s/tempUrlToBeDeleted",
-// // config.getCatalogBeHost(), config.getCatalogBePort(), uniqueId);
-// String url = String.format(Urls.ACTIVATE_DISTRIBUTION, config.getCatalogBeHost(), config.getCatalogBePort(),
-// uniqueId, "PROD");
-// return sendDistrState(user, userRemarks, url);
-// } else
-// return null;
-
- }
-
- public static RestResponse sendApproveDistribution(User sdncModifierDetails, String uniqueId, String userRemarks)
- throws FileNotFoundException, IOException {
- Config config = Utils.getConfig();
- String url = String.format(Urls.APPROVE_DISTRIBUTION, config.getCatalogBeHost(), config.getCatalogBePort(),
- uniqueId);
- return sendDistrState(sdncModifierDetails, userRemarks, url);
- }
-
- public static RestResponse rejectDistribution(ServiceReqDetails serviceDetails, String version, User user,
- String userRemarks) throws Exception {
- return rejectDistribution(user, userRemarks, serviceDetails.getUniqueId());
- }
-
- public static RestResponse rejectDistribution(User user, String userRemarks, String uniqueId)
- throws FileNotFoundException, IOException {
- Config config = Utils.getConfig();
- String url = String.format(Urls.REJECT_DISTRIBUTION, config.getCatalogBeHost(), config.getCatalogBePort(),
- uniqueId);
- return sendDistrState(user, userRemarks, url);
- }
-
- private static RestResponse sendDistrState(User user, String userRemarks, String url) throws IOException {
- Map<String, String> headersMap = prepareHeadersMap(user);
- Map<String, String> userRemarksMap = new HashMap<String, String>();
- userRemarksMap.put("userRemarks", userRemarks);
-
- String serviceBodyJson = new JSONObject().toJSONString(userRemarksMap);
-
- HttpRequest httpRequest = new HttpRequest();
- logger.debug(url);
- logger.debug("Send POST request to create service: {}",url);
- logger.debug("Service body: {}",serviceBodyJson);
- logger.debug("Service headers: {}",headersMap);
- RestResponse rejectDistributionResponse = httpRequest.httpSendPost(url, serviceBodyJson, headersMap);
-
- return rejectDistributionResponse;
- }
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ProductRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ProductRestUtils.java
deleted file mode 100644
index fad47f0178..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ProductRestUtils.java
+++ /dev/null
@@ -1,196 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utils.rest;
-
-import java.io.IOException;
-
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.model.LifecycleStateEnum;
-import org.openecomp.sdc.be.model.Product;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.ci.tests.api.Urls;
-import org.openecomp.sdc.ci.tests.config.Config;
-import org.openecomp.sdc.ci.tests.datatypes.ProductReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
-import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
-import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
-import org.openecomp.sdc.ci.tests.utils.Utils;
-import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.gson.Gson;
-
-public class ProductRestUtils extends BaseRestUtils {
- private static Gson gson = new Gson();
- private static Logger logger = LoggerFactory.getLogger(ProductRestUtils.class.getName());
-
- public static RestResponse createProduct(ProductReqDetails product, User user) throws Exception {
- Config config = Utils.getConfig();
- String url = String.format(Urls.CREATE_PRODUCT, config.getCatalogBeHost(), config.getCatalogBePort());
- String serviceBodyJson = gson.toJson(product);
-
- logger.debug("Send POST request to create service: {}",url);
- logger.debug("Service body: {}",serviceBodyJson);
-
- RestResponse res = sendPost(url, serviceBodyJson, user.getUserId(), acceptHeaderData);
- if (res.getErrorCode() == STATUS_CODE_CREATED) {
- product.setUniqueId(ResponseParser.getUniqueIdFromResponse(res));
- product.setVersion(ResponseParser.getVersionFromResponse(res));
- product.setUUID(ResponseParser.getUuidFromResponse(res));
- // Creator details never change after component is created - Ella,
- // 12/1/2016
- product.setCreatorUserId(user.getUserId());
- product.setCreatorFullName(user.getFullName());
- product.setLastUpdaterFullName(user.getFullName());
- product.setLastUpdaterUserId(user.getUserId());
- product.setLastUpdaterFullName(user.getFullName());
- product.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
- product.setVersion("0.1");
- String lastUpdate = ResponseParser.getValueFromJsonResponse(res.getResponse(), "lastUpdateDate");
- product.setLastUpdateDate(Long.parseLong(lastUpdate, 10));
- product.setCreationDate(Long.parseLong(lastUpdate, 10));
- }
- return res;
- }
-
- public static RestResponse updateProduct(ProductReqDetails product, User user) throws Exception {
- Config config = Utils.getConfig();
- String url = String.format(Urls.UPDATE_PRODUCT, config.getCatalogBeHost(), config.getCatalogBePort(),
- product.getUniqueId());
- String serviceBodyJson = gson.toJson(product);
-
- logger.debug("Send POST request to create service: {}",url);
- logger.debug("Service body: {}",serviceBodyJson);
-
- RestResponse res = sendPut(url, serviceBodyJson, user.getUserId(), acceptHeaderData);
- if (res.getErrorCode() == STATUS_CODE_CREATED) {
- product.setUniqueId(ResponseParser.getUniqueIdFromResponse(res));
- product.setVersion(ResponseParser.getVersionFromResponse(res));
- product.setUUID(ResponseParser.getUuidFromResponse(res));
- // Creator details never change after component is created - Ella,
- // 12/1/2016
- product.setCreatorUserId(user.getUserId());
- product.setCreatorFullName(user.getFullName());
- product.setLastUpdaterFullName(user.getFullName());
- product.setLastUpdaterUserId(user.getUserId());
- product.setLastUpdaterFullName(user.getFullName());
- product.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
- String valueFromJsonResponse = ResponseParser.getValueFromJsonResponse(res.getResponse(), "version");
- product.setVersion(valueFromJsonResponse);
- String lastUpdate = ResponseParser.getValueFromJsonResponse(res.getResponse(), "lastUpdateDate");
- product.setLastUpdateDate(Long.parseLong(lastUpdate, 10));
- product.setCreationDate(Long.parseLong(lastUpdate, 10));
- }
- return res;
- }
-
- public static RestResponse createProduct_Invalid_Json(String userId) throws Exception {
- Config config = Utils.getConfig();
- String url = String.format(Urls.CREATE_PRODUCT, config.getCatalogBeHost(), config.getCatalogBePort());
-
- RestResponse res = sendPost(url, "kukumuku", userId, acceptHeaderData);
- return res;
- }
-
- public static RestResponse deleteProduct(String id, String userId) throws IOException {
-
- Config config = Utils.getConfig();
- String url = String.format(Urls.DELETE_PRODUCT, config.getCatalogBeHost(), config.getCatalogBePort(), id);
- return sendDelete(url, userId);
- }
-
- public static RestResponse getProduct(String productId) throws Exception {
-
- Config config = Utils.getConfig();
- String url = String.format(Urls.GET_PRODUCT, config.getCatalogBeHost(), config.getCatalogBePort(), productId);
- logger.debug("Send GET request to get product: {}",url);
-
- return sendGet(url, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER).getUserId());
- }
-
- public static RestResponse getProduct(String productId, String userId) throws Exception {
-
- Config config = Utils.getConfig();
- String url = String.format(Urls.GET_PRODUCT, config.getCatalogBeHost(), config.getCatalogBePort(), productId);
- logger.debug("Send GET request to get product: {}",url);
-
- return sendGet(url, userId);
- }
-
- public static RestResponse getFollowed(String userId) throws Exception {
- Config config = Utils.getConfig();
- String url = String.format(Urls.GET_FOLLWED_LIST, config.getCatalogBeHost(), config.getCatalogBePort());
- logger.debug("Send GET request to get user followed page: {}",url);
- return sendGet(url, userId);
-
- }
-
- public static RestResponse changeProductLifeCycle(Product product, User userModifier, LifeCycleStatesEnum lifeCycle)
- throws Exception {
- String checkinComment = "my comment";
- RestResponse changeLifeCycleResponse = LifecycleRestUtils.changeProductState(product, userModifier, lifeCycle,
- checkinComment);
- if (changeLifeCycleResponse.getErrorCode() == STATUS_CODE_SUCCESS) {
- product.setLastUpdaterUserId(userModifier.getUserId());
- product.setLastUpdaterFullName(userModifier.getFullName());
- String latestVersion = ResponseParser.getValueFromJsonResponse(changeLifeCycleResponse.getResponse(),
- "version");
- product.setVersion(latestVersion);
- String lifecycleState = ResponseParser.getValueFromJsonResponse(changeLifeCycleResponse.getResponse(),
- "lifecycleState");
- product.setLifecycleState((LifecycleStateEnum.valueOf(lifecycleState)));
- String uniqueId = ResponseParser.getValueFromJsonResponse(changeLifeCycleResponse.getResponse(),
- "uniqueId");
- product.setUniqueId(uniqueId);
- String lastUpdate = ResponseParser.getValueFromJsonResponse(changeLifeCycleResponse.getResponse(),
- "lastUpdateDate");
- product.setLastUpdateDate((Long.parseLong(lastUpdate, 10)));
- String uuid = ResponseParser.getValueFromJsonResponse(changeLifeCycleResponse.getResponse(), "uuid");
- product.setUUID(uuid);
- }
- return changeLifeCycleResponse;
- }
-
- public static RestResponse changeServiceInstanceVersion(String componentUniqueId,
- String serviceInstanceToReplaceUniqueId, String serviceUniqueId, User sdncModifierDetails,
- ComponentTypeEnum componentType) throws IOException {
- Config config = Utils.getConfig();
- String resourceUid = ("{\"componentUid\":\"" + serviceUniqueId + "\"}");
- String url = String.format(Urls.CHANGE_RESOURCE_INSTANCE_VERSION, config.getCatalogBeHost(),
- config.getCatalogBePort(), ComponentTypeEnum.findParamByType(componentType), componentUniqueId,
- serviceInstanceToReplaceUniqueId);
- RestResponse changeResourceInstanceVersion = sendPost(url, resourceUid, sdncModifierDetails.getUserId(),
- acceptHeaderData);
- return changeResourceInstanceVersion;
-
- }
-
- public static RestResponse getProductByNameAndVersion(String productName, String productVersion, String userId)
- throws Exception {
- Config config = Utils.getConfig();
- String url = String.format(Urls.GET_PRODUCT_BY_NAME_AND_VERSION, config.getCatalogBeHost(),
- config.getCatalogBePort(), productName, productVersion);
- logger.debug("Send GET request to get product by name and version: {}",url);
- return sendGet(url, userId);
- }
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/PropertyRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/PropertyRestUtils.java
deleted file mode 100644
index a8661830ee..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/PropertyRestUtils.java
+++ /dev/null
@@ -1,262 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utils.rest;
-
-import static org.testng.AssertJUnit.assertNotNull;
-import static org.testng.AssertJUnit.assertNull;
-import static org.testng.AssertJUnit.assertTrue;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.ComponentInstanceProperty;
-import org.openecomp.sdc.be.model.PropertyDefinition;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.Service;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.ci.tests.api.Urls;
-import org.openecomp.sdc.ci.tests.config.Config;
-import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class PropertyRestUtils extends BaseRestUtils {
- private static Logger logger = LoggerFactory.getLogger(PropertyRestUtils.class.getName());
-
- public static RestResponse createProperty(String resourceId, String body, User user) throws Exception {
- Config config = Config.instance();
- String url = String.format(Urls.CREATE_PROPERTY, config.getCatalogBeHost(), config.getCatalogBePort(), resourceId);
-
- return sendPost(url, body, user.getUserId(), acceptHeaderData);
- }
-
- public static RestResponse updateProperty(String resourceId, String propertyId, String body, User user) throws Exception {
- Config config = Config.instance();
-
- String url = String.format(Urls.UPDATE_PROPERTY, config.getCatalogBeHost(), config.getCatalogBePort(), resourceId, propertyId);
- return sendPut(url, body, user.getUserId(), acceptHeaderData);
- }
-
- public static RestResponse getProperty(String resourceId, String propertyId, User user) throws Exception {
- Config config = Config.instance();
- String url = String.format(Urls.GET_PROPERTY, config.getCatalogBeHost(), config.getCatalogBePort(), resourceId, propertyId);
- return sendGet(url, user.getUserId());
- }
-
- public static RestResponse deleteProperty(String resourceId, String propertyId, User user) throws Exception {
- Config config = Config.instance();
- String url = String.format(Urls.DELETE_PROPERTY, config.getCatalogBeHost(), config.getCatalogBePort(), resourceId, propertyId);
-
- return sendDelete(url, user.getUserId());
- }
-
- public static ComponentInstanceProperty getPropFromListByPropNameAndType(List<ComponentInstanceProperty> propList, String propNameToUpdate, String propTypeToUpdate) {
- for (ComponentInstanceProperty componentInstanceProperty : propList) {
- if (componentInstanceProperty.getName().equals(propNameToUpdate) && componentInstanceProperty.getType().equals(propTypeToUpdate)) {
- return componentInstanceProperty;
- }
- }
- return null;
- }
-
- public static ComponentInstanceProperty getPropFromListByPropNameTypeAndPath(List<ComponentInstanceProperty> propList, String propNameToUpdate, String propTypeToUpdate, List<String> path) {
- for (ComponentInstanceProperty componentInstanceProperty : propList) {
- if (componentInstanceProperty.getPath() == null) {
- return getPropFromListByPropNameAndType(propList, propNameToUpdate, propTypeToUpdate);
- }
- if (componentInstanceProperty.getName().equals(propNameToUpdate) && componentInstanceProperty.getType().equals(propTypeToUpdate) && path.containsAll(componentInstanceProperty.getPath())) {
- return componentInstanceProperty;
- }
- }
- return null;
- }
-
- public static ComponentInstanceProperty getPropFromListByPropIdAndPath(List<ComponentInstanceProperty> propList, String propId, List<String> path) {
-
- for (ComponentInstanceProperty componentInstanceProperty : propList) {
- if (path != null) {
- if (componentInstanceProperty.getUniqueId().equals(propId) && componentInstanceProperty.getPath().equals(path)) {
- return componentInstanceProperty;
- }
- } else {
- if (componentInstanceProperty.getUniqueId().equals(propId)) {
- return componentInstanceProperty;
- }
- }
- }
- return null;
- }
-
- public static void comparePropertyLists(List<ComponentInstanceProperty> expectedList, List<ComponentInstanceProperty> actualList, Boolean isUpdate) {
-
- assertTrue("list size are not equals, expected size is: " + expectedList.size() + " ,actual: " + actualList.size(), expectedList.size() == actualList.size());
- Boolean flag = false;
- for (ComponentInstanceProperty expectedcompInstProp : expectedList) {
- for (ComponentInstanceProperty actualcompInstProp : actualList) {
- flag = comparePropertyObjects(expectedcompInstProp, actualcompInstProp, isUpdate);
- if (flag) {
- break;
- }
- }
- }
- // System.out.println("expected: " + expectedList + ", actual: " +
- // actualList);
- logger.debug("expected: {}, actual: {}",expectedList,actualList);
- assertTrue("actual lists does not contain all uniqeIds", flag);
- }
-
- public static Boolean comparePropertyObjects(ComponentInstanceProperty expectedCompInstProp, ComponentInstanceProperty actualCompInstProp, Boolean isUpdate) {
- String uniqueId = expectedCompInstProp.getUniqueId();
- String type = expectedCompInstProp.getType();
- String defaulValue = expectedCompInstProp.getDefaultValue();
- if (actualCompInstProp.getUniqueId().equals(uniqueId) && actualCompInstProp.getPath().equals(expectedCompInstProp.getPath())) {
- assertTrue("expected type is: " + type + " ,actual: " + actualCompInstProp.getType(), actualCompInstProp.getType().equals(type));
- if (defaulValue == null) {
- assertTrue("expected defaulValue is: " + defaulValue + " ,actual: " + actualCompInstProp.getDefaultValue(), actualCompInstProp.getDefaultValue() == defaulValue);
- } else {
- assertTrue("expected defaulValue is: " + defaulValue + " ,actual: " + actualCompInstProp.getDefaultValue(), actualCompInstProp.getDefaultValue().equals(defaulValue));
- }
- if (isUpdate) {
- assertTrue("actual [Value] parameter " + actualCompInstProp.getName() + "should equal to expected [Value]: " + actualCompInstProp.getValue() + " ,Value: " + actualCompInstProp.getValue(),
- actualCompInstProp.getValue().equals(expectedCompInstProp.getValue()));
- assertNotNull("valueId is null", actualCompInstProp.getValueUniqueUid());
- } else {
- if (defaulValue == null) {
- assertTrue("actual [Value] parameter " + actualCompInstProp.getName() + "should equal to expected [defaultValue]: " + actualCompInstProp.getValue() + " ,defaultValue: " + actualCompInstProp.getDefaultValue(),
- actualCompInstProp.getValue() == expectedCompInstProp.getDefaultValue());
- } else {
- assertTrue("actual [Value] parameter " + actualCompInstProp.getName() + "should equal to expected [defaultValue]: " + actualCompInstProp.getValue() + " ,defaultValue: " + actualCompInstProp.getDefaultValue(),
- actualCompInstProp.getValue().equals(expectedCompInstProp.getDefaultValue()));
- }
- assertNull("valueId is not null", actualCompInstProp.getValueUniqueUid());
- }
- return true;
- }
- return false;
- }
-
- public static List<ComponentInstanceProperty> addResourcePropertiesToList(Resource resource, List<ComponentInstanceProperty> listToFill) {
- for (PropertyDefinition prop : resource.getProperties()) {
- listToFill.add(new ComponentInstanceProperty(prop, null, null));
- }
- return listToFill;
- }
-
- public static List<ComponentInstanceProperty> addComponentInstPropertiesToList(Component component, List<ComponentInstanceProperty> listToFill, String componentId) {
-
- if (componentId != null) {
- List<ComponentInstanceProperty> list = component.getComponentInstancesProperties().get(componentId);
- for (ComponentInstanceProperty prop : list) {
- ComponentInstanceProperty componentInstanceProperty = new ComponentInstanceProperty(prop, null, null);
- componentInstanceProperty.setPath(prop.getPath());
- componentInstanceProperty.setValueUniqueUid(prop.getValueUniqueUid());
- componentInstanceProperty.setValue(prop.getValue());
- listToFill.add(componentInstanceProperty);
- }
- } else {
- Map<String, List<ComponentInstanceProperty>> componentInstancesProperties = component.getComponentInstancesProperties();
- for (Map.Entry<String, List<ComponentInstanceProperty>> componentInstanceProperties : componentInstancesProperties.entrySet()) {
- for (ComponentInstanceProperty prop : componentInstanceProperties.getValue()) {
- ComponentInstanceProperty componentInstanceProperty = new ComponentInstanceProperty(prop, null, null);
- componentInstanceProperty.setPath(prop.getPath());
- componentInstanceProperty.setValueUniqueUid(prop.getValueUniqueUid());
- componentInstanceProperty.setValue(prop.getValue());
- listToFill.add(componentInstanceProperty);
- }
- }
- }
-
- if (component.getComponentType().getValue().equals("Resource")) {
- for (PropertyDefinition prop : ((Resource) component).getProperties()) {
- listToFill.add(new ComponentInstanceProperty(prop, null, null));
- }
- }
- return listToFill;
- }
-
- public static ComponentInstanceProperty getCompPropInstListByInstIdAndPropName(Component component, ComponentInstance componentInstanceDetails, String name, String type) {
- List<ComponentInstanceProperty> propList = component.getComponentInstancesProperties().get(componentInstanceDetails.getUniqueId());
- if (propList != null) {
- return getPropFromListByPropNameAndType(propList, name, type);
- }
- return null;
- }
-
- private static void updatePropertyListWithPathParameter(Resource resource, List<String> path, List<ComponentInstanceProperty> expectedPropertyList) {
- List<PropertyDefinition> propertyList = resource.getProperties();
- for (PropertyDefinition propertyDefinition : propertyList) {
- ComponentInstanceProperty propDetailsToRemove = PropertyRestUtils.getPropFromListByPropNameAndType(expectedPropertyList, propertyDefinition.getName(), propertyDefinition.getType());
- ComponentInstanceProperty propDetailsToAdd = propDetailsToRemove;
- propDetailsToAdd.setPath(path);
- expectedPropertyList.remove(propDetailsToRemove);
- expectedPropertyList.add(propDetailsToAdd);
- }
- }
-
- private static void updatePropertyListWithPathParameterOnCompInst(Service service, List<String> path, List<ComponentInstanceProperty> expectedPropertyList) {
- List<ComponentInstanceProperty> servicePropertyList = new ArrayList<>();
- servicePropertyList = PropertyRestUtils.addComponentInstPropertiesToList(service, servicePropertyList, path.get(0));
-
- for (ComponentInstanceProperty serviceCompInstProperty : servicePropertyList) {
- ComponentInstanceProperty propDetailsToRemove = PropertyRestUtils.getPropFromListByPropNameTypeAndPath(expectedPropertyList, serviceCompInstProperty.getName(), serviceCompInstProperty.getType(), serviceCompInstProperty.getPath());
- ComponentInstanceProperty propDetailsToAdd = propDetailsToRemove;
- List<String> tempPathList = new ArrayList<String>();
- for (String tempPath : path) {
- tempPathList.add(tempPath);
- }
- // path parameter can not contain the same service unique ID twice
- if (propDetailsToAdd.getPath() != null && !propDetailsToAdd.getPath().get(0).contains(service.getUniqueId())) {
- if (!propDetailsToAdd.getPath().containsAll(tempPathList)) {
- tempPathList.addAll(propDetailsToAdd.getPath());
- }
- }
- propDetailsToAdd.setPath(tempPathList);
- expectedPropertyList.remove(propDetailsToRemove);
- expectedPropertyList.add(propDetailsToAdd);
- }
- }
-
- public static void updatePropertyListWithPathOnResource(ComponentInstance componentInstDetails, Resource resource, List<ComponentInstanceProperty> list, Component container) {
- List<String> path = new ArrayList<>();
- if (container != null) {
- List<ComponentInstance> componentInstances = container.getComponentInstances();
- for (ComponentInstance componentInstance : componentInstances) {
- if (componentInstance.getNormalizedName().equals(componentInstDetails.getNormalizedName())) {
- path.add(componentInstance.getUniqueId());
- break;
- }
- }
-
- } else {
- path.add(componentInstDetails.getUniqueId());
- }
- updatePropertyListWithPathParameter(resource, path, list);
- }
-
- public static void updatePropertyListWithPathOnComponentInstance(ComponentInstance componentInstDetails, Service service, List<ComponentInstanceProperty> list) {
- List<String> path = new ArrayList<>();
- path.add(componentInstDetails.getUniqueId());
- updatePropertyListWithPathParameterOnCompInst(service, path, list);
- }
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtils.java
deleted file mode 100644
index 0d8a1119ad..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtils.java
+++ /dev/null
@@ -1,725 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utils.rest;
-
-import static org.testng.AssertJUnit.assertEquals;
-
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.commons.codec.binary.Base64;
-import org.apache.commons.lang.StringUtils;
-import org.apache.http.client.ClientProtocolException;
-import org.json.JSONException;
-import org.json.simple.JSONArray;
-import org.json.simple.JSONObject;
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
-import org.openecomp.sdc.be.model.CapabilityDefinition;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.RequirementDefinition;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.resources.data.RelationshipInstData;
-import org.openecomp.sdc.ci.tests.api.Urls;
-import org.openecomp.sdc.ci.tests.config.Config;
-import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.ImportReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
-import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
-import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest;
-import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
-import org.openecomp.sdc.ci.tests.utils.Utils;
-import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
-import org.openecomp.sdc.common.util.GeneralUtility;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.gson.Gson;
-import com.google.gson.JsonArray;
-import com.google.gson.JsonElement;
-import com.google.gson.JsonParser;
-
-public class ResourceRestUtils extends BaseRestUtils {
-
- private static final String CSARS_PATH = "/src/test/resources/CI/csars/";
- private static Logger logger = LoggerFactory.getLogger(ResourceRestUtils.class.getName());
-
- // ****** CREATE *******
-
- public static RestResponse createResource(ResourceReqDetails resourceDetails, User sdncModifierDetails)
- throws Exception {
-
- Config config = Utils.getConfig();
- String url = String.format(Urls.CREATE_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort());
-
- String userId = sdncModifierDetails.getUserId();
-
- Map<String, String> headersMap = prepareHeadersMap(userId);
-
- Gson gson = new Gson();
- String userBodyJson = gson.toJson(resourceDetails);
- String calculateMD5 = GeneralUtility.calculateMD5Base64EncodedByString(userBodyJson);
- headersMap.put(HttpHeaderEnum.Content_MD5.getValue(), calculateMD5);
- HttpRequest http = new HttpRequest();
- // System.out.println(url);
- // System.out.println(userBodyJson);
- RestResponse createResourceResponse = http.httpSendPost(url, userBodyJson, headersMap);
- if (createResourceResponse.getErrorCode() == STATUS_CODE_CREATED) {
- resourceDetails.setUUID(ResponseParser.getUuidFromResponse(createResourceResponse));
- resourceDetails.setVersion(ResponseParser.getVersionFromResponse(createResourceResponse));
- resourceDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(createResourceResponse));
- String lastUpdaterUserId = ResponseParser.getValueFromJsonResponse(createResourceResponse.getResponse(),
- "lastUpdaterUserId");
- resourceDetails.setLastUpdaterUserId(lastUpdaterUserId);
- String lastUpdaterFullName = ResponseParser.getValueFromJsonResponse(createResourceResponse.getResponse(),
- "lastUpdaterFullName");
- resourceDetails.setLastUpdaterFullName(lastUpdaterFullName);
- // Creator details never change after component is created - Ella,
- // 12/1/2016
- resourceDetails.setCreatorUserId(userId);
- resourceDetails.setCreatorFullName(sdncModifierDetails.getFullName());
- }
- return createResourceResponse;
-
- }
-
- public static RestResponse createImportResource(ImportReqDetails importReqDetails, User sdncModifierDetails,
- Map<String, String> additionalHeaders) throws JSONException, IOException {
-
- Config config = Utils.getConfig();
- String url = String.format(Urls.CREATE_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort());
- String userId = sdncModifierDetails.getUserId();
-
- Gson gson = new Gson();
- String resourceImportBodyJson = gson.toJson(importReqDetails);
- HttpRequest http = new HttpRequest();
- // System.out.println(url);
- // System.out.println(resourceImportBodyJson);
-
- Map<String, String> headersMap = prepareHeadersMap(userId);
- if (additionalHeaders != null) {
- headersMap.putAll(additionalHeaders);
- } else {
- headersMap.put(HttpHeaderEnum.Content_MD5.getValue(),
- ArtifactRestUtils.calculateMD5(resourceImportBodyJson));
- }
-
- RestResponse createResourceResponse = http.httpSendPost(url, resourceImportBodyJson, headersMap);
- if (createResourceResponse.getErrorCode() == STATUS_CODE_CREATED) {
- importReqDetails.setVersion(ResponseParser.getVersionFromResponse(createResourceResponse));
- importReqDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(createResourceResponse));
- // Creator details never change after component is created - Ella,
- // 12/1/2016
- importReqDetails.setCreatorUserId(userId);
- importReqDetails.setCreatorFullName(sdncModifierDetails.getFullName());
- importReqDetails
- .setToscaResourceName(ResponseParser.getToscaResourceNameFromResponse(createResourceResponse));
- importReqDetails.setDerivedList(ResponseParser.getDerivedListFromJson(createResourceResponse));
- }
- return createResourceResponse;
-
- }
-
- // ***** DELETE ****
- public static RestResponse deleteResource(ResourceReqDetails resourceDetails, User sdncModifierDetails,
- String version) throws IOException {
-
- if (resourceDetails.getUniqueId() != null) {
- Config config = Utils.getConfig();
- String url = String.format(Urls.DELETE_RESOURCE_BY_NAME_AND_VERSION, config.getCatalogBeHost(),
- config.getCatalogBePort(), resourceDetails.getName(), version);
- return sendDelete(url, sdncModifierDetails.getUserId());
- } else {
- return null;
- }
-
- }
-
- public static RestResponse markResourceToDelete(String resourceId, String userId) throws IOException {
-
- Config config = Utils.getConfig();
- String url = String.format(Urls.DELETE_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(),
- resourceId);
- RestResponse sendDelete = sendDelete(url, userId);
-
- return sendDelete;
-
- }
-
- public static RestResponse deleteResource(String resourceId, String userId) throws IOException {
-
- Config config = Utils.getConfig();
- String url = String.format(Urls.DELETE_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(),
- resourceId);
- RestResponse sendDelete = sendDelete(url, userId);
-
- deleteMarkedResources(userId);
-
- return sendDelete;
-
- }
-
- public static void deleteMarkedResources(String userId) throws IOException {
- String url;
- Config config = Utils.getConfig();
- url = String.format(Urls.DELETE_MARKED_RESOURCES, config.getCatalogBeHost(), config.getCatalogBePort());
- sendDelete(url, userId);
- }
-
- public static RestResponse deleteResourceByNameAndVersion(User sdncModifierDetails, String resourceName,
- String resourceVersion) throws IOException {
- Config config = Utils.getConfig();
- String url = String.format(Urls.DELETE_RESOURCE_BY_NAME_AND_VERSION, config.getCatalogBeHost(),
- config.getCatalogBePort(), resourceName, resourceVersion);
- RestResponse sendDelete = sendDelete(url, sdncModifierDetails.getUserId());
-
- deleteMarkedResources(sdncModifierDetails.getUserId());
-
- return sendDelete;
- }
-
- public static Boolean deleteResourceByNameAndVersion(String resourceName, String resourceVersion)
- throws IOException {
- RestResponse deleteResponse = ResourceRestUtils.deleteResourceByNameAndVersion(
- ElementFactory.getDefaultUser(UserRoleEnum.ADMIN), resourceName, resourceVersion);
- return checkErrorCode(deleteResponse);
- }
-
- public static Boolean removeResource(String resourceId)
- throws FileNotFoundException, IOException, ClientProtocolException {
- RestResponse response = deleteResource(resourceId,
- ElementFactory.getDefaultUser(UserRoleEnum.ADMIN).getUserId());
- return checkErrorCode(response);
- }
-
- // ************** GET *************
- public static RestResponse getResource(User sdncModifierDetails, String uniqueId) throws IOException {
-
- Config config = Utils.getConfig();
- String url = String.format(Urls.GET_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(), uniqueId);
- return sendGet(url, sdncModifierDetails.getUserId());
- }
-
- public static RestResponse getModule(User sdncModifierDetails, String componentId, String moduleId)
- throws IOException {
- Config config = Utils.getConfig();
- String url = String.format(Urls.GET_MODULE_BY_ID, config.getCatalogBeHost(), config.getCatalogBePort(),
- componentId, moduleId);
- return sendGet(url, sdncModifierDetails.getUserId());
- }
-
- public static RestResponse getLatestResourceFromCsarUuid(User sdncModifierDetails, String csarUuid)
- throws IOException {
-
- Config config = Utils.getConfig();
- String url = String.format(Urls.GET_RESOURCE_BY_CSAR_UUID, config.getCatalogBeHost(), config.getCatalogBePort(),
- csarUuid);
- return sendGet(url, sdncModifierDetails.getUserId());
- }
-
- public static RestResponse getResource(ResourceReqDetails resourceDetails, User sdncModifierDetails)
- throws IOException {
-
- Config config = Utils.getConfig();
- String url = String.format(Urls.GET_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(),
- resourceDetails.getUniqueId());
- return sendGet(url, sdncModifierDetails.getUserId());
- }
-
- public static RestResponse getResourceLatestVersionListMetadata(User sdncModifierDetails, String internalComponentType) throws IOException {
-
- Config config = Utils.getConfig();
- StringBuilder sb = new StringBuilder();
- String url = String.format(Urls.GET_RESOURCE_METADATA_lATEST_VERSION, config.getCatalogBeHost(),
- config.getCatalogBePort());
- sb.append(url);
- if (internalComponentType != null && !internalComponentType.isEmpty()) {
- sb.append("?internalComponentType="+internalComponentType);
- }
- return sendGet(sb.toString(), sdncModifierDetails.getUserId());
-
- }
-
- public static RestResponse getResourceByNameAndVersion(String userId, String resourceName, String resourceVersion)
- throws IOException {
-
- Config config = Utils.getConfig();
- String url = String.format(Urls.GET_RESOURCE_BY_NAME_AND_VERSION, config.getCatalogBeHost(),
- config.getCatalogBePort(), resourceName, resourceVersion);
-
- return sendGet(url, userId);
- }
-
- public static RestResponse getResourceList(User sdncModifierDetails) throws IOException {
-
- Config config = Utils.getConfig();
- String url = String.format(Urls.GET_FOLLWED_LIST, config.getCatalogBeHost(), config.getCatalogBePort());
-
- return sendGet(url, sdncModifierDetails.getUserId());
-
- }
-
- public static RestResponse getResourceListFilterByCategory(User sdncModifierDetails, String componentType, String category) throws IOException {
-
- Config config = Utils.getConfig();
- String url = String.format(Urls.GET_FILTERED_ASSET_LIST, config.getCatalogBeHost(), config.getCatalogBePort(), componentType, "category=" + category);
-
- Map<String, String> headersMap = prepareHeadersMap(sdncModifierDetails.getUserId());
- headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), authorizationHeader);
- headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci");
-
- return sendGet(url, sdncModifierDetails.getUserId(), headersMap);
-
- }
-
- public static RestResponse getResourceListFilterByCriteria(User sdncModifierDetails, String componentType, String criteria, String value) throws IOException {
-
- Config config = Utils.getConfig();
- String url = String.format(Urls.GET_FILTERED_ASSET_LIST, config.getCatalogBeHost(), config.getCatalogBePort(), componentType, criteria + "=" + value);
-
- Map<String, String> headersMap = prepareHeadersMap(sdncModifierDetails.getUserId());
- headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), authorizationHeader);
- headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci");
-
- return sendGet(url, sdncModifierDetails.getUserId(), headersMap);
-
- }
-
- public static RestResponse getResource(String resourceId) throws ClientProtocolException, IOException {
- return getResource(ElementFactory.getDefaultUser(UserRoleEnum.ADMIN), resourceId);
- }
-
- public static RestResponse getLatestResourceFromCsarUuid(String csarUuid)
- throws ClientProtocolException, IOException {
- return getLatestResourceFromCsarUuid(ElementFactory.getDefaultUser(UserRoleEnum.ADMIN), csarUuid);
- }
-
- public static RestResponse getResourceLatestVersionList(User sdncModifierDetails) throws IOException {
-
- Config config = Utils.getConfig();
- String url = String.format(Urls.GET_RESOURCE_lATEST_VERSION, config.getCatalogBeHost(),
- config.getCatalogBePort());
-
- return sendGet(url, sdncModifierDetails.getUserId());
-
- }
-
- public static RestResponse putAllCategoriesTowardsCatalogFeWithUuidNotAllowed(String uuid) throws IOException {
-
- Config config = Utils.getConfig();
- String url = String.format(Urls.GET_ALL_CATEGORIES_FE, config.getCatalogFeHost(), config.getCatalogFePort(),
- BaseRestUtils.RESOURCE_COMPONENT_TYPE);
-
- Map<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderData);
- headersMap.put(HttpHeaderEnum.X_ECOMP_REQUEST_ID_HEADER.getValue(), uuid);
- HttpRequest http = new HttpRequest();
-
- logger.debug("Send PUT request to get all categories (should be 405): {}",url);
- return http.httpSendByMethod(url, "PUT", null, headersMap);
- }
-
- public static RestResponse getAllTagsTowardsCatalogBe() throws IOException {
-
- Config config = Utils.getConfig();
- HttpRequest http = new HttpRequest();
- String url = String.format(Urls.GET_ALL_TAGS, config.getCatalogBeHost(), config.getCatalogBePort());
-
- Map<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderData);
-
- return http.httpSendGet(url, headersMap);
-
- }
-
- public static RestResponse getAllPropertyScopesTowardsCatalogBe() throws IOException {
-
- Config config = Utils.getConfig();
- HttpRequest http = new HttpRequest();
- String url = String.format(Urls.GET_PROPERTY_SCOPES_LIST, config.getCatalogBeHost(), config.getCatalogBePort());
-
- Map<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json");
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json");
- headersMap.put(HttpHeaderEnum.USER_ID.getValue(), "cs0008");
-
- return http.httpSendGet(url, headersMap);
- }
-
- public static RestResponse getAllArtifactTypesTowardsCatalogBe() throws IOException {
-
- Config config = Utils.getConfig();
- HttpRequest http = new HttpRequest();
- String url = String.format(Urls.GET_ALL_ARTIFACTS, config.getCatalogBeHost(), config.getCatalogBePort());
-
- Map<String, String> headersMap = new HashMap<String, String>();
-
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json");
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json");
- headersMap.put(HttpHeaderEnum.USER_ID.getValue(), "cs0008");
-
- return http.httpSendGet(url, headersMap);
-
- }
-
- public static RestResponse getConfigurationTowardsCatalogBe() throws IOException {
-
- Config config = Utils.getConfig();
- HttpRequest http = new HttpRequest();
- String url = String.format(Urls.GET_CONFIGURATION, config.getCatalogBeHost(), config.getCatalogBePort());
-
- Map<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json");
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json");
- headersMap.put(HttpHeaderEnum.USER_ID.getValue(), "cs0008");
-
- return http.httpSendGet(url, headersMap);
-
- }
-
- public static RestResponse getResourceFilteredDataByParams(User sdncModifierDetails, String uniqueId , List<String> parameters) throws IOException {
- Config config = Utils.getConfig();
- String urlGetResourceDataByParams = Urls.GET_RESOURCE_DATA_BY_PARAMS;
- String joinedParameters = StringUtils.join(parameters , "&");
- String url = String.format(urlGetResourceDataByParams + joinedParameters , config.getCatalogBeHost(), config.getCatalogBePort(), uniqueId);
- return sendGet(url, sdncModifierDetails.getUserId());
-
- }
-
-
- public static RestResponse sendOptionsTowardsCatalogFeWithUuid() throws IOException {
-
- Config config = Utils.getConfig();
- String url = String.format(Urls.GET_ALL_CATEGORIES_FE, config.getCatalogFeHost(), config.getCatalogFePort(),
- BaseRestUtils.RESOURCE_COMPONENT_TYPE);
-
- Map<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderData);
- HttpRequest http = new HttpRequest();
-
- logger.debug("Send OPTIONS request for categories: {}",url);
- return http.httpSendByMethod(url, "OPTIONS", null, headersMap);
- }
-
- // ********** UPDATE *************
- public static RestResponse updateResourceMetadata(ResourceReqDetails updatedResourceDetails,
- User sdncModifierDetails, String uniqueId, String encoding) throws Exception {
- Config config = Utils.getConfig();
- String url = String.format(Urls.UPDATE_RESOURCE_METADATA, config.getCatalogBeHost(), config.getCatalogBePort(),
- uniqueId);
-
- String ContentTypeString = String.format("%s;%s", contentTypeHeaderData, encoding);
-
- Gson gson = new Gson();
- String userBodyJson = gson.toJson(updatedResourceDetails);
- String userId = sdncModifierDetails.getUserId();
-
- RestResponse updateResourceResponse = sendPut(url, userBodyJson, userId, ContentTypeString);
-
- updatedResourceDetails.setVersion(ResponseParser.getVersionFromResponse(updateResourceResponse));
- updatedResourceDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(updateResourceResponse));
-
- return updateResourceResponse;
- }
-
- public static RestResponse updateResourceTEST(Resource resource, User sdncModifierDetails, String uniqueId,
- String encoding) throws Exception {
- Config config = Utils.getConfig();
- String url = String.format(Urls.UPDATE_RESOURCE_METADATA, config.getCatalogBeHost(), config.getCatalogBePort(),
- uniqueId);
-
- String ContentTypeString = String.format("%s;%s", contentTypeHeaderData, encoding);
-
- Gson gson = new Gson();
- String userBodyJson = gson.toJson(resource);
- String userId = sdncModifierDetails.getUserId();
-
- RestResponse updateResourceResponse = sendPut(url, userBodyJson, userId, ContentTypeString);
-
- // String resourceUniqueId =
- // ResponseParser.getValueFromJsonResponse(updateResourceResponse.getResponse(),
- // "uniqueId");
- // updatedResourceDetails.setUniqueId(resourceUniqueId);
- // String resourceVersion =
- // ResponseParser.getValueFromJsonResponse(updateResourceResponse.getResponse(),
- // "version");
- // updatedResourceDetails.setUniqueId(resourceVersion);
-
- return updateResourceResponse;
- }
-
- public static RestResponse updateResourceMetadata(ResourceReqDetails updatedResourceDetails,
- User sdncModifierDetails, String uniqueId) throws Exception {
- return updateResourceMetadata(updatedResourceDetails, sdncModifierDetails, uniqueId, "");
- }
-
- public static RestResponse updateResourceMetadata(String json, User sdncModifierDetails, String resourceId)
- throws IOException {
- Config config = Utils.getConfig();
- String url = String.format(Urls.UPDATE_RESOURCE_METADATA, config.getCatalogBeHost(), config.getCatalogBePort(),
- resourceId);
- String userId = sdncModifierDetails.getUserId();
-
- RestResponse updateResourceResponse = sendPut(url, json, userId, contentTypeHeaderData);
-
- return updateResourceResponse;
- }
-
- public static RestResponse updateResource(ResourceReqDetails resourceDetails, User sdncModifierDetails,
- String resourceId) throws IOException {
-
- String userId = sdncModifierDetails.getUserId();
- Config config = Utils.getConfig();
- String url = String.format(Urls.UPDATE_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(),
- resourceId);
-
- Map<String, String> headersMap = prepareHeadersMap(userId);
-
- Gson gson = new Gson();
- String userBodyJson = gson.toJson(resourceDetails);
- String calculateMD5 = GeneralUtility.calculateMD5Base64EncodedByString(userBodyJson);
- headersMap.put(HttpHeaderEnum.Content_MD5.getValue(), calculateMD5);
- HttpRequest http = new HttpRequest();
- RestResponse updateResourceResponse = http.httpSendPut(url, userBodyJson, headersMap);
- if (updateResourceResponse.getErrorCode() == STATUS_CODE_UPDATE_SUCCESS) {
- resourceDetails.setUUID(ResponseParser.getUuidFromResponse(updateResourceResponse));
- resourceDetails.setVersion(ResponseParser.getVersionFromResponse(updateResourceResponse));
- resourceDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(updateResourceResponse));
- String lastUpdaterUserId = ResponseParser.getValueFromJsonResponse(updateResourceResponse.getResponse(),
- "lastUpdaterUserId");
- resourceDetails.setLastUpdaterUserId(lastUpdaterUserId);
- String lastUpdaterFullName = ResponseParser.getValueFromJsonResponse(updateResourceResponse.getResponse(),
- "lastUpdaterFullName");
- resourceDetails.setLastUpdaterFullName(lastUpdaterFullName);
- resourceDetails.setCreatorUserId(userId);
- resourceDetails.setCreatorFullName(sdncModifierDetails.getFullName());
- }
- return updateResourceResponse;
- }
-
- public static RestResponse createResourceInstance(ResourceReqDetails resourceDetails, User modifier,
- String vfResourceUniqueId) throws Exception {
- ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory
- .getComponentResourceInstance(resourceDetails);
- RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
- resourceInstanceReqDetails, modifier, vfResourceUniqueId, ComponentTypeEnum.RESOURCE);
- ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
- return createResourceInstanceResponse;
- }
-
- public static RestResponse associateResourceInstances(JSONObject body, User sdncModifierDetails,
- Component component) throws IOException {
-
- Config config = Utils.getConfig();
- Gson gson = new Gson();
- String bodyJson = gson.toJson(body);
- component.getComponentType();
- String componentType = ComponentTypeEnum.findParamByType(component.getComponentType());
- String url = String.format(Urls.ASSOCIATE_RESOURCE_INSTANCE, config.getCatalogBeHost(),
- config.getCatalogBePort(), componentType, component.getUniqueId());
- return sendPost(url, bodyJson, sdncModifierDetails.getUserId(), null);
-
- }
-
- public static RestResponse getFollowedList(User sdncModifierDetails) throws Exception {
- Config config = Utils.getConfig();
- String url = String.format(Urls.GET_FOLLWED_LIST, config.getCatalogBeHost(), config.getCatalogBePort());
- return sendGet(url, sdncModifierDetails.getUserId());
- }
-
- public static List<Resource> restResponseToResourceObjectList(String restResponse) {
- JsonElement jelement = new JsonParser().parse(restResponse);
- JsonArray jsonArray = jelement.getAsJsonArray();
- List<Resource> restResponseArray = new ArrayList<>();
- Resource resource = null;
- for (int i = 0; i < jsonArray.size(); i++) {
- String resourceString = (String) jsonArray.get(i).toString();
- resource = ResponseParser.convertResourceResponseToJavaObject(resourceString);
- restResponseArray.add(resource);
- }
-
- return restResponseArray;
-
- }
-
- public static Resource getResourceObjectFromResourceListByUid(List<Resource> resourceList, String uid) {
- if (resourceList != null && resourceList.size() > 0) {
- for (Resource resource : resourceList) {
- if (resource.getUniqueId().equals(uid))
- return resource;
- }
- } else
- return null;
- return null;
- }
-
- // =======================================resource
- // associate==================================================
- public static RestResponse associate2ResourceInstances(Component container, ComponentInstance fromNode,
- ComponentInstance toNode, String assocType, User sdncUserDetails) throws IOException {
- return associate2ResourceInstances(container, fromNode.getUniqueId(), toNode.getUniqueId(), assocType,
- sdncUserDetails);
- }
-
- public static RestResponse associate2ResourceInstances(Component component, String fromNode, String toNode,
- String assocType, User sdncUserDetails) throws IOException {
-
- RelationshipInstData relationshipInstData = new RelationshipInstData();
- Map<String, List<CapabilityDefinition>> capabilitiesMap = component.getCapabilities();
- Map<String, List<RequirementDefinition>> requirementMap = component.getRequirements();
- List<CapabilityDefinition> capabilitiesList = capabilitiesMap.get(assocType);
- List<RequirementDefinition> requirementList = requirementMap.get(assocType);
-
- RequirementDefinition requirementDefinitionFrom = getRequirementDefinitionByOwnerId(requirementList, fromNode);
- CapabilityDefinition capabilityDefinitionTo = getCapabilityDefinitionByOwnerId(capabilitiesList, toNode);
- relationshipInstData.setCapabilityOwnerId(capabilityDefinitionTo.getOwnerId());
- relationshipInstData.setCapabiltyId(capabilityDefinitionTo.getUniqueId());
- relationshipInstData.setRequirementOwnerId(requirementDefinitionFrom.getOwnerId());
- relationshipInstData.setRequirementId(requirementDefinitionFrom.getUniqueId());
-
- JSONObject assocBody = assocBuilder(relationshipInstData, capabilityDefinitionTo, requirementDefinitionFrom,
- toNode, fromNode);
- return ResourceRestUtils.associateResourceInstances(assocBody, sdncUserDetails, component);
-
- }
-
- private static JSONObject assocBuilder(RelationshipInstData relationshipInstData,
- CapabilityDefinition capabilityDefinitionTo, RequirementDefinition requirementDefinitionFrom, String toNode,
- String fromNode) {
-
- String type = capabilityDefinitionTo.getType();
- String requirement = requirementDefinitionFrom.getName();
- String capability = requirementDefinitionFrom.getName();
-
- JSONObject wrapper = new JSONObject();
- JSONArray relationshipsArray = new JSONArray();
- JSONObject relationship = new JSONObject();
- JSONObject simpleObject = new JSONObject();
-
- relationship.put("type", type);
- simpleObject.put("relationship", relationship);
- simpleObject.put("requirement", requirement);
- simpleObject.put("capability", capability);
- simpleObject.put("capabilityUid", relationshipInstData.getCapabiltyId());
- simpleObject.put("capabilityOwnerId", relationshipInstData.getCapabilityOwnerId());
- simpleObject.put("requirementOwnerId", relationshipInstData.getRequirementOwnerId());
- simpleObject.put("requirementUid", relationshipInstData.getRequirementId());
- relationshipsArray.add(simpleObject);
-
- ArrayList<Object> relationships = new ArrayList<Object>(relationshipsArray);
- wrapper.put("fromNode", fromNode);
- wrapper.put("toNode", toNode);
- wrapper.put("relationships", relationships);
- return wrapper;
-
- }
-
- private static CapabilityDefinition getCapabilityDefinitionByOwnerId(
- List<CapabilityDefinition> capabilityDefinitionList, String ownerId) {
-
- for (CapabilityDefinition capabilityDefinition : capabilityDefinitionList) {
- if (capabilityDefinition.getOwnerId().equals(ownerId)) {
- return capabilityDefinition;
- }
- }
- return null;
- }
-
- private static RequirementDefinition getRequirementDefinitionByOwnerId(
- List<RequirementDefinition> requirementDefinitionList, String ownerId) {
-
- for (RequirementDefinition requirementDefinition : requirementDefinitionList) {
- if (requirementDefinition.getOwnerId().equals(ownerId)) {
- return requirementDefinition;
- }
- }
- return null;
- }
-
- public static String getRiUniqueIdByRiName(Component component, String resourceInstanceName) {
-
- List<ComponentInstance> componentInstances = component.getComponentInstances();
- String name = null;
- for (ComponentInstance componentInstance : componentInstances) {
- if (componentInstance.getName().equals(resourceInstanceName)) {
- name = componentInstance.getUniqueId();
- break;
- }
- }
- return name;
- }
-
- public static Resource convertResourceGetResponseToJavaObject(ResourceReqDetails resourceDetails)
- throws IOException {
- RestResponse response = ResourceRestUtils.getResource(resourceDetails,
- ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
- assertEquals("Check response code after get resource", 200, response.getErrorCode().intValue());
- return ResponseParser.convertResourceResponseToJavaObject(response.getResponse());
- }
-
- public static RestResponse changeResourceInstanceVersion(String containerUniqueId, String instanceToReplaceUniqueId,
- String newResourceUniqueId, User sdncModifierDetails, ComponentTypeEnum componentType) throws IOException {
- return ProductRestUtils.changeServiceInstanceVersion(containerUniqueId, instanceToReplaceUniqueId,
- newResourceUniqueId, sdncModifierDetails, componentType);
- }
-
- public static Resource importResourceFromCsar(String csarName) throws Exception{
- User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
- String payloadName = csarName;
- ImportReqDetails resourceDetails = ElementFactory.getDefaultImportResource();
- String rootPath = System.getProperty("user.dir");
- Path path = null;
- byte[] data = null;
-
- String payloadData = null;
-
- path = Paths.get(rootPath + CSARS_PATH + csarName);
- data = Files.readAllBytes(path);
- payloadData = Base64.encodeBase64String(data);
- resourceDetails.setPayloadData(payloadData);
-
- // create new resource from Csar
- resourceDetails.setCsarUUID(payloadName);
- resourceDetails.setPayloadName(payloadName);
- resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
- RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
- BaseRestUtils.checkCreateResponse(createResource);
- Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
- return resource;
-
- // add to restResourceUtil
- }
-
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtilsExternalAPI.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtilsExternalAPI.java
deleted file mode 100644
index d9b8ec3d4b..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtilsExternalAPI.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utils.rest;
-
-import java.util.Map;
-
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.ci.tests.api.Urls;
-import org.openecomp.sdc.ci.tests.config.Config;
-import org.openecomp.sdc.ci.tests.datatypes.ResourceExternalReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
-import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest;
-import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
-import org.openecomp.sdc.ci.tests.utils.Utils;
-import org.openecomp.sdc.common.util.GeneralUtility;
-
-import com.google.gson.Gson;
-
-public class ResourceRestUtilsExternalAPI extends BaseRestUtils {
-
- public static RestResponse createResource(ResourceExternalReqDetails resourceDetails, User sdncModifierDetails)
- throws Exception {
-
- Config config = Utils.getConfig();
- String url = String.format(Urls.POST_EXTERNAL_API_CREATE_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort());
-
- String userId = sdncModifierDetails.getUserId();
- Map<String, String> headersMap = prepareHeadersMap(userId);
-
- Gson gson = new Gson();
- String userBodyJson = gson.toJson(resourceDetails);
- String calculateMD5 = GeneralUtility.calculateMD5Base64EncodedByString(userBodyJson);
- headersMap.put(HttpHeaderEnum.Content_MD5.getValue(), calculateMD5);
- headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), authorizationHeader);
- headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci");
- headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId());
-
- HttpRequest http = new HttpRequest();
- RestResponse createResourceResponse = http.httpSendPost(url, userBodyJson, headersMap);
-
- return createResourceResponse;
- }
-
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResponseParser.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResponseParser.java
deleted file mode 100644
index 2d173cc151..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResponseParser.java
+++ /dev/null
@@ -1,564 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utils.rest;
-
-import java.io.IOException;
-import java.text.ParseException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.commons.codec.binary.Base64;
-import org.apache.log4j.Logger;
-import org.codehaus.jackson.Version;
-import org.codehaus.jackson.map.JsonDeserializer;
-import org.codehaus.jackson.map.ObjectMapper;
-import org.codehaus.jackson.map.module.SimpleModule;
-import org.json.JSONArray;
-import org.json.JSONException;
-import org.json.simple.JSONObject;
-import org.json.simple.JSONValue;
-import org.openecomp.sdc.be.model.ArtifactDefinition;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.ComponentInstanceProperty;
-import org.openecomp.sdc.be.model.Product;
-import org.openecomp.sdc.be.model.PropertyConstraint;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.Service;
-import org.openecomp.sdc.be.model.category.CategoryDefinition;
-import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintJacksonDeserialiser;
-import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.ResourceRespJavaObject;
-import org.openecomp.sdc.ci.tests.datatypes.ServiceDistributionStatus;
-import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
-import org.openecomp.sdc.ci.tests.utils.Utils;
-
-import com.google.gson.Gson;
-import com.google.gson.JsonArray;
-import com.google.gson.JsonElement;
-import com.google.gson.JsonObject;
-import com.google.gson.JsonParser;
-
-public class ResponseParser {
-
- // comment by Andrey, for test only
- // public static void main(String[] args) {
- // String response =
- // "{\"uniqueId\":\"52eb0139-a855-47b9-a0e6-c90f0a90b1d2\",\"resourceName\":\"importResource4test\",\"resourceVersion\":\"0.1\",\"creatorUserId\":\"jh0003\",\"creatorFullName\":\"Jimmy
- // Hendrix\",\"lastUpdaterUserId\":\"jh0003\",\"lastUpdaterFullName\":\"Jimmy
- // Hendrix\",\"creationDate\":1446742241514,\"lastUpdateDate\":1446742241514,\"description\":\"Represents
- // a generic software component that can be managed and run by a Compute
- // Node
- // Type.\",\"icon\":\"defaulticon\",\"tags\":[\"importResource4test\"],\"category\":\"Generic/Infrastructure\",\"lifecycleState\":\"NOT_CERTIFIED_CHECKOUT\",\"derivedFrom\":[\"tosca.nodes.Root\"],\"artifacts\":{},\"deploymentArtifacts\":{},\"properties\":[{\"uniqueId\":\"52eb0139-a855-47b9-a0e6-c90f0a90b1d2.port\",\"type\":\"integer\",\"required\":false,\"description\":\"the
- // port the DBMS service will listen to for data and
- // requests\",\"password\":false,\"name\":\"port\",\"parentUniqueId\":\"52eb0139-a855-47b9-a0e6-c90f0a90b1d2\",\"definition\":true},{\"uniqueId\":\"52eb0139-a855-47b9-a0e6-c90f0a90b1d2.root_password\",\"type\":\"string\",\"required\":false,\"description\":\"the
- // optional root password for the DBMS
- // service\",\"password\":false,\"name\":\"root_password\",\"parentUniqueId\":\"52eb0139-a855-47b9-a0e6-c90f0a90b1d2\",\"definition\":true}],\"interfaces\":{\"standard\":{\"type\":\"tosca.interfaces.node.lifecycle.Standard\",\"uniqueId\":\"tosca.interfaces.node.lifecycle.standard\",\"operations\":{\"stop\":{\"uniqueId\":\"tosca.interfaces.node.lifecycle.standard.stop\",\"description\":\"Standard
- // lifecycle stop
- // operation.\",\"definition\":false},\"start\":{\"uniqueId\":\"tosca.interfaces.node.lifecycle.standard.start\",\"description\":\"Standard
- // lifecycle start
- // operation.\",\"definition\":false},\"delete\":{\"uniqueId\":\"tosca.interfaces.node.lifecycle.standard.delete\",\"description\":\"Standard
- // lifecycle delete
- // operation.\",\"definition\":false},\"create\":{\"uniqueId\":\"tosca.interfaces.node.lifecycle.standard.create\",\"description\":\"Standard
- // lifecycle create
- // operation.\",\"definition\":false},\"configure\":{\"uniqueId\":\"tosca.interfaces.node.lifecycle.standard.configure\",\"description\":\"Standard
- // lifecycle configure
- // operation.\",\"definition\":false}},\"definition\":false}},\"capabilities\":{\"feature\":{\"uniqueId\":\"capability.8313348e-3623-4f4a-9b8f-d2fbadaf9a31.feature\",\"type\":\"tosca.capabilities.Node\"},\"feature2\":{\"uniqueId\":\"capability.52eb0139-a855-47b9-a0e6-c90f0a90b1d2.feature2\",\"type\":\"tosca.capabilities.Node\"}},\"requirements\":{\"dependency\":{\"uniqueId\":\"8313348e-3623-4f4a-9b8f-d2fbadaf9a31.dependency\",\"capability\":\"tosca.capabilities.Node\",\"node\":\"tosca.nodes.Root\",\"relationship\":\"tosca.relationships.DependsOn\"},\"dependency2\":{\"uniqueId\":\"52eb0139-a855-47b9-a0e6-c90f0a90b1d2.dependency2\",\"capability\":\"tosca.capabilities.Node\",\"node\":\"tosca.nodes.importResource4test\",\"relationship\":\"tosca.relationships.DependsOn\"}},\"vendorName\":\"ATT
- // (Tosca)\",\"vendorRelease\":\"1.0.0.wd03\",\"contactId\":\"jh0003\",\"systemName\":\"Importresource4test\",\"additionalInformation\":[{\"uniqueId\":\"52eb0139-a855-47b9-a0e6-c90f0a90b1d2.additionalinformation\",\"lastCreatedCounter\":0,\"parentUniqueId\":\"52eb0139-a855-47b9-a0e6-c90f0a90b1d2\",\"parameters\":[]}],\"allVersions\":{\"0.1\":\"52eb0139-a855-47b9-a0e6-c90f0a90b1d2\"},\"abstract\":false,\"highestVersion\":true,\"uuid\":\"2e91a2df-b066-49bb-abde-4c1c01e409db\"}";
- // convertResourceResponseToJavaObject(response);
- // }
-
- private static final String INVARIANT_UUID = "invariantUUID";
- public static final String UNIQUE_ID = "uniqueId";
- public static final String VERSION = "version";
- public static final String UUID = "uuid";
- public static final String NAME = "name";
- public static final String ORIGIN_TYPE = "originType";
- public static final String TOSCA_RESOURCE_NAME = "toscaResourceName";
-
- static Logger logger = Logger.getLogger(ResponseParser.class.getName());
-
- public static String getValueFromJsonResponse(String response, String fieldName) {
- try {
- JSONObject jsonResp = (JSONObject) JSONValue.parse(response);
- Object fieldValue = jsonResp.get(fieldName);
- return fieldValue.toString();
-
- } catch (Exception e) {
- return null;
- }
-
- }
-
- public static String getUniqueIdFromResponse(RestResponse response) {
- return getValueFromJsonResponse(response.getResponse(), UNIQUE_ID);
- }
-
- public static String getInvariantUuid(RestResponse response) {
- return getValueFromJsonResponse(response.getResponse(), INVARIANT_UUID);
- }
-
- public static String getUuidFromResponse(RestResponse response) {
- return getValueFromJsonResponse(response.getResponse(), UUID);
- }
-
- public static String getNameFromResponse(RestResponse response) {
- return getValueFromJsonResponse(response.getResponse(), NAME);
- }
-
- public static String getVersionFromResponse(RestResponse response) {
- return ResponseParser.getValueFromJsonResponse(response.getResponse(), VERSION);
- }
-
- public static String getComponentTypeFromResponse(RestResponse response) {
- return ResponseParser.getValueFromJsonResponse(response.getResponse(), ORIGIN_TYPE);
- }
-
- public static String getToscaResourceNameFromResponse(RestResponse response) {
- return getValueFromJsonResponse(response.getResponse(), TOSCA_RESOURCE_NAME);
- }
-
- @SuppressWarnings("unchecked")
- public static ResourceRespJavaObject parseJsonListReturnResourceDetailsObj(RestResponse restResponse,
- String resourceType, String searchPattern, String expectedResult) throws Exception {
-
- // Gson gson = new Gson;
-
- JsonElement jElement = new JsonParser().parse(restResponse.getResponse());
- JsonObject jObject = jElement.getAsJsonObject();
- JsonArray arrayOfObjects = (JsonArray) jObject.get(resourceType);
- Gson gson = new Gson();
- Map<String, Object> map = new HashMap<String, Object>();
- ResourceRespJavaObject jsonToJavaObject = new ResourceRespJavaObject();
-
- for (int counter = 0; counter < arrayOfObjects.size(); counter++) {
- JsonObject jHitObject = (JsonObject) arrayOfObjects.get(counter);
-
- map = (Map<String, Object>) gson.fromJson(jHitObject.toString(), map.getClass());
- if (map.get(searchPattern).toString().contains(expectedResult)) {
-
- jsonToJavaObject = gson.fromJson(jObject, ResourceRespJavaObject.class);
- break;
- }
- }
- return jsonToJavaObject;
-
- }
-
- public static Resource convertResourceResponseToJavaObject(String response) {
-
- ObjectMapper mapper = new ObjectMapper();
- final SimpleModule module = new SimpleModule("customerSerializationModule",
- new Version(1, 0, 0, "static version"));
- JsonDeserializer<PropertyConstraint> desrializer = new PropertyConstraintJacksonDeserialiser();
- addDeserializer(module, PropertyConstraint.class, desrializer);
-
- mapper.registerModule(module);
- Resource resource = null;
- try {
- resource = mapper.readValue(response, Resource.class);
- logger.debug(resource.toString());
- } catch (IOException e) {
- try {
- List<Resource> resources = Arrays.asList(mapper.readValue(response.toString(), Resource[].class));
- resource = resources.get(0);
- } catch (Exception e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- }
- }
-
- return resource;
- }
-
- public static ComponentInstanceProperty convertPropertyResponseToJavaObject(String response) {
-
- ObjectMapper mapper = new ObjectMapper();
- final SimpleModule module = new SimpleModule("customerSerializationModule",
- new Version(1, 0, 0, "static version"));
- JsonDeserializer<PropertyConstraint> desrializer = new PropertyConstraintJacksonDeserialiser();
- addDeserializer(module, PropertyConstraint.class, desrializer);
-
- mapper.registerModule(module);
- ComponentInstanceProperty propertyDefinition = null;
- try {
- propertyDefinition = mapper.readValue(response, ComponentInstanceProperty.class);
- logger.debug(propertyDefinition.toString());
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return propertyDefinition;
- }
-
- public static String toJson(Object object) {
- Gson gson = new Gson();
- return gson.toJson(object);
- }
-
- public static ArtifactDefinition convertArtifactDefinitionResponseToJavaObject(String response) {
- ObjectMapper mapper = new ObjectMapper();
- ArtifactDefinition artifactDefinition = null;
- try {
-
- artifactDefinition = mapper.readValue(response, ArtifactDefinition.class);
- logger.debug(artifactDefinition.toString());
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
- return artifactDefinition;
-
- }
-
- public static ArtifactReqDetails convertArtifactReqDetailsToJavaObject(String response) {
-
- ArtifactReqDetails artifactReqDetails = null;
-
- Gson gson = new Gson();
- artifactReqDetails = gson.fromJson(response, ArtifactReqDetails.class);
- return artifactReqDetails;
- }
-
- public static <T> T parseToObject(String json, Class<T> clazz) {
- Gson gson = new Gson();
- T object;
- try {
- object = gson.fromJson(json, clazz);
- } catch (Exception e) {
- object = parseToObjectUsingMapper(json, clazz);
- }
- return object;
- }
-
- public static <T> T parseToObjectUsingMapper(String json, Class<T> clazz) {
- // Generic convert
- ObjectMapper mapper = new ObjectMapper();
- T object = null;
- final SimpleModule module = new SimpleModule("customerSerializationModule",
- new Version(1, 0, 0, "static version"));
- JsonDeserializer<PropertyConstraint> desrializer = new PropertyConstraintJacksonDeserialiser();
- addDeserializer(module, PropertyConstraint.class, desrializer);
- mapper.registerModule(module);
- try {
- object = mapper.readValue(json, clazz);
- // System.out.println("Class: "+clazz.getSimpleName()+", json:
- // "+json);
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
- return object;
- }
-
- public static ArtifactReqDetails convertArtifactDefinitionToArtifactReqDetailsObject(
- ArtifactDefinition artifactDefinition) {
-
- ArtifactReqDetails artifactReqDetails = null;
-
- Gson gson = new Gson();
- String artDef = gson.toJson(artifactDefinition);
- artifactReqDetails = gson.fromJson(artDef, ArtifactReqDetails.class);
- return artifactReqDetails;
- }
-
- public static <T> void addDeserializer(SimpleModule module, Class<T> clazz,
- final JsonDeserializer<T> deserializer) {
- module.addDeserializer(clazz, deserializer);
- }
-
- public static Service convertServiceResponseToJavaObject(String response) {
-
- ObjectMapper mapper = new ObjectMapper();
- final SimpleModule module = new SimpleModule("customerSerializationModule",
- new Version(1, 0, 0, "static version"));
- JsonDeserializer<PropertyConstraint> desrializer = new PropertyConstraintJacksonDeserialiser();
- addDeserializer(module, PropertyConstraint.class, desrializer);
-
- mapper.registerModule(module);
- Service service = null;
- try {
- service = mapper.readValue(response, Service.class);
- logger.debug(service.toString());
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
- return service;
- }
-
- public static Product convertProductResponseToJavaObject(String response) {
-
- ObjectMapper mapper = new ObjectMapper();
- Product product = null;
- try {
- product = mapper.readValue(response, Product.class);
- logger.debug(product.toString());
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
- return product;
- }
-
- public static ComponentInstance convertComponentInstanceResponseToJavaObject(String response) {
-
- ObjectMapper mapper = new ObjectMapper();
- final SimpleModule module = new SimpleModule("customerSerializationModule",
- new Version(1, 0, 0, "static version"));
- JsonDeserializer<PropertyConstraint> desrializer = new PropertyConstraintJacksonDeserialiser();
- addDeserializer(module, PropertyConstraint.class, desrializer);
-
- mapper.registerModule(module);
- ComponentInstance componentInstance = null;
- try {
- componentInstance = mapper.readValue(response, ComponentInstance.class);
- logger.debug(componentInstance.toString());
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
- return componentInstance;
- }
-
- public static List<String> getValuesFromJsonArray(RestResponse message) throws Exception {
- List<String> artifactTypesArrayFromApi = new ArrayList<String>();
-
- org.json.JSONObject responseObject = new org.json.JSONObject(message.getResponse());
- JSONArray jArr = responseObject.getJSONArray("artifactTypes");
-
- for (int i = 0; i < jArr.length(); i++) {
- org.json.JSONObject jObj = jArr.getJSONObject(i);
- String value = jObj.get("name").toString();
-
- artifactTypesArrayFromApi.add(value);
- }
- return artifactTypesArrayFromApi;
- }
-
- public static String calculateMD5Header(ArtifactReqDetails artifactDetails) {
- Gson gson = new Gson();
- String jsonBody = gson.toJson(artifactDetails);
- // calculate MD5 for json body
- return calculateMD5(jsonBody);
-
- }
-
- public static String calculateMD5(String data) {
- String calculatedMd5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(data);
- // encode base-64 result
- byte[] encodeBase64 = Base64.encodeBase64(calculatedMd5.getBytes());
- String encodeBase64Str = new String(encodeBase64);
- return encodeBase64Str;
-
- }
-
- public static List<Map<String, Object>> getAuditFromMessage(Map auditingMessage) {
- List<Map<String, Object>> auditList = new ArrayList<Map<String, Object>>();
- // JsonElement jElement = new JsonParser().parse(auditingMessage);
- // JsonObject jObject = jElement.getAsJsonObject();
- // JsonObject hitsObject = (JsonObject) jObject.get("hits");
- // JsonArray hitsArray = (JsonArray) hitsObject.get("hits");
- //
- // Iterator<JsonElement> hitsIterator = hitsArray.iterator();
- // while(hitsIterator.hasNext())
- // {
- // JsonElement nextHit = hitsIterator.next();
- // JsonObject jHitObject = nextHit.getAsJsonObject();
- // JsonObject jSourceObject = (JsonObject) jHitObject.get("_source");
- //
- // Gson gson=new Gson();
- // String auditUnparsed = jSourceObject.toString();
- //
- // Map<String,Object> map = new HashMap<String,Object>();
- // map = (Map<String,Object>) gson.fromJson(auditUnparsed,
- // map.getClass());
-
- auditList.add(auditingMessage);
- // }
- return auditList;
- }
-
- public static List<CategoryDefinition> parseCategories(RestResponse getAllCategoriesRest) {
-
- List<CategoryDefinition> categories = new ArrayList<>();
- try {
- JsonElement jElement = new JsonParser().parse(getAllCategoriesRest.getResponse());
- JsonArray cagegories = jElement.getAsJsonArray();
- Iterator<JsonElement> iter = cagegories.iterator();
- while (iter.hasNext()) {
- JsonElement next = iter.next();
- CategoryDefinition category = ResponseParser.parseToObject(next.toString(), CategoryDefinition.class);
- categories.add(category);
- }
-
- } catch (Exception e) {
- e.printStackTrace();
- }
-
- return categories;
- }
-
- public static JSONArray getListFromJson(RestResponse res, String field) throws JSONException {
- String valueFromJsonResponse = getValueFromJsonResponse(res.getResponse(), field);
- JSONArray jArr = new JSONArray(valueFromJsonResponse);
-
- return jArr;
- }
-
- public static List<String> getDerivedListFromJson(RestResponse res) throws JSONException {
- JSONArray listFromJson = getListFromJson(res, "derivedFrom");
- List<String> lst = new ArrayList<String>();
- for (int i = 0; i < listFromJson.length(); i++) {
- lst.add(listFromJson.getString(i));
- }
-
- return lst;
- }
-
- public static Map<String, Object> convertStringToMap(String obj) {
- Map<String, Object> object = (Map<String, Object>) JSONValue.parse(obj);
- return object;
- }
-
- public static List<Map<String, Object>> getListOfMapsFromJson(RestResponse res, String field) throws Exception {
- List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
- JSONArray listFromJson = getListFromJson(res, field);
- for (int i = 0; i < listFromJson.length(); i++) {
- Map<String, Object> convertStringToMap = convertStringToMap(listFromJson.getString(i));
- list.add(convertStringToMap);
- }
- return list;
-
- }
-
- public static Map<String, Object> getJsonValueAsMap(RestResponse response, String key) {
- String valueField = getValueFromJsonResponse(response.getResponse(), key);
- Map<String, Object> convertToMap = convertStringToMap(valueField);
- return convertToMap;
- }
-
- public static String getJsonObjectValueByKey(String metadata, String key) {
- JsonElement jelement = new JsonParser().parse(metadata);
-
- JsonObject jobject = jelement.getAsJsonObject();
- Object obj = jobject.get(key);
- if (obj == null) {
- return null;
- } else {
- return obj.toString();
- }
- }
-
- public static Map<String, List<Component>> convertCatalogResponseToJavaObject(String response) {
-
- // Map<String, ArrayList<Component>> map = new HashMap<String,
- // ArrayList<Component>>();
- Map<String, List<Component>> map = new HashMap<String, List<Component>>();
-
- JsonElement jElement = new JsonParser().parse(response);
- JsonObject jObject = jElement.getAsJsonObject();
- JsonArray jArrReousrces = jObject.getAsJsonArray("resources");
- JsonArray jArrServices = jObject.getAsJsonArray("services");
- JsonArray jArrProducts = jObject.getAsJsonArray("products");
-
- //////// RESOURCE/////////////////////////////
- ArrayList<Component> restResponseArray = new ArrayList<>();
- Component component = null;
- for (int i = 0; i < jArrReousrces.size(); i++) {
- String resourceString = (String) jArrReousrces.get(i).toString();
- component = ResponseParser.convertResourceResponseToJavaObject(resourceString);
- restResponseArray.add(component);
- }
-
- map.put("resources", restResponseArray);
-
- ///////// SERVICE/////////////////////////////
-
- restResponseArray = new ArrayList<>();
- component = null;
- for (int i = 0; i < jArrServices.size(); i++) {
- String resourceString = (String) jArrServices.get(i).toString();
- component = ResponseParser.convertServiceResponseToJavaObject(resourceString);
- restResponseArray.add(component);
- }
-
- map.put("services", restResponseArray);
-
- ///////// PRODUCT/////////////////////////////
- restResponseArray = new ArrayList<>();
- component = null;
- for (int i = 0; i < jArrProducts.size(); i++) {
- String resourceString = (String) jArrProducts.get(i).toString();
- component = ResponseParser.convertProductResponseToJavaObject(resourceString);
- restResponseArray.add(component);
- }
-
- map.put("products", restResponseArray);
-
- return map;
-
- }
-
-
- public static Map<Long, ServiceDistributionStatus> convertServiceDistributionStatusToObject(String response) throws ParseException {
-
- Map<Long, ServiceDistributionStatus> serviceDistributionStatusMap = new HashMap<Long, ServiceDistributionStatus>();
- ServiceDistributionStatus serviceDistributionStatusObject = null;
-
- JsonElement jElement = new JsonParser().parse(response);
- JsonObject jObject = jElement.getAsJsonObject();
- JsonArray jDistrStatusArray = jObject.getAsJsonArray("distributionStatusOfServiceList");
-
- for (int i = 0; i < jDistrStatusArray.size(); i++){
- Gson gson = new Gson();
- String servDistrStatus = gson.toJson(jDistrStatusArray.get(i));
- serviceDistributionStatusObject = gson.fromJson(servDistrStatus, ServiceDistributionStatus.class);
- serviceDistributionStatusMap.put(Utils.getEpochTimeFromUTC(serviceDistributionStatusObject.getTimestamp()), serviceDistributionStatusObject);
- }
-
- return serviceDistributionStatusMap;
-
- }
-
- public static Map<String, String> getPropertiesNameType(RestResponse restResponse)
- throws JSONException {
- Map<String, String> propertiesMap = new HashMap<String, String>();
- JSONArray propertiesList = getListFromJson(restResponse, "properties");
- for (int i = 0; i < propertiesList.length() ; i ++){
- JSONObject prop = (JSONObject) JSONValue.parse(propertiesList.get(i).toString());
- String propName = prop.get("name").toString();
- String propType = prop.get("type").toString();
- propertiesMap.put(propName, propType);
- }
-
- return propertiesMap;
- }
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ServiceRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ServiceRestUtils.java
deleted file mode 100644
index 0055dbd982..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ServiceRestUtils.java
+++ /dev/null
@@ -1,285 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utils.rest;
-
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.Map;
-
-import org.json.simple.JSONArray;
-import org.json.simple.JSONObject;
-import org.json.simple.JSONValue;
-import org.openecomp.sdc.be.model.Service;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.ci.tests.api.Urls;
-import org.openecomp.sdc.ci.tests.config.Config;
-import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
-import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
-import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest;
-import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
-import org.openecomp.sdc.ci.tests.utils.Utils;
-import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.gson.Gson;
-
-public class ServiceRestUtils extends BaseRestUtils {
- private static Logger logger = LoggerFactory.getLogger(ServiceRestUtils.class.getName());
- private final static String cacheControl = "no-cache";
- private final static String contentTypeHeaderData = "application/json";
- private final static String acceptHeaderDate = "application/json";
- // ****** CREATE *******
-
- private static Gson gson = new Gson();
-
- public static RestResponse deleteService(String serviceName, String version, User sdncModifierDetails)
- throws IOException {
-
- Config config = Utils.getConfig();
- String url = String.format(Urls.DELETE_SERVICE_BY_NAME_AND_VERSION, config.getCatalogBeHost(),
- config.getCatalogBePort(), serviceName, version);
-
- String userId = sdncModifierDetails.getUserId();
- RestResponse sendDelete = sendDelete(url, userId);
- deleteMarkedServices(userId);
- return sendDelete;
- }
-
- public static RestResponse deleteServiceById(String serviceId, String userId) throws IOException {
-
- Config config = Utils.getConfig();
- String url = String.format(Urls.DELETE_SERVICE, config.getCatalogBeHost(), config.getCatalogBePort(),
- serviceId);
- RestResponse sendDelete = sendDelete(url, userId);
- deleteMarkedServices(userId);
- return sendDelete;
- }
-
- public static void deleteMarkedServices(String userId) throws IOException {
- String url;
- Config config = Utils.getConfig();
- url = String.format(Urls.DELETE_MARKED_SERVICES, config.getCatalogBeHost(), config.getCatalogBePort());
- sendDelete(url, userId);
- }
-
- public static RestResponse createService(ServiceReqDetails service, User user) throws Exception {
- Config config = Utils.getConfig();
- String url = String.format(Urls.CREATE_SERVICE, config.getCatalogBeHost(), config.getCatalogBePort());
- String serviceBodyJson = gson.toJson(service);
-
- logger.debug("Send POST request to create service: {}",url);
- logger.debug("Service body: {}",serviceBodyJson);
-
- RestResponse res = sendPost(url, serviceBodyJson, user.getUserId(), acceptHeaderData);
- if (res.getErrorCode() == STATUS_CODE_CREATED) {
- service.setUniqueId(ResponseParser.getUniqueIdFromResponse(res));
- service.setVersion(ResponseParser.getVersionFromResponse(res));
- service.setUUID(ResponseParser.getUuidFromResponse(res));
- // Creator details never change after component is created - Ella,
- // 12/1/2016
- service.setCreatorUserId(user.getUserId());
- service.setCreatorFullName(user.getFullName());
- }
-
- return res;
- }
-
- public static RestResponse updateService(ServiceReqDetails service, User user) throws Exception {
- Config config = Utils.getConfig();
- String url = String.format(Urls.UPDATE_SERVICE_METADATA, config.getCatalogBeHost(), config.getCatalogBePort(),
- service.getUniqueId());
- String serviceBodyJson = gson.toJson(service);
-
- logger.debug("Send PUT request to create service: {}",url);
- logger.debug("Service body: {}",serviceBodyJson);
-
- RestResponse res = sendPut(url, serviceBodyJson, user.getUserId(), acceptHeaderData);
- if (res.getErrorCode() == STATUS_CODE_CREATED) {
- service.setUniqueId(ResponseParser.getUniqueIdFromResponse(res));
- service.setVersion(ResponseParser.getVersionFromResponse(res));
- }
-
- return res;
- }
-
- public static RestResponse getService(String serviceId) throws IOException {
-
- Config config = Utils.getConfig();
- String url = String.format(Urls.GET_SERVICE, config.getCatalogBeHost(), config.getCatalogBePort(), serviceId);
- return getServiceFromUrl(url, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), false);
- }
-
- public static RestResponse getService(ServiceReqDetails serviceReqDetails, User sdncModifierDetails)
- throws IOException {
-
- Config config = Utils.getConfig();
- String url = String.format(Urls.GET_SERVICE, config.getCatalogBeHost(), config.getCatalogBePort(),
- serviceReqDetails.getUniqueId());
- return getServiceFromUrl(url, sdncModifierDetails, false);
- }
-
- public static RestResponse getService(String serviceId, User sdncModifierDetails) throws IOException {
-
- Config config = Utils.getConfig();
- String url = String.format(Urls.GET_SERVICE, config.getCatalogBeHost(), config.getCatalogBePort(), serviceId);
- return getServiceFromUrl(url, sdncModifierDetails, false);
- }
-
- public static RestResponse getServiceByNameAndVersion(User sdncModifierDetails, String serviceName,
- String serviceVersion) throws IOException {
- Config config = Utils.getConfig();
- String url = String.format(Urls.GET_SERVICE_BY_NAME_AND_VERSION, config.getCatalogBeHost(),
- config.getCatalogBePort(), serviceName, serviceVersion);
- return getServiceFromUrl(url, sdncModifierDetails, false);
- }
-
- public static RestResponse getServiceFromUrl(String url, User sdncModifierDetails, boolean isCached)
- throws IOException {
- Map<String, String> headersMap = prepareHeadersMap(sdncModifierDetails, isCached);
- HttpRequest http = new HttpRequest();
- logger.debug("Send GET request to create service: {}",url);
- logger.debug("Service headers: {}",headersMap);
- RestResponse sendGetServerRequest = http.httpSendGet(url, headersMap);
-
- return sendGetServerRequest;
- }
-
- public static Map<String, String> prepareHeadersMap(User sdncModifierDetails, boolean isCached) {
- Map<String, String> headersMap = new HashMap<String, String>();
- if (isCached)
- headersMap.put(HttpHeaderEnum.CACHE_CONTROL.getValue(), cacheControl);
-
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
- headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId());
- return headersMap;
- }
-
- public static RestResponse approveServiceDistribution(String serviceId, String userId) throws Exception {
- return changeServiceDistributionState(serviceId, userId, Urls.APPROVE_DISTRIBUTION);
- }
-
- public static RestResponse rejectServiceDistribution(String serviceId, String userId) throws Exception {
- return changeServiceDistributionState(serviceId, userId, Urls.REJECT_DISTRIBUTION);
- }
-
- // Benny
- public static RestResponse rejectServiceDistribution(String serviceId, String userId, String comment)
- throws Exception {
- Config config = Utils.getConfig();
- String url = String.format(Urls.REJECT_DISTRIBUTION, config.getCatalogBeHost(), config.getCatalogBePort(),
- serviceId);
- String userBodyJson = gson.toJson(comment);
- return sendPost(url, userBodyJson, userId, acceptHeaderData);
-
- }
-
- private static RestResponse changeServiceDistributionState(String serviceId, String userId, String distributionUrl)
- throws Exception {
- Config config = Utils.getConfig();
- String url = String.format(distributionUrl, config.getCatalogBeHost(), config.getCatalogBePort(), serviceId);
- String defComment = "{ userRemarks : \"this is an test\" }";
- String userBodyJson = gson.toJson(defComment);
- return sendPost(url, userBodyJson, userId, acceptHeaderData);
-
- }
-
- public static RestResponse getServiceLatestVersionList(User sdncModifierDetails) throws IOException {
-
- Config config = Utils.getConfig();
- String url = String.format(Urls.GET_SERVICE_lATEST_VERSION, config.getCatalogBeHost(),
- config.getCatalogBePort());
-
- return sendGet(url, sdncModifierDetails.getUserId());
-
- }
-
- public static RestResponse createServiceByHttpMethod(ServiceReqDetails serviceDetails, User sdncModifierDetails,
- String method, String urls) throws IOException {
- Map<String, String> headersMap = prepareHeadersMap(sdncModifierDetails, true);
-
- Config config = Utils.getConfig();
- String serviceBodyJson = gson.toJson(serviceDetails);
- HttpRequest http = new HttpRequest();
- String url = String.format(urls, config.getCatalogBeHost(), config.getCatalogBePort());
- // TODO: ADD AUTHENTICATION IN REQUEST
- logger.debug(url);
- logger.debug("Send {} request to create user: {}",method,url);
- logger.debug("User body: {}",serviceBodyJson);
- logger.debug("User headers: {}",headersMap);
- RestResponse sendCreateUserRequest = http.httpSendByMethod(url, method, serviceBodyJson, headersMap);
-
- return sendCreateUserRequest;
-
- }
-
- public static RestResponse deleteServiceByNameAndVersion(User sdncModifierDetails, String serviceName,
- String serviceVersion) throws IOException {
- Config config = Utils.getConfig();
-
- Map<String, String> headersMap = prepareHeadersMap(sdncModifierDetails, true);
-
- HttpRequest http = new HttpRequest();
-
- String url = String.format(Urls.DELETE_SERVICE_BY_NAME_AND_VERSION, config.getCatalogBeHost(),
- config.getCatalogBePort(), serviceName, serviceVersion);
- RestResponse deleteResponse = http.httpSendDelete(url, headersMap);
-
- return deleteResponse;
- }
-
- public static RestResponse getFollowed(User user) throws Exception {
- Config config = Utils.getConfig();
-
- HttpRequest httpRequest = new HttpRequest();
-
- String url = String.format(Urls.GET_FOLLWED_LIST, config.getCatalogBeHost(), config.getCatalogBePort());
-
- Map<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json");
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json");
- headersMap.put(HttpHeaderEnum.USER_ID.getValue(), user.getUserId());
-
- RestResponse getResourceNotAbstarctResponse = httpRequest.httpSendGet(url, headersMap);
-
- return getResourceNotAbstarctResponse;
- }
-
- public static JSONArray getListArrayFromRestResponse(RestResponse restResponse) {
- String json = restResponse.getResponse();
- JSONObject jsonResp = (JSONObject) JSONValue.parse(json);
- JSONArray servicesArray = (JSONArray) jsonResp.get("services");
-
- logger.debug("services= {}",servicesArray);
-
- return servicesArray;
- }
-
- public static RestResponse getDistributionServiceList(Service service, User user) throws IOException {
-
- Config config = Utils.getConfig();
- String url = String.format(Urls.DISTRIBUTION_SERVICE_LIST, config.getCatalogBeHost(), config.getCatalogBePort(), service.getUUID());
- return getServiceFromUrl(url, user, false);
- }
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/UserRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/UserRestUtils.java
deleted file mode 100644
index 6c6a66d863..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/UserRestUtils.java
+++ /dev/null
@@ -1,281 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utils.rest;
-
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.Map;
-
-import org.apache.commons.lang.StringUtils;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.ci.tests.api.Urls;
-import org.openecomp.sdc.ci.tests.config.Config;
-import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
-import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest;
-import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
-import org.openecomp.sdc.ci.tests.run.StartTest;
-import org.openecomp.sdc.ci.tests.utils.Utils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.gson.Gson;
-
-public class UserRestUtils extends BaseRestUtils {
-
- static Gson gson = new Gson();
-
- static Logger logger = LoggerFactory.getLogger(UserRestUtils.class.getName());
- static String contentTypeHeaderData = "application/json";
- static String acceptHeaderDate = "application/json";
-
- public UserRestUtils() {
- super();
-
- StartTest.enableLogger();
- }
-
- public static RestResponse createUser(User sdncUserDetails, User sdncModifierDetails) throws IOException {
-
- Config config = Utils.getConfig();
-
- Map<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
- headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId());
-
- String userBodyJson = gson.toJson(sdncUserDetails);
- HttpRequest http = new HttpRequest();
- String url = String.format(Urls.CREATE_USER, config.getCatalogBeHost(), config.getCatalogBePort());
-
- logger.debug("Send POST request to create user: {}",url);
- logger.debug("User body: {}",userBodyJson);
- logger.debug("User headers: {}",headersMap);
- RestResponse sendCreateUserRequest = http.httpSendPost(url, userBodyJson, headersMap);
-
- return sendCreateUserRequest;
-
- }
-
- public static RestResponse deactivateUser(User sdncUserDetails, User sdncModifierDetails) throws IOException {
- return deleteUser(sdncUserDetails, sdncModifierDetails, true);
- }
-
- public static RestResponse deActivateUser(User sdncUserDetails, User sdncModifierDetails) throws IOException {
- return deleteUser(sdncUserDetails, sdncModifierDetails, false);
- }
-
- public static RestResponse deleteUser(User sdncUserDetails, User sdncModifierDetails, boolean isForceDelete)
- throws IOException {
-
- Config config = Utils.getConfig();
-
- Map<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
- headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId());
- if (isForceDelete) {
- headersMap.put(User.FORCE_DELETE_HEADER_FLAG, User.FORCE_DELETE_HEADER_FLAG);
- }
-
- HttpRequest http = new HttpRequest();
- String url = String.format(Urls.DELETE_USER, config.getCatalogBeHost(), config.getCatalogBePort(),
- sdncUserDetails.getUserId());
- RestResponse sendDeleteUserRequest = http.httpSendDelete(url, headersMap);
- return sendDeleteUserRequest;
-
- }
-
- public static RestResponse updateUser(User sdncUserDetails, User sdncModifierDetails)
- throws IOException, CloneNotSupportedException {
-
- Config config = Utils.getConfig();
- User user = new User(sdncModifierDetails);
-
- Map<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
- headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId());
-
- user.setUserId(StringUtils.EMPTY);
- user.setRole(StringUtils.EMPTY);
-
- Gson gson = new Gson();
- String userBodyJson = gson.toJson(user);
- logger.debug("userBodyJson: {}",userBodyJson);
- HttpRequest http = new HttpRequest();
- String url = String.format(Urls.UPDATE_USER, config.getCatalogBeHost(), config.getCatalogBePort(),
- sdncModifierDetails.getUserId());
- RestResponse sendUpdateUserRequest = http.httpSendPost(url, userBodyJson, headersMap);
-
- return sendUpdateUserRequest;
- }
-
- /// Benny
- public static RestResponse updateUserRole(User sdncUserDetails, User sdncModifierDetails, String userIdToUpdate)
- throws IOException {
-
- Config config = Utils.getConfig();
-
- Map<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
- headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId());
-
- Gson gson = new Gson();
- String userBodyJson = gson.toJson(sdncUserDetails);
- logger.debug("userBodyJson: {}",userBodyJson);
- HttpRequest http = new HttpRequest();
- String url = String.format(Urls.UPDATE_USER_ROLE, config.getCatalogBeHost(), config.getCatalogBePort(),
- userIdToUpdate);
- RestResponse sendUpdateUserRequest = http.httpSendPost(url, userBodyJson, headersMap);
-
- return sendUpdateUserRequest;
-
- }
-
- public static RestResponse getUser(User sdncUserDetails, User sdncModifierDetails) throws IOException {
-
- Config config = Utils.getConfig();
-
- Map<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
- headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId());
- HttpRequest http = new HttpRequest();
- String url = String.format(Urls.GET_USER, config.getCatalogBeHost(), config.getCatalogBePort(),
- sdncUserDetails.getUserId());
- RestResponse sendGetUserRequest = http.httpSendGet(url, headersMap);
- return sendGetUserRequest;
-
- }
-
- public static RestResponse getAllAdminUsers(User sdncModifierDetails) throws IOException {
-
- Config config = Utils.getConfig();
-
- Map<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
- headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId());
-
- // Gson gson = new Gson();
- // String userBodyJson = gson.toJson(sdncModifierDetails);
- // System.out.println(userBodyJson);
- HttpRequest http = new HttpRequest();
- String url = String.format(Urls.GET_ALL_ADMIN_USERS, config.getCatalogBeHost(), config.getCatalogBePort());
- logger.debug("Send following url: {} and headers: {}",url,headersMap.toString());
- RestResponse sendGetUserRequest = http.httpSendGet(url, headersMap);
-
- return sendGetUserRequest;
-
- }
-
- // US571255
- public static RestResponse getUsersByRoles(User sdncModifierDetails, String roles) throws IOException {
-
- Config config = Utils.getConfig();
- Map<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
- headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId());
- HttpRequest http = new HttpRequest();
- String url;
- if (roles == "/") {
- url = String.format(Urls.GET_ALL_USERS, config.getCatalogBeHost(), config.getCatalogBePort());
- } else {
- url = String.format(Urls.GET_USERS_BY_ROLES, config.getCatalogBeHost(), config.getCatalogBePort(), roles);
-
- }
- logger.debug("Send following url: {} and headers: {}",url,headersMap.toString());
- RestResponse sendGetUserRequest = http.httpSendGet(url, headersMap);
- return sendGetUserRequest;
- }
-
- public static RestResponse getUsersByRolesHttpCspAtuUidIsMissing(User sdncModifierDetails, String roles)
- throws Exception {
-
- Config config = Utils.getConfig();
- Map<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
- headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId());
- headersMap.remove("USER_ID");
- HttpRequest http = new HttpRequest();
- String url = String.format(Urls.GET_USERS_BY_ROLES, config.getCatalogBeHost(), config.getCatalogBePort(),
- roles);
- logger.debug(
- "Send following url without USER_ID header : " + url + " headers: " + headersMap.toString());
-
- RestResponse sendGetUserRequest = http.httpSendGet(url, headersMap);
- return sendGetUserRequest;
- }
-
- public static RestResponse authorizedUserTowardsCatalogBe(User sdncUserDetails) throws IOException {
-
- Map<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json");
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json");
- headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncUserDetails.getUserId());
- if (sdncUserDetails.getFirstName() != null) {
- headersMap.put(HttpHeaderEnum.HTTP_CSP_FIRSTNAME.getValue(), sdncUserDetails.getFirstName());
- }
- if (sdncUserDetails.getLastName() != null) {
- headersMap.put(HttpHeaderEnum.HTTP_CSP_LASTNAME.getValue(), sdncUserDetails.getLastName());
- }
- if (sdncUserDetails.getEmail() != null) {
- headersMap.put(HttpHeaderEnum.HTTP_CSP_EMAIL.getValue(), sdncUserDetails.getEmail());
- }
-
- logger.debug("headersMap: {}",headersMap.toString());
-
- Config config = Utils.getConfig();
- HttpRequest http = new HttpRequest();
- String url = String.format(Urls.AUTHORIZE_USER, config.getCatalogBeHost(), config.getCatalogBePort());
- logger.debug("Send GET request to login as seal user : {}",url);
- return http.httpSendGet(url, headersMap);
- }
-
- public static RestResponse authorizedUserTowardsCatalogBeQA(User sdncUserDetails) throws IOException {
-
- Map<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json");
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json");
- headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncUserDetails.getUserId());
- if (sdncUserDetails.getFirstName() != null) {
- headersMap.put(HttpHeaderEnum.HTTP_CSP_FIRSTNAME.getValue(), sdncUserDetails.getFirstName());
- }
- if (sdncUserDetails.getLastName() != null) {
- headersMap.put(HttpHeaderEnum.HTTP_CSP_LASTNAME.getValue(), sdncUserDetails.getLastName());
- }
- if (sdncUserDetails.getEmail() != null) {
- headersMap.put(HttpHeaderEnum.HTTP_CSP_EMAIL.getValue(), sdncUserDetails.getEmail());
- }
-
- logger.debug("headersMap: {}",headersMap.toString());
-
- Config config = Utils.getConfig();
- HttpRequest http = new HttpRequest();
- String url = String.format(Urls.AUTHORIZE_USER, config.getCatalogBeHost(), config.getCatalogBePort());
- logger.debug("Send GET request to login as seal user : {}",url);
- return http.httpSendGet(url, headersMap);
- }
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ArtifactValidationUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ArtifactValidationUtils.java
deleted file mode 100644
index 50ecdd8520..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ArtifactValidationUtils.java
+++ /dev/null
@@ -1,223 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utils.validation;
-
-import static org.testng.AssertJUnit.assertEquals;
-import static org.testng.AssertJUnit.assertTrue;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.List;
-import java.util.Map;
-
-import org.codehaus.jackson.JsonParseException;
-import org.codehaus.jackson.JsonProcessingException;
-import org.codehaus.jackson.map.ObjectMapper;
-import org.openecomp.sdc.be.model.ArtifactDefinition;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.resources.data.ESArtifactData;
-import org.openecomp.sdc.ci.tests.config.Config;
-import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
-import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
-import org.openecomp.sdc.ci.tests.utils.Decoder;
-import org.openecomp.sdc.ci.tests.utils.Utils;
-import org.openecomp.sdc.ci.tests.utils.general.FileUtils;
-import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
-
-import com.google.gson.JsonElement;
-import com.google.gson.JsonParser;
-
-public class ArtifactValidationUtils {
-
- private static String desc = "description";
- private static String artifactType = "artifactType";
- private static String artifactName = "artifactName";
- private static String artifactChecksum = "artifactChecksum";
- private static String uniqueId = "uniqueId";
- protected Utils utils;
-
- public static void validateInformationalArtifact(ArtifactReqDetails expectedArtifact,
- Map<String, Object> actualArtifact) {
- assertTrue("description is not as expected",
- expectedArtifact.getDescription().equals(actualArtifact.get(desc).toString()));
- assertTrue("artifactType is not as expected",
- expectedArtifact.getArtifactType().toUpperCase().equals(actualArtifact.get(artifactType).toString()));
- assertTrue("artifactName is not as expected",
- expectedArtifact.getArtifactName().equals(actualArtifact.get(artifactName).toString()));
- assertTrue("uniqueId is not as expected",
- expectedArtifact.getUniqueId().equals(actualArtifact.get(uniqueId).toString()));
- assertTrue("description is not as expected", expectedArtifact.getArtifactLabel().toLowerCase()
- .equals(actualArtifact.get("artifactLabel").toString()));
- }
-
- public static void validateArtifactsNumberInComponent(Component component, ArtifactGroupTypeEnum artifactGroupType,
- ArtifactTypeEnum artifactType, int expectedNumber) {
- Map<String, ArtifactDefinition> deploymentArtifacts;
- int counter = 0;
- if (artifactGroupType == ArtifactGroupTypeEnum.DEPLOYMENT) {
- deploymentArtifacts = component.getDeploymentArtifacts();
- } else {
- deploymentArtifacts = component.getArtifacts();
- }
- if (deploymentArtifacts != null) {
- for (ArtifactDefinition artifactDefinition : deploymentArtifacts.values()) {
- if (artifactDefinition.getArtifactType().equals(artifactType.getType())) {
- counter++;
- }
- }
- }
- assertEquals("Unexpected number of " + artifactGroupType.getType() + " artifacts in component", expectedNumber,
- counter);
- }
-
- // Benny
- public static void validateArtifactsNumberInComponentInstance(ComponentInstance componentInstance,
- ArtifactGroupTypeEnum artifactGroupType, ArtifactTypeEnum artifactType, int expectedNumber) {
- Map<String, ArtifactDefinition> deploymentArtifacts = null;
- int counter = 0;
- if (artifactGroupType == ArtifactGroupTypeEnum.DEPLOYMENT) {
- deploymentArtifacts = componentInstance.getDeploymentArtifacts();
- }
- if (deploymentArtifacts != null) {
- for (ArtifactDefinition artifactDefinition : deploymentArtifacts.values()) {
- if (artifactDefinition.getArtifactType().equals(artifactType.getType())) {
- counter++;
- }
- }
- }
- assertEquals("Unexpected number of " + artifactGroupType.getType() + " artifacts in component", expectedNumber,
- counter);
- }
-
- public static ESArtifactData parseArtifactRespFromES(RestResponse resResponse)
- throws JsonParseException, JsonProcessingException, Exception {
- String bodyToParse = resResponse.getResponse();
- JsonElement jElement = new JsonParser().parse(bodyToParse);
- JsonElement jsourceElement = jElement.getAsJsonObject().get("_source");
-
- ObjectMapper mapper = new ObjectMapper();
- ESArtifactData esArtifactObject = mapper.readValue(jsourceElement.toString(), ESArtifactData.class);
-
- return esArtifactObject;
- }
-
- public static void validateArtifactReqVsResp(ArtifactReqDetails expectedArtifactDetails,
- ArtifactDefinition actualArtifactJavaObject) {
- String expected;
-
- expected = expectedArtifactDetails.getArtifactName();
- if (expected == null)
- expected = "";
- assertEquals("artifact name is not correct ", expected, actualArtifactJavaObject.getArtifactName());
-
- expected = expectedArtifactDetails.getArtifactType();
- if (expected == null)
- expected = "";
- assertEquals("artifact type is not correct ", expected, actualArtifactJavaObject.getArtifactType());
-
- expected = expectedArtifactDetails.getDescription();
- if (expected == null)
- expected = "";
- assertEquals("artifact description is not correct ", expected, actualArtifactJavaObject.getDescription());
-
- expected = expectedArtifactDetails.getArtifactLabel();
- if (expected == null || expected == "") {
- expected = expectedArtifactDetails.getArtifactName().toLowerCase().substring(0,
- expectedArtifactDetails.getArtifactName().lastIndexOf("."));
- // expected = tmp.substring(0,
- // artifactInfo.getArtifactName().lastIndexOf("."));
- }
- assertEquals("artifact label is not correct ", expected, actualArtifactJavaObject.getArtifactLabel());
-
- expected = expectedArtifactDetails.getUrl();
- if (expected != "") {
- assertEquals(expected, actualArtifactJavaObject.getApiUrl());
- assertEquals(expectedArtifactDetails.getArtifactDisplayName(),
- actualArtifactJavaObject.getArtifactDisplayName());
- }
-
- // assertEquals(validChecksum,
- // actualArtifactJavaObject.getArtifactChecksum());
-
- // expected = expectedArtifactDetails.getArtifactDisplayName();
- // if (expected != "")
- // {
- // assertEquals(expected,
- // actualArtifactJavaObject.getArtifactDisplayName());
- // }
-
- boolean actual = actualArtifactJavaObject.getMandatory();
- assertEquals(expectedArtifactDetails.isMandatory(), actual);
-
- if (actualArtifactJavaObject.getServiceApi()) {
-
- boolean actual2 = actualArtifactJavaObject.getServiceApi();
- assertEquals(expectedArtifactDetails.isServiceApi(), actual2);
- }
-
- }
-
- public static void validateEsArtifactReqVsResp(ArtifactReqDetails expectedArtifactInfo,
- ESArtifactData esArtifactData) throws Exception {
- String expectedArtifactUid = expectedArtifactInfo.getUniqueId();
- if (expectedArtifactUid == null)
- expectedArtifactUid = "";
- assertEquals("artifact name is not correct ", expectedArtifactUid, esArtifactData.getId());
-
- String actualPayload = Decoder.encode(esArtifactData.getData().array());
- assertEquals("artifact payloadData is not correct ", expectedArtifactInfo.getPayload(), actualPayload);
- }
-
- public static List<String> getListOfArtifactFromFolder(String folderName) throws IOException, Exception {
- Config config = Utils.getConfig();
- String sourceDir = config.getResourceConfigDir();
- String testResourcesPath = sourceDir + File.separator + folderName;
- List<String> listofFiles = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath);
- return listofFiles;
- }
-
- public static ArtifactReqDetails replaceDefaultArtWithArtFromList_(ArtifactReqDetails heatArtifactDetails,
- String heatExtension, String folderName, int positionInlist) throws IOException, Exception {
-
- Config config = Utils.getConfig();
- String ext = heatExtension;
- String sourceDir = config.getResourceConfigDir();
- String testResourcesPath = sourceDir + File.separator + folderName;
- List<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath);
- String payload = FileUtils.loadPayloadFile(listFileName, ext, true);
- heatArtifactDetails.setPayload(payload);
- heatArtifactDetails.setArtifactName(listFileName.get(positionInlist) + "." + ext);
- return heatArtifactDetails;
- }
-
- public static ArtifactReqDetails replaceDefaultArtWithArtFromList(ArtifactReqDetails heatArtifactDetails,
- String heatExtension, String folderName, int positionInlist) throws IOException, Exception {
- List<String> listOfArtifactFromFolder = getListOfArtifactFromFolder(folderName);
- String payload = FileUtils.loadPayloadFileFromListUsingPosition(listOfArtifactFromFolder, heatExtension, true,
- positionInlist);
- heatArtifactDetails.setPayload(payload);
- heatArtifactDetails.setArtifactName(heatArtifactDetails.getArtifactType()
- + listOfArtifactFromFolder.get(positionInlist) + "." + heatExtension);
- return heatArtifactDetails;
- }
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/AuditValidationUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/AuditValidationUtils.java
deleted file mode 100644
index 0d16308e26..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/AuditValidationUtils.java
+++ /dev/null
@@ -1,1390 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utils.validation;
-
-import static org.testng.AssertJUnit.assertEquals;
-import static org.testng.AssertJUnit.assertTrue;
-
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.log4j.Logger;
-import org.codehaus.jettison.json.JSONArray;
-import org.codehaus.jettison.json.JSONException;
-import org.codehaus.jettison.json.JSONObject;
-import org.javatuples.Pair;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.datatypes.elements.ConsumerDataDefinition;
-import org.openecomp.sdc.be.model.ArtifactDefinition;
-import org.openecomp.sdc.be.model.LifecycleStateEnum;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.model.category.CategoryDefinition;
-import org.openecomp.sdc.be.model.category.GroupingDefinition;
-import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
-import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
-import org.openecomp.sdc.ci.tests.api.Urls;
-import org.openecomp.sdc.ci.tests.config.Config;
-import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.enums.AuditEnum;
-import org.openecomp.sdc.ci.tests.datatypes.enums.AuditJsonKeysEnum;
-import org.openecomp.sdc.ci.tests.datatypes.enums.ComponentType;
-import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo;
-import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedAuthenticationAudit;
-import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedCategoryAudit;
-import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedDistDownloadAudit;
-import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedEcomConsumerAudit;
-import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedExternalAudit;
-import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedGetUserListAudit;
-import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedProductAudit;
-import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedResourceAuditJavaObject;
-import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedUserCRUDAudit;
-import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest;
-import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
-import org.openecomp.sdc.ci.tests.run.StartTest;
-import org.openecomp.sdc.ci.tests.utils.ArtifactUtils;
-import org.openecomp.sdc.ci.tests.utils.Utils;
-import org.openecomp.sdc.ci.tests.utils.cassandra.CassandraUtils;
-import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
-import org.openecomp.sdc.ci.tests.utils.rest.CategoryRestUtils.CategoryAuditJsonKeysEnum;
-import org.openecomp.sdc.ci.tests.utils.rest.ConsumerRestUtils.EcompConsumerAuditJsonKeysEnum;
-import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
-import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
-
-import com.datastax.driver.core.ColumnDefinitions;
-import com.datastax.driver.core.Row;
-
-public class AuditValidationUtils {
- protected static Logger logger = Logger.getLogger(AuditValidationUtils.class.getName());
- private static final String auditKeySpaceName = "sdcaudit";
-
- public AuditValidationUtils() {
- super();
-
- StartTest.enableLogger();
- logger = Logger.getLogger(AuditValidationUtils.class.getName());
-
- }
-
- public static String buildAuditDescription(ErrorInfo errorInfo, List<String> variables) {
-
- String auditDesc = errorInfo.getMessageId() + ": " + errorInfo.getMessage();
- for (int i = 0; i < variables.size(); i++) {
- if (auditDesc.contains("%" + (i + 1))) {
- auditDesc = auditDesc.replace("%" + (i + 1), variables.get(i));
- }
- }
-
- return auditDesc;
- }
-
- public static String getModifierString(String userName, String uid) {
-
- if (userName.isEmpty() && uid.isEmpty())
- return "(UNKNOWN)";
-
- StringBuilder sb = new StringBuilder();
- sb.append(userName).append("(").append(uid).append(")");
- return sb.toString();
-
- }
-
- public static void validateAuditDownloadExternalAPI(ExpectedResourceAuditJavaObject resourceAuditJavaObject,
- String action, String body, boolean checkAllFields) throws Exception {
- Map<String, Object> actualAuditRecords = new HashMap<String, Object>();
- // Andrey's comment
- // actualAuditRecords = parseAuditResourceByAction(action, body);
- actualAuditRecords = parseAuditResourceByAction(action, null);
-
- // List<Map<String, Object>> actualAuditRecords = new
- // ArrayList<Map<String, Object>>();
- // actualAuditRecords = parseAuditResourceByActionToList(action, body);
-
- validateField(actualAuditRecords, AuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action);
- validateField(actualAuditRecords, AuditJsonKeysEnum.RESOURCE_NAME.getAuditJsonKeyName(),
- resourceAuditJavaObject.getResourceName());
- validateField(actualAuditRecords, AuditJsonKeysEnum.RESOURCE_TYPE.getAuditJsonKeyName(),
- resourceAuditJavaObject.getResourceType());
-
- validateField(actualAuditRecords, AuditJsonKeysEnum.STATUS.getAuditJsonKeyName(),
- resourceAuditJavaObject.getStatus());
- validateField(actualAuditRecords, AuditJsonKeysEnum.DESCRIPTION.getAuditJsonKeyName(),
- resourceAuditJavaObject.getDesc());
-
- // validateField(actualAuditRecords,
- // AuditJsonKeysEnum.CONSUMER_ID.getAuditJsonKeyName(),
- // resourceAuditJavaObject.getCONSUMER_ID());
- // validateField(actualAuditRecords,
- // AuditJsonKeysEnum.RESOURCE_URL.getAuditJsonKeyName(),
- // resourceAuditJavaObject.getRESOURCE_URL());
-
- }
-
- public static void validateAudit(ExpectedResourceAuditJavaObject resourceAuditJavaObject, String action,
- String body, boolean checkAllFields) throws Exception {
- Map<String, Object> actualAuditRecords = new HashMap<String, Object>();
- // Andrey's comment
- // actualAuditRecords = parseAuditResourceByAction(action, body);
- actualAuditRecords = parseAuditResourceByAction(action, null);
-
- if ((resourceAuditJavaObject.getModifierName() != null) && (resourceAuditJavaObject.getModifierUid() != null)) {
- resourceAuditJavaObject.setModifierUid(getModifierString(resourceAuditJavaObject.getModifierName(),
- resourceAuditJavaObject.getModifierUid()));
- }
-
- validateField(actualAuditRecords, AuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action);
- validateField(actualAuditRecords, AuditJsonKeysEnum.RESOURCE_NAME.getAuditJsonKeyName(),
- resourceAuditJavaObject.getResourceName());
- validateField(actualAuditRecords, AuditJsonKeysEnum.RESOURCE_TYPE.getAuditJsonKeyName(),
- resourceAuditJavaObject.getResourceType());
- validateField(actualAuditRecords, AuditJsonKeysEnum.PREV_VERSION.getAuditJsonKeyName(),
- resourceAuditJavaObject.getPrevVersion());
- validateField(actualAuditRecords, AuditJsonKeysEnum.CURR_VERSION.getAuditJsonKeyName(),
- resourceAuditJavaObject.getCurrVersion());
-
- validateField(actualAuditRecords, AuditJsonKeysEnum.MODIFIER.getAuditJsonKeyName(),
- resourceAuditJavaObject.getModifierUid());
- validateField(actualAuditRecords, AuditJsonKeysEnum.PREV_STATE.getAuditJsonKeyName(),
- resourceAuditJavaObject.getPrevState());
- validateField(actualAuditRecords, AuditJsonKeysEnum.CURR_STATE.getAuditJsonKeyName(),
- resourceAuditJavaObject.getCurrState());
- validateField(actualAuditRecords, AuditJsonKeysEnum.STATUS.getAuditJsonKeyName(),
- resourceAuditJavaObject.getStatus());
- // validateField(map2, AuditJsonKeysEnum.STATUS.getAuditJsonKeyName(),
- // Double.parseDouble(resourceAuditJavaObject.getStatus()));
- validateField(actualAuditRecords, AuditJsonKeysEnum.DESCRIPTION.getAuditJsonKeyName(),
- resourceAuditJavaObject.getDesc());
- validateField(actualAuditRecords, AuditJsonKeysEnum.COMMENT.getAuditJsonKeyName(),
- resourceAuditJavaObject.getComment());
- // validateField(map2,
- // AuditJsonKeysEnum.ARTIFACT_DATA.getAuditJsonKeyName(),
- // resourceAuditJavaObject.getArtifactData());
- validateField(actualAuditRecords, AuditJsonKeysEnum.TOSCA_NODE_TYPE.getAuditJsonKeyName(),
- resourceAuditJavaObject.getToscaNodeType());
- validateField(actualAuditRecords, AuditJsonKeysEnum.CURR_ARTIFACT_UUID.getAuditJsonKeyName(),
- resourceAuditJavaObject.getCurrArtifactUuid());
- validateField(actualAuditRecords, AuditJsonKeysEnum.PREV_ARTIFACT_UUID.getAuditJsonKeyName(),
- resourceAuditJavaObject.getPrevArtifactUuid());
-
- validateAtifactDataField(actualAuditRecords, AuditJsonKeysEnum.ARTIFACT_DATA.getAuditJsonKeyName(),
- resourceAuditJavaObject.getArtifactData(), checkAllFields);
- }
-
- public static void validateExternalAudit(ExpectedExternalAudit externalAuditObject, String action,
- Map<AuditingFieldsKeysEnum, String> body) throws Exception {
-
- Map<String, Object> actualAuditRecord = new HashMap<String, Object>();
- actualAuditRecord = parseAuditResourceByAction(action, body);
-
- validateField(actualAuditRecord, AuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action);
- validateField(actualAuditRecord, AuditJsonKeysEnum.CONSUMER_ID.getAuditJsonKeyName(),
- externalAuditObject.getCONSUMER_ID());
- // TODO
- validateField(actualAuditRecord, AuditJsonKeysEnum.RESOURCE_URL.getAuditJsonKeyName(),
- externalAuditObject.getRESOURCE_URL());
- //TODO
- validateField(actualAuditRecord, AuditJsonKeysEnum.RESOURCE_NAME.getAuditJsonKeyName(),
- externalAuditObject.getRESOURCE_NAME());
- validateField(actualAuditRecord, AuditJsonKeysEnum.SERVICE_INSTANCE_ID.getAuditJsonKeyName(),
- externalAuditObject.getSERVICE_INSTANCE_ID());
- //TODO
- validateField(actualAuditRecord, AuditJsonKeysEnum.RESOURCE_TYPE.getAuditJsonKeyName(),
- externalAuditObject.getRESOURCE_TYPE());
- validateField(actualAuditRecord, AuditJsonKeysEnum.STATUS.getAuditJsonKeyName(),
- externalAuditObject.getSTATUS());
- validateField(actualAuditRecord, AuditJsonKeysEnum.DESCRIPTION.getAuditJsonKeyName(),
- externalAuditObject.getDESC());
- //TODO
-// validateField(actualAuditRecord, AuditJsonKeysEnum.MODIFIER.getAuditJsonKeyName(),
-// externalAuditObject.getMODIFIER());
- validateField(actualAuditRecord, AuditJsonKeysEnum.PREV_ARTIFACT_UUID.getAuditJsonKeyName(),
- externalAuditObject.getPREV_ARTIFACT_UUID());
- validateField(actualAuditRecord, AuditJsonKeysEnum.CURR_ARTIFACT_UUID.getAuditJsonKeyName(),
- externalAuditObject.getCURR_ARTIFACT_UUID());
- //TODO
- validateField(actualAuditRecord, AuditJsonKeysEnum.ARTIFACT_DATA.getAuditJsonKeyName(),
- externalAuditObject.getARTIFACT_DATA());
-
- }
-
- public enum ArtifactDataFieldEnum {
- attGroup, artLable, artType, artName, artTimeout, artPayloadUUID, artVersion, artUUID
- }
-
- private static void validateAtifactDataField(Map<String, Object> map, String auditJsonKeyName,
- String expectedArtifactData, boolean checkAllFields) {
- Map<ArtifactDataFieldEnum, String> expectedArtifactDataFileds = new HashMap<ArtifactDataFieldEnum, String>();
- Map<ArtifactDataFieldEnum, String> actualAtifactDataFileds = new HashMap<ArtifactDataFieldEnum, String>();
- if (expectedArtifactData != null) {
- String[] expected = expectedArtifactData.split(",");
-
- assertTrue("Audit field " + auditJsonKeyName + " not found", map.containsKey(auditJsonKeyName));
- String actualValue = (String) map.get(auditJsonKeyName);
- String[] actual = actualValue.split(",");
-
- if (expected.length == 1 && actual.length == 1) {
- assertEquals(expectedArtifactData, actualValue);
- return;
- }
-
- assertEquals(ArtifactDataFieldEnum.values().length, expected.length);
- assertEquals(ArtifactDataFieldEnum.values().length, actual.length);
-
- for (ArtifactDataFieldEnum field : ArtifactDataFieldEnum.values()) {
-
- expectedArtifactDataFileds.put(field, expected[field.ordinal()]);
- actualAtifactDataFileds.put(field, actual[field.ordinal()]);
- }
- for (Map.Entry<ArtifactDataFieldEnum, String> entry : expectedArtifactDataFileds.entrySet()) {
- ArtifactDataFieldEnum field = entry.getKey();
- if (checkAllFields || (!field.equals(ArtifactDataFieldEnum.artVersion)
- && !field.equals(ArtifactDataFieldEnum.artUUID))) {
- assertTrue("Audit field ArtifactData dosn't containt " + field,
- actualAtifactDataFileds.containsKey(field));
- assertEquals("Audit field ArtifactData dosn't equal " + field,
- expectedArtifactDataFileds.get(field), actualAtifactDataFileds.get(field));
- }
-
- }
- }
- }
-
- // //Benny
- public static void validateEcompConsumerAudit(ExpectedEcomConsumerAudit ecompConsumerAuditJavaObject, String action)
- throws Exception {
-
- String fixedAction = BaseRestUtils.encodeUrlForDownload(action);
- Map<String, Object> map2 = new HashMap<String, Object>();
- map2 = parseAuditResourceByAction(fixedAction, null);
-
- validateField(map2, EcompConsumerAuditJsonKeysEnum.MODIFIER.getAuditJsonKeyName(),
- ecompConsumerAuditJavaObject.getModifier());
- validateField(map2, EcompConsumerAuditJsonKeysEnum.ECOMP_USER.getAuditJsonKeyName(),
- ecompConsumerAuditJavaObject.getEcomUser());
- validateField(map2, EcompConsumerAuditJsonKeysEnum.STATUS.getAuditJsonKeyName(),
- ecompConsumerAuditJavaObject.getStatus());
- validateField(map2, EcompConsumerAuditJsonKeysEnum.DESC.getAuditJsonKeyName(),
- ecompConsumerAuditJavaObject.getDesc());
- validateField(map2, EcompConsumerAuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action);
- }
-
- public static void ecompConsumerAuditSuccess(String action, ConsumerDataDefinition consumerDataDefinition,
- User user, int status) throws Exception {
- ExpectedEcomConsumerAudit expectedEcomConsumerAuditJavaObject = new ExpectedEcomConsumerAudit();
- expectedEcomConsumerAuditJavaObject.setAction(action);
- expectedEcomConsumerAuditJavaObject.setEcomUser(
- consumerDataDefinition.getConsumerName() + "," + consumerDataDefinition.getConsumerSalt().toLowerCase()
- + "," + consumerDataDefinition.getConsumerPassword().toLowerCase());
- expectedEcomConsumerAuditJavaObject.setStatus(String.valueOf(status));
- expectedEcomConsumerAuditJavaObject.setDesc("OK");
- expectedEcomConsumerAuditJavaObject.setModifier(user.getFullName() + "(" + user.getUserId() + ")");
- AuditValidationUtils.validateEcompConsumerAudit(expectedEcomConsumerAuditJavaObject, action);
- }
-
- public static void createEcompConsumerAuditFailure(String action, ConsumerDataDefinition consumerDataDefinition,
- User user, ActionStatus errorMessage, Object... variables) throws Exception {
- // validate audit
- ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(errorMessage.name());
- ExpectedEcomConsumerAudit expectedEcomConsumerAuditJavaObject = new ExpectedEcomConsumerAudit();
- expectedEcomConsumerAuditJavaObject.setAction(action);
- expectedEcomConsumerAuditJavaObject.setEcomUser(
- consumerDataDefinition.getConsumerName() + "," + consumerDataDefinition.getConsumerSalt().toLowerCase()
- + "," + consumerDataDefinition.getConsumerPassword().toLowerCase());
- expectedEcomConsumerAuditJavaObject.setStatus(errorInfo.getCode().toString());
- expectedEcomConsumerAuditJavaObject.setDesc(errorInfo.getAuditDesc(variables));
- expectedEcomConsumerAuditJavaObject.setModifier(user.getFullName() + "(" + user.getUserId() + ")");
- AuditValidationUtils.validateEcompConsumerAudit(expectedEcomConsumerAuditJavaObject, action);
- }
-
- public static void deleteEcompConsumerAuditFailure(String action, ConsumerDataDefinition consumerDataDefinition,
- User user, ActionStatus errorMessage, Object... variables) throws Exception {
- // validate audit
- ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(errorMessage.name());
- ExpectedEcomConsumerAudit expectedEcomConsumerAuditJavaObject = new ExpectedEcomConsumerAudit();
- // String auditAction = ADD_ECOMP_USER_CREDENTIALS_AUDIT_ACTION;
- expectedEcomConsumerAuditJavaObject.setAction(action);
- expectedEcomConsumerAuditJavaObject.setEcomUser(consumerDataDefinition.getConsumerName());
- expectedEcomConsumerAuditJavaObject.setStatus(errorInfo.getCode().toString());
- expectedEcomConsumerAuditJavaObject.setDesc(errorInfo.getAuditDesc(variables));
- expectedEcomConsumerAuditJavaObject.setModifier(user.getFullName() + "(" + user.getUserId() + ")");
- AuditValidationUtils.validateEcompConsumerAudit(expectedEcomConsumerAuditJavaObject, action);
- }
-
- ////////////////////// US571255
- public static void GetListOfUsersByRolesAuditFailure(String action, String roles, int status, User userModifier,
- ActionStatus errorMessage, Object... variables) throws Exception {
- ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(errorMessage.name());
- ExpectedGetUserListAudit expectedGetListOfUsersAuditJavaObject = new ExpectedGetUserListAudit(); // String
- // auditAction
- // =
- // ADD_ECOMP_USER_CREDENTIALS_AUDIT_ACTION;
- expectedGetListOfUsersAuditJavaObject.setAction(action);
- expectedGetListOfUsersAuditJavaObject.setStatus(String.valueOf(status));
- expectedGetListOfUsersAuditJavaObject.setDesc(errorInfo.getAuditDesc(variables));
-
- expectedGetListOfUsersAuditJavaObject.setDetails(roles);
- if (errorMessage == ActionStatus.USER_INACTIVE || errorMessage == ActionStatus.MISSING_INFORMATION) {
- expectedGetListOfUsersAuditJavaObject.setModifier("(UNKNOWN)");
- } else {
- expectedGetListOfUsersAuditJavaObject
- .setModifier(userModifier.getFullName() + "(" + userModifier.getUserId() + ")");
- }
- AuditValidationUtils.validateAuditGetListOfUsersByRoles(expectedGetListOfUsersAuditJavaObject, action);
- }
-
- public static void GetListOfUsersByRolesAuditSuccess(String action, String roles, User user, int status)
- throws Exception {
- ExpectedGetUserListAudit expectedGetListOfUsersAuditJavaObject = new ExpectedGetUserListAudit();
- expectedGetListOfUsersAuditJavaObject.setAction(action);
- expectedGetListOfUsersAuditJavaObject.setStatus(String.valueOf(status));
- expectedGetListOfUsersAuditJavaObject.setDesc("OK");
- expectedGetListOfUsersAuditJavaObject.setModifier(user.getFullName() + "(" + user.getUserId() + ")");
- expectedGetListOfUsersAuditJavaObject.setDetails(roles);
- validateAuditGetListOfUsersByRoles(expectedGetListOfUsersAuditJavaObject, action);
- }
-
- public static void validateAuditGetListOfUsersByRoles(ExpectedGetUserListAudit GetListOfUsersAuditJavaObject,
- String action) throws Exception {
-
- Map<String, Object> map2 = new HashMap<String, Object>();
- map2 = parseAuditResourceByAction(action, null);
- validateField(map2, AuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action);
- validateField(map2, AuditJsonKeysEnum.STATUS.getAuditJsonKeyName(), GetListOfUsersAuditJavaObject.getStatus());
- validateField(map2, AuditJsonKeysEnum.MODIFIER.getAuditJsonKeyName(),
- GetListOfUsersAuditJavaObject.getModifier());
- validateField(map2, AuditJsonKeysEnum.DESCRIPTION.getAuditJsonKeyName(),
- GetListOfUsersAuditJavaObject.getDesc());
- validateField(map2, AuditJsonKeysEnum.DETAILS.getAuditJsonKeyName(),
- GetListOfUsersAuditJavaObject.getDetails());
- }
-
- public static void validateAuditImport(ExpectedResourceAuditJavaObject resourceAuditJavaObject, String action)
- throws Exception {
-
- Map<String, Object> map2 = new HashMap<String, Object>();
- map2 = parseAuditResourceByAction(action, null);
-
- resourceAuditJavaObject.setModifierUid(
- getModifierString(resourceAuditJavaObject.getModifierName(), resourceAuditJavaObject.getModifierUid()));
-
- validateField(map2, AuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action);
- validateField(map2, AuditJsonKeysEnum.RESOURCE_TYPE.getAuditJsonKeyName(),
- resourceAuditJavaObject.getResourceType());
- validateField(map2, AuditJsonKeysEnum.PREV_VERSION.getAuditJsonKeyName(),
- resourceAuditJavaObject.getPrevVersion());
- validateField(map2, AuditJsonKeysEnum.CURR_VERSION.getAuditJsonKeyName(),
- resourceAuditJavaObject.getCurrVersion());
- validateField(map2, AuditJsonKeysEnum.MODIFIER.getAuditJsonKeyName(), resourceAuditJavaObject.getModifierUid());
- validateField(map2, AuditJsonKeysEnum.PREV_STATE.getAuditJsonKeyName(), resourceAuditJavaObject.getPrevState());
- validateField(map2, AuditJsonKeysEnum.CURR_STATE.getAuditJsonKeyName(), resourceAuditJavaObject.getCurrState());
- validateField(map2, AuditJsonKeysEnum.STATUS.getAuditJsonKeyName(), resourceAuditJavaObject.getStatus());
- validateField(map2, AuditJsonKeysEnum.DESCRIPTION.getAuditJsonKeyName(), resourceAuditJavaObject.getDesc());
-
- }
-
- public static void validateAuditDistribution(ExpectedResourceAuditJavaObject resourceAuditJavaObject, String action)
- throws Exception {
-
- Map<String, Object> map2 = new HashMap<String, Object>();
- map2 = parseAuditResourceByAction(action, null);
-
- resourceAuditJavaObject.setModifierUid(
- getModifierString(resourceAuditJavaObject.getModifierName(), resourceAuditJavaObject.getModifierUid()));
-
- validateField(map2, AuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action);
- validateField(map2, AuditJsonKeysEnum.RESOURCE_NAME.getAuditJsonKeyName(),
- resourceAuditJavaObject.getResourceName());
- validateField(map2, AuditJsonKeysEnum.RESOURCE_TYPE.getAuditJsonKeyName(),
- resourceAuditJavaObject.getResourceType());
- validateField(map2, AuditJsonKeysEnum.CURR_VERSION.getAuditJsonKeyName(),
- resourceAuditJavaObject.getCurrVersion());
- validateField(map2, AuditJsonKeysEnum.MODIFIER.getAuditJsonKeyName(), resourceAuditJavaObject.getModifierUid());
- validateField(map2, AuditJsonKeysEnum.CURR_STATE.getAuditJsonKeyName(), resourceAuditJavaObject.getCurrState());
- validateField(map2, AuditJsonKeysEnum.DPREV_STATUS.getAuditJsonKeyName(),
- resourceAuditJavaObject.getDprevStatus());
- validateField(map2, AuditJsonKeysEnum.DCURR_STATUS.getAuditJsonKeyName(),
- resourceAuditJavaObject.getDcurrStatus());
- validateField(map2, AuditJsonKeysEnum.STATUS.getAuditJsonKeyName(), resourceAuditJavaObject.getStatus());
- validateField(map2, AuditJsonKeysEnum.DESCRIPTION.getAuditJsonKeyName(), resourceAuditJavaObject.getDesc());
- validateField(map2, AuditJsonKeysEnum.COMMENT.getAuditJsonKeyName(), resourceAuditJavaObject.getComment());
- validateField(map2, AuditJsonKeysEnum.DID.getAuditJsonKeyName(), resourceAuditJavaObject.getDistributionId());
-
- }
-
- // Benny
- public static void validateAudit_Distribution(ExpectedResourceAuditJavaObject resourceAuditJavaObject,
- String action) throws Exception {
-
- List<Map<String, Object>> actionToList = getAuditListByAction(resourceAuditJavaObject.getAction(), 1);
- Map<String, Object> map2 = actionToList.get(0);
- validateField(map2, AuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action);
- validateField(map2, AuditJsonKeysEnum.RESOURCE_NAME.getAuditJsonKeyName(),
- resourceAuditJavaObject.getResourceName());
- validateField(map2, AuditJsonKeysEnum.RESOURCE_TYPE.getAuditJsonKeyName(),
- resourceAuditJavaObject.getResourceType());
- validateField(map2, AuditJsonKeysEnum.CURR_VERSION.getAuditJsonKeyName(),
- resourceAuditJavaObject.getCurrVersion());
- validateField(map2, AuditJsonKeysEnum.MODIFIER.getAuditJsonKeyName(), resourceAuditJavaObject.getMODIFIER());
- validateField(map2, AuditJsonKeysEnum.CURR_STATE.getAuditJsonKeyName(), resourceAuditJavaObject.getCurrState());
- validateField(map2, AuditJsonKeysEnum.DPREV_STATUS.getAuditJsonKeyName(),
- resourceAuditJavaObject.getDprevStatus());
- validateField(map2, AuditJsonKeysEnum.DCURR_STATUS.getAuditJsonKeyName(),
- resourceAuditJavaObject.getDcurrStatus());
- validateField(map2, AuditJsonKeysEnum.STATUS.getAuditJsonKeyName(), resourceAuditJavaObject.getStatus());
- validateField(map2, AuditJsonKeysEnum.DESCRIPTION.getAuditJsonKeyName(), resourceAuditJavaObject.getDesc());
- validateField(map2, AuditJsonKeysEnum.COMMENT.getAuditJsonKeyName(), resourceAuditJavaObject.getComment());
-
- }
-
- public void validateAuditNotification(ExpectedResourceAuditJavaObject resourceAuditJavaObject, String action)
- throws Exception {
-
- Map<String, Object> map2 = new HashMap<String, Object>();
- map2 = parseAuditResourceByAction(action, null);
-
- resourceAuditJavaObject.setModifierUid(
- getModifierString(resourceAuditJavaObject.getModifierName(), resourceAuditJavaObject.getModifierUid()));
-
- validateField(map2, AuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action);
- validateField(map2, AuditJsonKeysEnum.RESOURCE_NAME.getAuditJsonKeyName(),
- resourceAuditJavaObject.getResourceName());
- validateField(map2, AuditJsonKeysEnum.RESOURCE_TYPE.getAuditJsonKeyName(),
- resourceAuditJavaObject.getResourceType());
- validateField(map2, AuditJsonKeysEnum.CURR_VERSION.getAuditJsonKeyName(),
- resourceAuditJavaObject.getCurrVersion());
- validateField(map2, AuditJsonKeysEnum.CURR_STATE.getAuditJsonKeyName(), resourceAuditJavaObject.getCurrState());
- validateField(map2, AuditJsonKeysEnum.STATUS.getAuditJsonKeyName(), resourceAuditJavaObject.getStatus());
- validateField(map2, AuditJsonKeysEnum.DESCRIPTION.getAuditJsonKeyName(), resourceAuditJavaObject.getDesc());
- validateField(map2, AuditJsonKeysEnum.DID.getAuditJsonKeyName(), resourceAuditJavaObject.getDistributionId());
- validateField(map2, AuditJsonKeysEnum.TOPIC_NAME.getAuditJsonKeyName(), resourceAuditJavaObject.getTopicName());
-
- }
-
- public static void validateAudit(ExpectedDistDownloadAudit expectedDistDownloadAudit, String action)
- throws Exception {
-
- Map<String, Object> map2 = new HashMap<String, Object>();
- map2 = parseAuditResourceByAction(action, null);
-
- validateField(map2, AuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action);
- validateField(map2, AuditJsonKeysEnum.STATUS.getAuditJsonKeyName(), expectedDistDownloadAudit.getStatus());
- validateField(map2, AuditJsonKeysEnum.DESCRIPTION.getAuditJsonKeyName(), expectedDistDownloadAudit.getDesc());
- validateField(map2, AuditJsonKeysEnum.CONSUMER_ID.getAuditJsonKeyName(),
- expectedDistDownloadAudit.getConsumerId());
- validateField(map2, AuditJsonKeysEnum.RESOURCE_URL.getAuditJsonKeyName(),
- expectedDistDownloadAudit.getResourceUrl());
- }
-
- public static void validateAuditExternalSearchAPI(ExpectedExternalAudit expectedDistDownloadAudit, String action, Map<AuditingFieldsKeysEnum, String> body)
- throws Exception {
-
- Map<String, Object> map2 = new HashMap<String, Object>();
- map2 = parseAuditResourceByAction(action, body);
-
- validateField(map2, AuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action);
- validateField(map2, AuditJsonKeysEnum.STATUS.getAuditJsonKeyName(), expectedDistDownloadAudit.getSTATUS());
- validateField(map2, AuditJsonKeysEnum.DESCRIPTION.getAuditJsonKeyName(), expectedDistDownloadAudit.getDESC());
- validateField(map2, AuditJsonKeysEnum.CONSUMER_ID.getAuditJsonKeyName(),
- expectedDistDownloadAudit.getCONSUMER_ID());
- validateField(map2, AuditJsonKeysEnum.RESOURCE_URL.getAuditJsonKeyName(),
- expectedDistDownloadAudit.getRESOURCE_URL());
- }
-
- public static void validateAuditExternalCreateResource(ExpectedResourceAuditJavaObject expectedExternalAudit, String action, Map<AuditingFieldsKeysEnum, String> body) throws Exception {
- Map<String, Object> map2 = new HashMap<String, Object>();
- map2 = parseAuditResourceByAction(action, body);
-
- validateField(map2, AuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action);
- validateField(map2, AuditJsonKeysEnum.RESOURCE_NAME.getAuditJsonKeyName(), expectedExternalAudit.getResourceName());
- validateField(map2, AuditJsonKeysEnum.RESOURCE_TYPE.getAuditJsonKeyName(), expectedExternalAudit.getResourceType());
- validateField(map2, AuditJsonKeysEnum.CONSUMER_ID.getAuditJsonKeyName(), expectedExternalAudit.getCONSUMER_ID());
- validateField(map2, AuditJsonKeysEnum.RESOURCE_URL.getAuditJsonKeyName(), expectedExternalAudit.getRESOURCE_URL());
- validateField(map2, AuditJsonKeysEnum.MODIFIER.getAuditJsonKeyName(), expectedExternalAudit.getMODIFIER());
-
- validateField(map2, AuditJsonKeysEnum.PREV_VERSION.getAuditJsonKeyName(), expectedExternalAudit.getPrevVersion());
- validateField(map2, AuditJsonKeysEnum.CURR_VERSION.getAuditJsonKeyName(), expectedExternalAudit.getCurrVersion());
- validateField(map2, AuditJsonKeysEnum.PREV_STATE.getAuditJsonKeyName(), expectedExternalAudit.getPrevState());
- validateField(map2, AuditJsonKeysEnum.CURR_STATE.getAuditJsonKeyName(), expectedExternalAudit.getCurrState());
-
- validateField(map2, AuditJsonKeysEnum.STATUS.getAuditJsonKeyName(), expectedExternalAudit.getStatus());
- validateField(map2, AuditJsonKeysEnum.DESCRIPTION.getAuditJsonKeyName(), expectedExternalAudit.getDesc());
- }
-
- public static void validateAuditExternalChangeLifecycle(ExpectedResourceAuditJavaObject expectedExternalAudit, String action, Map<AuditingFieldsKeysEnum, String> body) throws Exception {
- Map<String, Object> map2 = new HashMap<String, Object>();
- map2 = parseAuditResourceByAction(action, body);
-
- validateField(map2, AuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action);
- validateField(map2, AuditJsonKeysEnum.RESOURCE_NAME.getAuditJsonKeyName(), expectedExternalAudit.getResourceName());
- validateField(map2, AuditJsonKeysEnum.RESOURCE_TYPE.getAuditJsonKeyName(), expectedExternalAudit.getResourceType());
- validateField(map2, AuditJsonKeysEnum.CONSUMER_ID.getAuditJsonKeyName(), expectedExternalAudit.getCONSUMER_ID());
- validateField(map2, AuditJsonKeysEnum.RESOURCE_URL.getAuditJsonKeyName(), expectedExternalAudit.getRESOURCE_URL());
- validateField(map2, AuditJsonKeysEnum.MODIFIER.getAuditJsonKeyName(), expectedExternalAudit.getMODIFIER());
-
- validateField(map2, AuditJsonKeysEnum.PREV_VERSION.getAuditJsonKeyName(), expectedExternalAudit.getPrevVersion());
- validateField(map2, AuditJsonKeysEnum.CURR_VERSION.getAuditJsonKeyName(), expectedExternalAudit.getCurrVersion());
- validateField(map2, AuditJsonKeysEnum.PREV_STATE.getAuditJsonKeyName(), expectedExternalAudit.getPrevState());
- validateField(map2, AuditJsonKeysEnum.CURR_STATE.getAuditJsonKeyName(), expectedExternalAudit.getCurrState());
-
- validateField(map2, AuditJsonKeysEnum.STATUS.getAuditJsonKeyName(), expectedExternalAudit.getStatus());
- validateField(map2, AuditJsonKeysEnum.DESCRIPTION.getAuditJsonKeyName(), expectedExternalAudit.getDesc());
- }
-
- public void validateAuditDeploy(ExpectedResourceAuditJavaObject resourceAuditJavaObject, String action)
- throws Exception {
-
- Map<String, Object> map2 = new HashMap<String, Object>();
- map2 = parseAuditResourceByAction(action, null);
-
- resourceAuditJavaObject.setModifierUid(
- getModifierString(resourceAuditJavaObject.getModifierName(), resourceAuditJavaObject.getModifierUid()));
-
- validateField(map2, AuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action);
- validateField(map2, AuditJsonKeysEnum.RESOURCE_NAME.getAuditJsonKeyName(),
- resourceAuditJavaObject.getResourceName());
- validateField(map2, AuditJsonKeysEnum.RESOURCE_TYPE.getAuditJsonKeyName(),
- resourceAuditJavaObject.getResourceType());
- validateField(map2, AuditJsonKeysEnum.CURR_VERSION.getAuditJsonKeyName(),
- resourceAuditJavaObject.getCurrVersion());
- validateField(map2, AuditJsonKeysEnum.MODIFIER.getAuditJsonKeyName(), resourceAuditJavaObject.getModifierUid());
- validateField(map2, AuditJsonKeysEnum.STATUS.getAuditJsonKeyName(), resourceAuditJavaObject.getStatus());
- validateField(map2, AuditJsonKeysEnum.DESCRIPTION.getAuditJsonKeyName(), resourceAuditJavaObject.getDesc());
- validateField(map2, AuditJsonKeysEnum.DID.getAuditJsonKeyName(), resourceAuditJavaObject.getDistributionId());
-
- }
-
- public static void validateAuditProduct(ExpectedProductAudit productExpectedAudit, String action,
- AuditJsonKeysEnum... additionalFields) throws Exception {
-
- Map<String, Object> map2 = new HashMap<String, Object>();
- map2 = parseAuditResourceByAction(action, null);
-
- validateField(map2, AuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action);
- validateField(map2, AuditJsonKeysEnum.RESOURCE_NAME.getAuditJsonKeyName(),
- productExpectedAudit.getRESOURCE_NAME());
- validateField(map2, AuditJsonKeysEnum.RESOURCE_TYPE.getAuditJsonKeyName(),
- productExpectedAudit.getRESOURCE_TYPE());
- validateField(map2, AuditJsonKeysEnum.PREV_VERSION.getAuditJsonKeyName(),
- productExpectedAudit.getPREV_VERSION());
- validateField(map2, AuditJsonKeysEnum.CURR_VERSION.getAuditJsonKeyName(),
- productExpectedAudit.getCURR_VERSION());
- validateField(map2, AuditJsonKeysEnum.PREV_STATE.getAuditJsonKeyName(), productExpectedAudit.getPREV_STATE());
- validateField(map2, AuditJsonKeysEnum.CURR_STATE.getAuditJsonKeyName(), productExpectedAudit.getCURR_STATE());
- validateField(map2, AuditJsonKeysEnum.MODIFIER.getAuditJsonKeyName(), productExpectedAudit.getMODIFIER());
- validateField(map2, AuditJsonKeysEnum.STATUS.getAuditJsonKeyName(), productExpectedAudit.getSTATUS());
- validateField(map2, AuditJsonKeysEnum.DESCRIPTION.getAuditJsonKeyName(), productExpectedAudit.getDESC());
- validateField(map2, AuditJsonKeysEnum.SERVICE_INSTANCE_ID.getAuditJsonKeyName(),
- productExpectedAudit.getSERVICE_INSTANCE_ID());
- if (additionalFields != null) {
- List<AuditJsonKeysEnum> fieldsList = Arrays.asList(additionalFields);
- if (fieldsList.contains(AuditJsonKeysEnum.COMMENT)) {
- validateField(map2, AuditJsonKeysEnum.COMMENT.getAuditJsonKeyName(), productExpectedAudit.getCOMMENT());
- }
- }
- }
-
- private static List<Map<String, Object>> getAuditListByAction(String action, int expectedNumOfAudit)
- throws Exception {
- List<Map<String, Object>> actionToList = parseAuditResourceByActionToList(action, null);
- assertEquals("recieved different audits number than expected", expectedNumOfAudit, actionToList.size());
- return actionToList;
- }
-
- public static void validateAuthenticationAudit(ExpectedAuthenticationAudit expectedAudit) throws Exception {
- List<Map<String, Object>> actionToList = getAuditListByAction(expectedAudit.getAction(), 1);
- assertEquals("expected number of ES action is 1", 1, actionToList.size());
-
- Map<String, Object> map = actionToList.get(0);
- validateField(map, AuditEnum.ACTION.getValue(), expectedAudit.getAction());
- validateField(map, AuditEnum.URL.getValue(), expectedAudit.getUrl());
- validateField(map, AuditEnum.USER.getValue(), expectedAudit.getUser());
- validateField(map, AuditEnum.AUTH_STATUS.getValue(), expectedAudit.getAuthStatus());
- validateField(map, AuditEnum.REALM.getValue(), expectedAudit.getRealm());
-
- }
-
- private static void validateField(Map<String, Object> actualAuditRecord, String jsonField, Object expectedValue) {
- if (expectedValue == null) {
- // || changed to &&
- if (actualAuditRecord.containsKey(jsonField)) {
- assertTrue("Audit field " + jsonField + ": expected null, actual " + actualAuditRecord.get(jsonField),
- actualAuditRecord.get(jsonField).toString().equals("null")
- || actualAuditRecord.get(jsonField).toString().equals(Constants.EMPTY_STRING));
- }
-
- } else {
- assertTrue("Audit field " + jsonField + " not found in actual", actualAuditRecord.containsKey(jsonField));
- Object foundValue = actualAuditRecord.get(jsonField);
- compareElements(expectedValue, foundValue);
- }
- }
-
- private static void compareElements(Object expectedValue, Object foundValue) {
- if (expectedValue instanceof String) {
- assertTrue("Actual value " + foundValue + " is not string", foundValue instanceof String);
- assertTrue("Expected " + expectedValue + " not equal to actual " + foundValue,
- foundValue.equals(expectedValue));
- }
- /*
- * else if( expectedValue instanceof Number){ assertTrue(foundValue
- * instanceof Number); assertTrue(foundValue == expectedValue); }
- */
- else if (expectedValue instanceof Boolean) {
- assertTrue(foundValue instanceof Boolean);
- assertTrue(foundValue == expectedValue);
- } else if (expectedValue instanceof Map) {
- assertTrue(foundValue instanceof Map);
- Map<String, Object> foundMap = (Map<String, Object>) foundValue;
- Map<String, Object> excpectedMap = (Map<String, Object>) expectedValue;
- assertTrue(foundMap.size() == excpectedMap.size());
- Iterator<String> foundkeyItr = foundMap.keySet().iterator();
- while (foundkeyItr.hasNext()) {
- String foundKey = foundkeyItr.next();
- assertTrue(excpectedMap.containsKey(foundKey));
- compareElements(excpectedMap.get(foundKey), foundMap.get(foundKey));
- }
-
- } else if (expectedValue instanceof List) {
- assertTrue(foundValue instanceof List);
- List<Object> foundList = (List<Object>) foundValue;
- List<Object> excpectedList = (List<Object>) expectedValue;
- assertTrue(foundList.size() == excpectedList.size());
- for (int i = 0; i < foundList.size(); i++) {
- compareElements(excpectedList.get(i), foundList.get(i));
- }
-
- } else {
- assertTrue(foundValue.equals(expectedValue));
- }
- }
-
- // public static Map<String, Object> parseAuditResourceByAction(String
- // action, String body) throws Exception {
- //
- // Map auditingMessage = null;
- // auditingMessage = retrieveAuditMessagesByPattern(action, null);
- //
- // return auditingMessage;
- //
- // }
-
- public static Map<String, Object> parseAuditResourceByAction(String action, Map<AuditingFieldsKeysEnum, String> body) throws Exception {
-
- Map auditingMessage = null;
- auditingMessage = retrieveAuditMessagesByPattern(action, body, false);
-
- return auditingMessage;
-
- }
-
- // public static List<Map<String, Object>>
- // parseAuditResourceByActionToList(String action, String body) throws
- // Exception {
- //
- // List<Map<String, Object>> auditList = new ArrayList<Map<String,
- // Object>>();
- //
- //// String auditingMessage = null;
- //
- // Map auditingMessage = null;
- // auditingMessage = retrieveAuditMessagesByPattern(action);
- //
- // if (body == null) {
- //// String pattern = "/_search?q=ACTION:\"" + action + "\"";
- //// auditingMessage = retrieveAuditMessagesByPattern(action);
- //// auditingMessage = retrieveAuditMessagesByPattern(pattern);
- // } else {
- //// auditingMessage = retrieveAuditMessagesUsingBody(body);
- // }
- //
- // return ResponseParser.getAuditFromMessage(auditingMessage);
- //
- // }
-
- public static List<Map<String, Object>> parseAuditResourceByActionToList(String action,
- Map<AuditingFieldsKeysEnum, String> body) throws Exception {
-
- List<Map<String, Object>> auditList = new ArrayList<Map<String, Object>>();
-
- // String auditingMessage = null;
-
- Map auditingMessage = null;
-
- if (body == null || body.isEmpty()) {
- auditingMessage = retrieveAuditMessagesByPattern(action, null, false);
- // String pattern = "/_search?q=ACTION:\"" + action + "\"";
- // auditingMessage = retrieveAuditMessagesByPattern(action);
- // auditingMessage = retrieveAuditMessagesByPattern(pattern);
- } else {
- auditingMessage = retrieveAuditMessagesByPattern(action, body, false);
- // auditingMessage = retrieveAuditMessagesUsingBody(body);
- }
-
- return ResponseParser.getAuditFromMessage(auditingMessage);
-
- }
-
- public JSONObject buildElasticQueryStringObject(String defaultField, String queryValue) throws JSONException {
-
- JSONObject query_string = new JSONObject();
- JSONObject jSONObject = new JSONObject();
- jSONObject.put("default_field", defaultField);
- jSONObject.put("query", queryValue);
-
- query_string.put("query_string", jSONObject);
-
- return query_string;
- }
-
- public static JSONObject buildElasticQueryBody(List<JSONObject> listObjects) throws JSONException {
-
- JSONObject query = new JSONObject();
- JSONObject bool = new JSONObject();
- JSONObject must = new JSONObject();
- JSONArray mustA = new JSONArray();
-
- for (int i = 0; i < listObjects.size(); i++) {
- JSONObject match = new JSONObject();
- match.put("match", listObjects.get(i));
- mustA.put(match);
-
- }
-
- must.put("must", mustA);
- bool.put("bool", must);
- query.put("query", bool);
-
- return query;
- }
-
- public static String retrieveAuditMessagesUsingBody(String query_string) throws IOException {
-
- Config config = Utils.getConfig();
- HttpRequest getAuditingMessage = new HttpRequest();
- Map<String, String> headersMap = new HashMap<String, String>();
- String body = query_string;
-
- String url = String.format(Urls.GET_SEARCH_DATA_FROM_ES, config.getEsHost(), config.getEsPort(), "_search");
- RestResponse restResponse = getAuditingMessage.httpSendPost(url, body, headersMap);
-
- return restResponse.getResponse();
- }
-
- public static Map<String, String> retrieveAuditMessagesByPattern(String action, Map<AuditingFieldsKeysEnum, String> body, Boolean retryFlag)
- throws IOException {
-
- // get cassandra table name by action
- String esType = AuditingActionEnum.getActionByName(action).getAuditingEsType();
- Map<String, String> resultsMap = new HashMap<String, String>();
-
- List<Pair<AuditingFieldsKeysEnum, String>> myFields = new ArrayList<Pair<AuditingFieldsKeysEnum, String>>();
- Pair<AuditingFieldsKeysEnum, String> myPair = new Pair<AuditingFieldsKeysEnum, String>(
- AuditingFieldsKeysEnum.AUDIT_ACTION, action);
- myFields.add(0, myPair);
- if (body != null && !body.isEmpty()) {
- for (Map.Entry<AuditingFieldsKeysEnum, String> mapElement : body.entrySet()) {
- myFields.add(new Pair<AuditingFieldsKeysEnum, String>(mapElement.getKey(), mapElement.getValue()));
- }
- }
-
- List<Row> fetchFromTable = CassandraUtils.fetchFromTable(auditKeySpaceName, esType, myFields);
- if(retryFlag){
- if(fetchFromTable.size() == 0){
- return resultsMap;
- }
- }
- assertTrue("expected on fetching from data base one record only, actual: " + fetchFromTable.size(), fetchFromTable.size() == 1);
- Row row = fetchFromTable.get(0);
-
- ColumnDefinitions columnDefinitions = row.getColumnDefinitions();
-
-
- for (int i = 0; i < columnDefinitions.size(); i++) {
- resultsMap.put(columnDefinitions.getName(i), row.getObject(columnDefinitions.getName(i)) == null ? "null"
- : row.getObject(columnDefinitions.getName(i)).toString());
- }
-
- return resultsMap;
- }
-
- // public static Map retrieveAuditMessagesByPattern(String pattern) throws
- // IOException {
- //
- //// Config config = Utils.getConfig();
- //// HttpRequest getAuditingMessage = new HttpRequest();
- //// String url = String.format(Urls.GET_SEARCH_DATA_FROM_ES,
- // config.getEsHost(), config.getEsPort(), pattern);
- //// RestResponse restResponse = getAuditingMessage.httpSendGet(url, null);
- //
- //// get cassandra table name by action
- // String esType =
- // AuditingActionEnum.getActionByName(pattern).getAuditingEsType();
- //// AuditingActionEnum actionByName =
- // AuditingActionEnum.getActionByName(pattern);
- //
- //// Map<AuditingFieldsKeysEnum, String> myFields= new
- // HashMap<AuditingFieldsKeysEnum, String>();
- //// myFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION , pattern);
- //
- // List<Pair<AuditingFieldsKeysEnum, String>> myFields = new
- // ArrayList<Pair<AuditingFieldsKeysEnum, String>>();
- // Pair<AuditingFieldsKeysEnum, String> myPair = new
- // Pair<AuditingFieldsKeysEnum, String>(AuditingFieldsKeysEnum.AUDIT_ACTION
- // , pattern);
- // myFields.add(0, myPair);
- //
- //
- // List<Row> fetchFromTable = CassandraUtils.fetchFromTable("sdcaudit",
- // esType, myFields);
- // Row row = fetchFromTable.get(0);
- //
- //
- // ColumnDefinitions columnDefinitions = row.getColumnDefinitions();
- //// String string = row.getString(columnDefinitions.getName(1));
- //
- //// String metaData = row.getColumnDefinitions().toString();
- //// metaData =metaData.replaceAll("\\((.*?)\\)|\\[|\\]|Columns", "");
- //// List<String> metaDataList = new
- // ArrayList<String>(Arrays.asList(metaData.split(", ")));
- //
- //
- //
- // Map<String, String> resultsMap = new HashMap<String, String>();
- //
- //
- // for (int i=0 ; i < columnDefinitions.size() ; i++){
- // resultsMap.put(columnDefinitions.getName(i) ,
- // row.getObject(columnDefinitions.getName(i)) == null ? "null" :
- // row.getObject(columnDefinitions.getName(i)).toString());
- // }
- //// for (String string : metaDataList) {
- //// resultsMap.put(string , row.getString(string));
- //// }
- ////
- //
- //// String dataString = fetchFromTable.toString();
- //// dataString = dataString.replaceAll("\\[|\\]|Row", "");
- //// List<String> dataArray = new
- // ArrayList<String>(Arrays.asList(dataString.split(", ")));
- ////
- ////
- //// Map<String, String> resultsMap = new HashMap<String, String>();
- //// for (int i=0 ; i<metaDataList.size() ; i++) {
- //// resultsMap.put(metaDataList.get(i), dataArray.get(i));
- //// }
- ////
- //// return restResponse.getResponse();
- // return resultsMap;
- // }
-
- public static void categoryAuditSuccess(String action, CategoryDefinition categoryDefinition, User user, int status,
- String resourceType) throws Exception {
- categoryAuditSuccessInternal(action, categoryDefinition, null, null, user, status, resourceType);
- }
-
- public static void categoryAuditFailure(String action, CategoryDefinition categoryDataDefinition, User user,
- ActionStatus errorMessage, int status, String resourceType, Object... variables) throws Exception {
- categoryAuditFailureInternal(action, categoryDataDefinition, null, null, user, errorMessage, status,
- resourceType, variables);
- }
-
- public static void subCategoryAuditSuccess(String action, CategoryDefinition categoryDefinition,
- SubCategoryDefinition subCategoryDefinition, User user, int status, String resourceType) throws Exception {
- categoryAuditSuccessInternal(action, categoryDefinition, subCategoryDefinition, null, user, status,
- resourceType);
- }
-
- public static void groupingAuditSuccess(String action, CategoryDefinition categoryDefinition,
- SubCategoryDefinition subCategoryDefinition, GroupingDefinition groupingDefinition, User user, int status,
- String resourceType) throws Exception {
- categoryAuditSuccessInternal(action, categoryDefinition, subCategoryDefinition, groupingDefinition, user,
- status, resourceType);
- }
-
- public static void subCategoryAuditFailure(String action, CategoryDefinition categoryDataDefinition,
- SubCategoryDefinition subCategoryDefinition, User user, ActionStatus errorMessage, int status,
- String resourceType, Object... variables) throws Exception {
- categoryAuditFailureInternal(action, categoryDataDefinition, subCategoryDefinition, null, user, errorMessage,
- status, resourceType, variables);
- }
-
- // NEW Benny
- public static void groupingAuditFailure(String action, CategoryDefinition categoryDefinition,
- SubCategoryDefinition subCategoryDefinition, GroupingDefinition groupingDefinition, User user,
- ActionStatus errorMessage, int status, String resourceType, Object... variables) throws Exception {
- groupingAuditFailureInternal(action, categoryDefinition, subCategoryDefinition, groupingDefinition, user,
- errorMessage, status, resourceType, variables);
- }
-
- private static void groupingAuditFailureInternal(String action, CategoryDefinition categoryDataDefinition,
- SubCategoryDefinition subCategoryDefinition, GroupingDefinition groupingDefinition, User user,
- ActionStatus errorMessage, int status, String resourceType, Object... variables) throws Exception {
- // validate audit
- ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(errorMessage.name());
- ExpectedCategoryAudit expectedCatrgoryAuditJavaObject = new ExpectedCategoryAudit();
- expectedCatrgoryAuditJavaObject.setAction(action);
- expectedCatrgoryAuditJavaObject.setModifier(user.getFullName() + "(" + user.getUserId() + ")");
- expectedCatrgoryAuditJavaObject.setCategoryName(categoryDataDefinition.getName());
- String subCategoryName = (subCategoryDefinition != null ? subCategoryDefinition.getName()
- : Constants.EMPTY_STRING);
- expectedCatrgoryAuditJavaObject.setSubCategoryName(subCategoryName);
- String groupingName = (groupingDefinition != null ? groupingDefinition.getName() : Constants.EMPTY_STRING);
- expectedCatrgoryAuditJavaObject.setGroupingName(groupingName);
- expectedCatrgoryAuditJavaObject.setResourceType(resourceType);
- expectedCatrgoryAuditJavaObject.setStatus(String.valueOf(status));
- expectedCatrgoryAuditJavaObject.setDesc(errorInfo.getAuditDesc(variables));
- AuditValidationUtils.validateCategoryAudit(expectedCatrgoryAuditJavaObject, action);
- }
-
- ///
- private static void categoryAuditSuccessInternal(String action, CategoryDefinition categoryDefinition,
- SubCategoryDefinition subCategoryDefinition, GroupingDefinition groupingDefinition, User user, int status,
- String resourceType) throws Exception {
- // resourceType = Service/Resource/Product
- ExpectedCategoryAudit expectedCatrgoryAuditJavaObject = new ExpectedCategoryAudit();
- expectedCatrgoryAuditJavaObject.setAction(action);
- expectedCatrgoryAuditJavaObject.setModifier(user.getFullName() + "(" + user.getUserId() + ")");
- expectedCatrgoryAuditJavaObject.setCategoryName(categoryDefinition.getName());
- String subCategoryName = (subCategoryDefinition != null ? subCategoryDefinition.getName()
- : Constants.EMPTY_STRING);
- expectedCatrgoryAuditJavaObject.setSubCategoryName(subCategoryName);
- String groupingName = (groupingDefinition != null ? groupingDefinition.getName() : Constants.EMPTY_STRING);
- expectedCatrgoryAuditJavaObject.setGroupingName(groupingName);
- expectedCatrgoryAuditJavaObject.setResourceType(resourceType);
- expectedCatrgoryAuditJavaObject.setStatus(String.valueOf(status));
- expectedCatrgoryAuditJavaObject.setDesc("OK");
- AuditValidationUtils.validateCategoryAudit(expectedCatrgoryAuditJavaObject, action);
- }
-
- ///////////////////////////
- ///// BENNNNNNNNY
- public enum UserAuditJsonKeysEnum {
- ACTION("ACTION"), MODIFIER("MODIFIER"), STATUS("STATUS"), DESC("DESCRIPTION"), USER_AFTER(
- "USER_AFTER"), USER_BEFORE("USER_BEFORE");
- private String auditJsonKeyName;
-
- private UserAuditJsonKeysEnum(String auditJsonKeyName) {
- this.auditJsonKeyName = auditJsonKeyName;
- }
-
- public String getAuditJsonKeyName() {
- return auditJsonKeyName.toLowerCase();
- }
- }
-
- public static void validateAddUserAudit(ExpectedUserCRUDAudit expectedAddUserAuditJavaObject, String action)
- throws Exception {
-
- List<Map<String, Object>> actionToList = getAuditListByAction(expectedAddUserAuditJavaObject.getAction(), 1);
- Map<String, Object> map = actionToList.get(0);
- validateField(map, UserAuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action);
- validateField(map, UserAuditJsonKeysEnum.MODIFIER.getAuditJsonKeyName(),
- expectedAddUserAuditJavaObject.getModifier());
- validateField(map, UserAuditJsonKeysEnum.USER_AFTER.getAuditJsonKeyName(),
- expectedAddUserAuditJavaObject.getUserAfter());
- validateField(map, UserAuditJsonKeysEnum.USER_BEFORE.getAuditJsonKeyName(),
- expectedAddUserAuditJavaObject.getUserBefore());
- validateField(map, UserAuditJsonKeysEnum.STATUS.getAuditJsonKeyName(),
- expectedAddUserAuditJavaObject.getStatus());
- validateField(map, UserAuditJsonKeysEnum.DESC.getAuditJsonKeyName(), expectedAddUserAuditJavaObject.getDesc());
-
- }
-
- private static void categoryAuditFailureInternal(String action, CategoryDefinition categoryDataDefinition,
- SubCategoryDefinition subCategoryDefinition, GroupingDefinition groupingDefinition, User user,
- ActionStatus errorMessage, int status, String resourceType, Object... variables) throws Exception {
- // validate audit
- ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(errorMessage.name());
- ExpectedCategoryAudit expectedCatrgoryAuditJavaObject = new ExpectedCategoryAudit();
- expectedCatrgoryAuditJavaObject.setAction(action);
- expectedCatrgoryAuditJavaObject.setModifier(user.getFullName() + "(" + user.getUserId() + ")");
- expectedCatrgoryAuditJavaObject.setCategoryName(categoryDataDefinition.getName());
- String subCategoryName = (subCategoryDefinition != null ? subCategoryDefinition.getName()
- : Constants.EMPTY_STRING);
- expectedCatrgoryAuditJavaObject.setSubCategoryName(subCategoryName);
- String groupingName = (groupingDefinition != null ? groupingDefinition.getName() : Constants.EMPTY_STRING);
- expectedCatrgoryAuditJavaObject.setGroupingName(groupingName);
- expectedCatrgoryAuditJavaObject.setResourceType(resourceType);
- expectedCatrgoryAuditJavaObject.setStatus(String.valueOf(status));
- expectedCatrgoryAuditJavaObject.setDesc(errorInfo.getAuditDesc(variables));
- AuditValidationUtils.validateCategoryAudit(expectedCatrgoryAuditJavaObject, action);
- }
-
- public static void validateGetCategoryHirarchy(ExpectedCategoryAudit expectedCatrgoryAuditJavaObject, String action)
- throws Exception {
-
- List<Map<String, Object>> actionToList = getAuditListByAction(expectedCatrgoryAuditJavaObject.getAction(), 1);
- Map<String, Object> map = actionToList.get(0);
-
- expectedCatrgoryAuditJavaObject.setModifier(getModifierString(expectedCatrgoryAuditJavaObject.getModifierName(),
- expectedCatrgoryAuditJavaObject.getModifierUid()));
- validateField(map, CategoryAuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action);
- validateField(map, CategoryAuditJsonKeysEnum.MODIFIER.getAuditJsonKeyName(),
- expectedCatrgoryAuditJavaObject.getModifier());
- validateField(map, CategoryAuditJsonKeysEnum.DETAILS.getAuditJsonKeyName(),
- expectedCatrgoryAuditJavaObject.getDetails());
- validateField(map, CategoryAuditJsonKeysEnum.STATUS.getAuditJsonKeyName(),
- expectedCatrgoryAuditJavaObject.getStatus());
- validateField(map, CategoryAuditJsonKeysEnum.DESCRIPTION.getAuditJsonKeyName(),
- expectedCatrgoryAuditJavaObject.getDesc());
-
- }
-
- public static void validateCategoryAudit(ExpectedCategoryAudit expectedCatrgoryAuditJavaObject, String action)
- throws Exception {
-
- List<Map<String, Object>> actionToList = getAuditListByAction(expectedCatrgoryAuditJavaObject.getAction(), 1);
- Map<String, Object> map = actionToList.get(0);
- validateField(map, CategoryAuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action);
- validateField(map, CategoryAuditJsonKeysEnum.MODIFIER.getAuditJsonKeyName(),
- expectedCatrgoryAuditJavaObject.getModifier());
- validateField(map, CategoryAuditJsonKeysEnum.CATEGORY_NAME.getAuditJsonKeyName(),
- expectedCatrgoryAuditJavaObject.getCategoryName());
- validateField(map, CategoryAuditJsonKeysEnum.SUB_CATEGORY_NAME.getAuditJsonKeyName(),
- expectedCatrgoryAuditJavaObject.getSubCategoryName());
- validateField(map, CategoryAuditJsonKeysEnum.GROUPING_NAME.getAuditJsonKeyName(),
- expectedCatrgoryAuditJavaObject.getGroupingName());
- validateField(map, CategoryAuditJsonKeysEnum.RESOURCE_TYPE.getAuditJsonKeyName(),
- expectedCatrgoryAuditJavaObject.getResourceType());
- validateField(map, CategoryAuditJsonKeysEnum.STATUS.getAuditJsonKeyName(),
- expectedCatrgoryAuditJavaObject.getStatus());
- validateField(map, CategoryAuditJsonKeysEnum.DESCRIPTION.getAuditJsonKeyName(),
- expectedCatrgoryAuditJavaObject.getDesc());
- }
-
- public static void GetCategoryHierarchyAuditSuccess(String action, String componentType, User user, int status)
- throws Exception {
- ExpectedGetUserListAudit expectedGetListOfUsersAuditJavaObject = new ExpectedGetUserListAudit();
- expectedGetListOfUsersAuditJavaObject.setAction(action);
- expectedGetListOfUsersAuditJavaObject.setStatus(String.valueOf(status));
- expectedGetListOfUsersAuditJavaObject.setDesc("OK");
- expectedGetListOfUsersAuditJavaObject.setModifier(user.getFullName() + "(" + user.getUserId() + ")");
- expectedGetListOfUsersAuditJavaObject.setDetails(componentType.toLowerCase());
- validateAuditGetListOfUsersByRoles(expectedGetListOfUsersAuditJavaObject, action);
- }
-
- public static String buildArtifactDataAudit(ArtifactDefinition artifactDefinition) {
- StringBuilder sb = new StringBuilder();
- if (artifactDefinition.getTimeout() == null) {
- artifactDefinition.setTimeout(0);
- }
- if (artifactDefinition != null) {
- sb.append(artifactDefinition.getArtifactGroupType() == null ? null
- : artifactDefinition.getArtifactGroupType().getType()).append(",").append("'")
- .append(artifactDefinition.getArtifactLabel()).append("'").append(",")
- .append(artifactDefinition.getArtifactType()).append(",")
- .append(artifactDefinition.getArtifactName()).append(",").append(artifactDefinition.getTimeout())
- .append(",").append(artifactDefinition.getEsId());
- sb.append(",");
- if (artifactDefinition.getArtifactVersion() != null) {
- sb.append(artifactDefinition.getArtifactVersion());
- } else {
- sb.append(" ");
- }
- sb.append(",");
- if (artifactDefinition.getArtifactUUID() != null) {
- sb.append(artifactDefinition.getArtifactUUID());
- } else {
- sb.append(" ");
- }
- }
-
- return sb.toString();
- }
-
- public static ExpectedResourceAuditJavaObject expectedMissingInformationAuditObject(String Action,
- String resourceUid, ComponentType resourceType) throws FileNotFoundException {
- ExpectedResourceAuditJavaObject expectedAudit = new ExpectedResourceAuditJavaObject();
- expectedAudit.setAction(Action);
- expectedAudit.setResourceName(resourceUid);
- expectedAudit.setResourceType(resourceType.getValue());
- expectedAudit.setPrevVersion("");
- expectedAudit.setCurrVersion("");
- expectedAudit.setModifierName("");
- expectedAudit.setModifierUid("");
- expectedAudit.setPrevState("");
- expectedAudit.setCurrState("");
- expectedAudit.setPrevArtifactUuid("");
- expectedAudit.setCurrArtifactUuid("");
- expectedAudit.setArtifactData("");
- expectedAudit.setStatus("403");
- expectedAudit.setDesc(buildAuditDescription(
- new ErrorValidationUtils().parseErrorConfigYaml(ActionStatus.MISSING_INFORMATION.name()),
- new ArrayList<String>()));
- return expectedAudit;
- }
-
- public static ExpectedResourceAuditJavaObject expectedComponentNotFoundAuditObject(String Action,
- String resourceUid, ComponentType resourceType, String artifactUid, User user,
- ArrayList<String> notFoundComponent) throws FileNotFoundException {
- String desc = null;
-
- ExpectedResourceAuditJavaObject expectedAudit = new ExpectedResourceAuditJavaObject();
- expectedAudit.setAction(Action);
- expectedAudit.setResourceName(resourceUid);
- expectedAudit.setResourceType(resourceType.getValue());
- expectedAudit.setPrevVersion("");
- expectedAudit.setCurrVersion("");
- expectedAudit.setModifierName(user.getFirstName() + " " + user.getLastName());
- expectedAudit.setModifierUid(user.getUserId());
- expectedAudit.setPrevState("");
- expectedAudit.setCurrState("");
- expectedAudit.setPrevArtifactUuid("");
- expectedAudit.setCurrArtifactUuid(artifactUid);
- expectedAudit.setArtifactData("");
- expectedAudit.setStatus("404");
-
- if (resourceType.getValue() == ComponentType.SERVICE.getValue()) {
- desc = buildAuditDescription(
- new ErrorValidationUtils().parseErrorConfigYaml(ActionStatus.SERVICE_NOT_FOUND.name()),
- notFoundComponent);
- } else if (resourceType.getValue() == ComponentType.RESOURCE.getValue())
- desc = buildAuditDescription(
- new ErrorValidationUtils().parseErrorConfigYaml(ActionStatus.RESOURCE_NOT_FOUND.name()),
- notFoundComponent);
-
- expectedAudit.setDesc(desc);
- return expectedAudit;
- }
-
- public static ExpectedResourceAuditJavaObject expectedArtifactNotFoundAuditObject(String Action, String resourceUid,
- ComponentType resourceType, String artifactUid, User user, String currState, String currVersion)
- throws FileNotFoundException {
- String desc = null;
-
- ExpectedResourceAuditJavaObject expectedAudit = new ExpectedResourceAuditJavaObject();
- expectedAudit.setAction(Action);
- expectedAudit.setResourceName(resourceUid);
- expectedAudit.setResourceType(resourceType.getValue());
- expectedAudit.setPrevVersion("");
- expectedAudit.setCurrVersion(currVersion);
- expectedAudit.setModifierName(user.getFirstName() + " " + user.getLastName());
- expectedAudit.setModifierUid(user.getUserId());
- expectedAudit.setPrevState("");
- expectedAudit.setCurrState(currState);
- expectedAudit.setPrevArtifactUuid("");
- expectedAudit.setCurrArtifactUuid(artifactUid);
- expectedAudit.setArtifactData("");
- expectedAudit.setStatus("404");
-
- desc = buildAuditDescription(
- new ErrorValidationUtils().parseErrorConfigYaml(ActionStatus.ARTIFACT_NOT_FOUND.name()),
- Arrays.asList(""));
-
- expectedAudit.setDesc(desc);
- return expectedAudit;
- }
-
- public static ExpectedResourceAuditJavaObject expectedArtifactNotFoundAuditObject(String Action,
- String resourceName, ComponentType resourceType, String artifactUid, LifecycleStateEnum lifecycle,
- User user, String currVersion) throws FileNotFoundException {
- String desc = null;
-
- ExpectedResourceAuditJavaObject expectedAudit = new ExpectedResourceAuditJavaObject();
- expectedAudit.setAction(Action);
- expectedAudit.setResourceName(resourceName);
- expectedAudit.setResourceType(resourceType.getValue());
- expectedAudit.setPrevVersion("");
- expectedAudit.setCurrVersion(currVersion);
- expectedAudit.setModifierName(user.getFirstName() + " " + user.getLastName());
- expectedAudit.setModifierUid(user.getUserId());
- expectedAudit.setPrevState("");
- expectedAudit.setCurrState(lifecycle.name());
- expectedAudit.setPrevArtifactUuid("");
- expectedAudit.setCurrArtifactUuid(artifactUid);
- expectedAudit.setArtifactData("");
- expectedAudit.setStatus("404");
-
- desc = buildAuditDescription(
- new ErrorValidationUtils().parseErrorConfigYaml(ActionStatus.ARTIFACT_NOT_FOUND.name()),
- new ArrayList<String>());
-
- expectedAudit.setDesc(desc);
- return expectedAudit;
- }
-
- public static ExpectedResourceAuditJavaObject expectedRestrictedOperationAuditObject(String Action,
- String resourceNameOrUid, ComponentType resourceType, String artifactUid, User user, String currVersion,
- String currState) throws FileNotFoundException {
- String desc = null;
-
- ExpectedResourceAuditJavaObject expectedAudit = new ExpectedResourceAuditJavaObject();
- expectedAudit.setAction(Action);
- expectedAudit.setResourceName(resourceNameOrUid);
- expectedAudit.setResourceType(resourceType.getValue());
- expectedAudit.setPrevVersion("");
- expectedAudit.setCurrVersion(currVersion);
- expectedAudit.setModifierName(user.getFirstName() + " " + user.getLastName());
- expectedAudit.setModifierUid(user.getUserId());
- expectedAudit.setPrevState("");
- expectedAudit.setCurrState(currState);
- expectedAudit.setPrevArtifactUuid("");
- expectedAudit.setCurrArtifactUuid(artifactUid);
- expectedAudit.setArtifactData("");
- expectedAudit.setStatus("409");
-
- desc = buildAuditDescription(
- new ErrorValidationUtils().parseErrorConfigYaml(ActionStatus.RESTRICTED_OPERATION.name()),
- new ArrayList<String>());
-
- expectedAudit.setDesc(desc);
- return expectedAudit;
- }
-
- public static ExpectedResourceAuditJavaObject expectedInvalidContentAuditObject(String Action, String resourceName,
- ComponentType resourceType, String artifactUid, User user, String currVersion, String currState,
- ArrayList<String> invalidContentList) throws FileNotFoundException {
- return expectedInvalidContentAuditObject(ActionStatus.INVALID_CONTENT, Action, resourceName, resourceType,
- artifactUid, user, currVersion, currState, invalidContentList);
- }
-
- public static ExpectedResourceAuditJavaObject expectedInvalidContentAuditObject(ActionStatus actionStatus,
- String Action, String resourceName, ComponentType resourceType, String artifactUid, User user,
- String currVersion, String currState, ArrayList<String> invalidContentList) throws FileNotFoundException {
- String desc = null;
-
- ExpectedResourceAuditJavaObject expectedAudit = new ExpectedResourceAuditJavaObject();
- expectedAudit.setAction(Action);
- expectedAudit.setResourceName(resourceName);
- expectedAudit.setResourceType(resourceType.getValue());
- expectedAudit.setPrevVersion("");
- expectedAudit.setCurrVersion(currVersion);
- expectedAudit.setModifierName(user.getFirstName() + " " + user.getLastName());
- expectedAudit.setModifierUid(user.getUserId());
- expectedAudit.setPrevState("");
- expectedAudit.setCurrState(currState);
- expectedAudit.setPrevArtifactUuid("");
- expectedAudit.setCurrArtifactUuid(artifactUid);
- expectedAudit.setArtifactData("");
- expectedAudit.setStatus("400");
-
- desc = buildAuditDescription(new ErrorValidationUtils().parseErrorConfigYaml(actionStatus.name()),
- invalidContentList);
-
- expectedAudit.setDesc(desc);
- return expectedAudit;
- }
-
- public static ExpectedResourceAuditJavaObject expectedSuccessAuditObject(String Action, String resourceName,
- ComponentType resourceType, ArtifactReqDetails artifactReq, User user, String currVersion, String currState,
- String prevArtifactUuid) throws FileNotFoundException {
- ExpectedResourceAuditJavaObject expectedAudit = new ExpectedResourceAuditJavaObject();
- expectedAudit.setAction(Action);
- expectedAudit.setResourceName(resourceName);
- expectedAudit.setResourceType(resourceType.getValue());
- expectedAudit.setPrevVersion("");
- expectedAudit.setCurrVersion(currVersion);
- expectedAudit.setModifierName(user.getFirstName() + " " + user.getLastName());
- expectedAudit.setModifierUid(user.getUserId());
- expectedAudit.setPrevState("");
- expectedAudit.setCurrState(currState);
- expectedAudit.setPrevArtifactUuid(prevArtifactUuid);
- expectedAudit.setCurrArtifactUuid(artifactReq.getUniqueId());
- expectedAudit
- .setArtifactData(buildArtifactDataAudit(ArtifactUtils.convertArtifactReqToDefinition(artifactReq)));
- expectedAudit.setStatus("200");
- expectedAudit.setDesc("OK");
- return expectedAudit;
- }
-
- public static JSONObject filterAuditByUuid(String action, String uuid) throws Exception {
- Map<String, String> actionMap = new HashMap<String, String>();
- actionMap.put("ACTION", action);
- JSONObject actionJsonObject = new JSONObject(actionMap);
- Map<String, String> uuidMap = new HashMap<String, String>();
- uuidMap.put("SERVICE_INSTANCE_ID", uuid);
- JSONObject uuidJsonObject = new JSONObject(uuidMap);
-
- List<JSONObject> filters = new ArrayList<JSONObject>(Arrays.asList(actionJsonObject, uuidJsonObject));
- JSONObject body = buildElasticQueryBody(filters);
- return body;
- }
-
- public static void validateAudit(ExpectedResourceAuditJavaObject resourceAuditJavaObject, String action)
- throws Exception {
- List<Map<String, Object>> actionToList = getAuditListByAction(resourceAuditJavaObject.getAction(), 1);
- Map<String, Object> map2 = actionToList.get(0);
- validateField(map2, AuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action);
- validateField(map2, AuditJsonKeysEnum.RESOURCE_NAME.getAuditJsonKeyName(),
- resourceAuditJavaObject.getResourceName());
- validateField(map2, AuditJsonKeysEnum.RESOURCE_TYPE.getAuditJsonKeyName(),
- resourceAuditJavaObject.getResourceType());
- validateField(map2, AuditJsonKeysEnum.PREV_VERSION.getAuditJsonKeyName(),
- resourceAuditJavaObject.getPrevVersion());
- validateField(map2, AuditJsonKeysEnum.CURR_VERSION.getAuditJsonKeyName(),
- resourceAuditJavaObject.getCurrVersion());
- validateField(map2, AuditJsonKeysEnum.MODIFIER.getAuditJsonKeyName(), resourceAuditJavaObject.getMODIFIER());
- validateField(map2, AuditJsonKeysEnum.PREV_STATE.getAuditJsonKeyName(), resourceAuditJavaObject.getPrevState());
- validateField(map2, AuditJsonKeysEnum.CURR_STATE.getAuditJsonKeyName(), resourceAuditJavaObject.getCurrState());
- validateField(map2, AuditJsonKeysEnum.STATUS.getAuditJsonKeyName(), resourceAuditJavaObject.getStatus());
- validateField(map2, AuditJsonKeysEnum.DESCRIPTION.getAuditJsonKeyName(), resourceAuditJavaObject.getDesc());
- validateField(map2, AuditJsonKeysEnum.COMMENT.getAuditJsonKeyName(), resourceAuditJavaObject.getComment());
- }
-
- ////// service audit validation/////////////////////
-
- public static ExpectedResourceAuditJavaObject constructFieldsForAuditValidation(ServiceReqDetails serviceReqDetails,
- String serviceVersion, User sdncUserDetails) {
-
- ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = new ExpectedResourceAuditJavaObject();
-
- expectedResourceAuditJavaObject.setAction("Create");
- expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId());
- String userFirstLastName = sdncUserDetails.getFirstName() + " " + sdncUserDetails.getLastName();
- expectedResourceAuditJavaObject.setModifierName(userFirstLastName);
- expectedResourceAuditJavaObject.setStatus("200");
- expectedResourceAuditJavaObject.setDesc("OK");
- expectedResourceAuditJavaObject.setResourceName(serviceReqDetails.getName());
- expectedResourceAuditJavaObject.setResourceType("Service");
- expectedResourceAuditJavaObject.setPrevVersion(String.valueOf(Float.parseFloat(serviceVersion) - 0.1f));
- expectedResourceAuditJavaObject.setCurrVersion(serviceVersion);
- expectedResourceAuditJavaObject.setPrevState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
- expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
- expectedResourceAuditJavaObject.setComment(null);
-
- return expectedResourceAuditJavaObject;
-
- }
-
- public static ExpectedResourceAuditJavaObject constructFieldsForAuditValidation(ServiceReqDetails serviceReqDetails,
- String serviceVersion, User sdncUserDetails, ActionStatus errorStatus, List<String> variables)
- throws FileNotFoundException {
-
- ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = constructFieldsForAuditValidation(
- serviceReqDetails, serviceVersion, sdncUserDetails);
- ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(errorStatus.name());
-
- expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString());
- String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables);
- expectedResourceAuditJavaObject.setDesc(auditDesc);
-
- return expectedResourceAuditJavaObject;
-
- }
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/BaseValidationUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/BaseValidationUtils.java
deleted file mode 100644
index eb3ee331ed..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/BaseValidationUtils.java
+++ /dev/null
@@ -1,116 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utils.validation;
-
-import static org.testng.AssertJUnit.assertEquals;
-
-import java.io.FileNotFoundException;
-import java.util.Arrays;
-
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo;
-import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
-import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
-import org.openecomp.sdc.exception.ResponseFormat;
-import org.testng.Assert;
-
-public class BaseValidationUtils {
-
- 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_RESTRICTED_OPERATION = 409;
- public static final int STATUS_CODE_ALREADY_EXISTS = 409;
-
- // ------
- 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 void checkSuccess(RestResponse response) {
- checkStatusCode(response, "request failed", false, STATUS_CODE_SUCCESS);
- }
-
- public static void checkErrorResponse(RestResponse errorResponse, ActionStatus actionStatus,
- String... expectedVariables) throws FileNotFoundException {
- // Expected error
- ErrorInfo expectedError = ErrorValidationUtils.parseErrorConfigYaml(actionStatus.name());
- String expectedMessage = expectedError.getMessage();
-
- // Actual error
- ResponseFormat responseFormat = ResponseParser.parseToObjectUsingMapper(errorResponse.getResponse(),
- ResponseFormat.class);
- String actualMessage = responseFormat.getText();
- String[] actualVariables = responseFormat.getVariables();
-
- assertEquals("Unexpected error message", expectedMessage, actualMessage);
- assertEquals("Unexpected error variables", Arrays.asList(expectedVariables), Arrays.asList(actualVariables));
- }
-
- public static void checkErrorMessageResponse(RestResponse errorResponse, ActionStatus actionStatus)
- throws FileNotFoundException {
- // Expected error
- ErrorInfo expectedError = ErrorValidationUtils.parseErrorConfigYaml(actionStatus.name());
- String expectedMessage = expectedError.getMessage();
-
- // Actual error
- ResponseFormat responseFormat = ResponseParser.parseToObjectUsingMapper(errorResponse.getResponse(),
- ResponseFormat.class);
- String actualMessage = responseFormat.getText();
-
- assertEquals("Unexpected error message", expectedMessage, actualMessage);
- }
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/CategoryValidationUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/CategoryValidationUtils.java
deleted file mode 100644
index cd2297fd19..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/CategoryValidationUtils.java
+++ /dev/null
@@ -1,126 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utils.validation;
-
-import static org.testng.AssertJUnit.assertEquals;
-import static org.testng.AssertJUnit.assertNotNull;
-import static org.testng.AssertJUnit.assertTrue;
-
-import org.json.JSONObject;
-import org.openecomp.sdc.be.model.category.CategoryDefinition;
-import org.openecomp.sdc.be.model.category.GroupingDefinition;
-import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
-import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
-import org.openecomp.sdc.ci.tests.utils.rest.CategoryRestUtils;
-
-public class CategoryValidationUtils {
-
- public static void verifyCategoryExistInGetResponse(RestResponse getAllCategoryRest,
- CategoryDefinition categoryDefinition) {
-
- int categoriesNum = CategoryRestUtils.getMatchingCategoriesNum(getAllCategoryRest, categoryDefinition);
- assertEquals("category " + categoryDefinition.getName() + " not found during get or found more than once", 1,
- categoriesNum);
- }
-
- public static void verifyCategoryNotExistsInGetResponse(RestResponse getAllCategoryRest,
- CategoryDefinition categoryDefinition) {
-
- int categoriesNum = CategoryRestUtils.getMatchingCategoriesNum(getAllCategoryRest, categoryDefinition);
- assertEquals("category " + categoryDefinition.getName() + " should't be found during get", 0, categoriesNum);
- }
-
- public static void verifySubCategoryExistInGetResponse(RestResponse getAllCategoryRest, String parentCategoryId,
- SubCategoryDefinition expectedSubCategoryDefinition) {
-
- int subCategoriesNum = CategoryRestUtils.getMatchingSubCategoriesNum(getAllCategoryRest, parentCategoryId,
- expectedSubCategoryDefinition);
- assertEquals(
- "sub-category " + expectedSubCategoryDefinition.getName()
- + " not found during get or found more than once for parentId " + parentCategoryId,
- 1, subCategoriesNum);
- }
-
- public static void verifyGroupingExistInGetResponse(RestResponse getAllCategoryRest, String parentCategoryId,
- String subCategoryId, GroupingDefinition expectedGroupingDefinition) {
-
- int groupingNum = CategoryRestUtils.getMatchingGroupingNum(getAllCategoryRest, parentCategoryId, subCategoryId,
- expectedGroupingDefinition);
- assertEquals(
- "sub-category " + expectedGroupingDefinition.getName()
- + " not found during get or found more than once for parentId " + parentCategoryId,
- 1, groupingNum);
- }
-
- public static void verifyGroupingNotExistInGetResponse(RestResponse getAllCategoryRest, String parentCategoryId,
- String subCategoryId, GroupingDefinition expectedGroupingDefinition) {
-
- int groupingNum = CategoryRestUtils.getMatchingGroupingNum(getAllCategoryRest, parentCategoryId, subCategoryId,
- expectedGroupingDefinition);
- assertEquals(
- "sub-category " + expectedGroupingDefinition.getName()
- + " not found during get or found more than once for parentId " + parentCategoryId,
- 0, groupingNum);
- }
-
- public static void verifySubCategoryNotExistsInGetResponse(RestResponse getAllCategoryRest, String parentCategoryId,
- SubCategoryDefinition expectedSubCategoryDefinition) {
-
- int subCategoriesNum = CategoryRestUtils.getMatchingSubCategoriesNum(getAllCategoryRest, parentCategoryId,
- expectedSubCategoryDefinition);
- assertEquals("sub-category " + expectedSubCategoryDefinition.getName()
- + " should't be found during get for parentId " + parentCategoryId, 0, subCategoriesNum);
- }
-
- /// NEE Benny
- public static void validateCreateGroupResponse(RestResponse createSubCategoryRest,
- GroupingDefinition expectedGroupDefinition) throws Exception {
-
- String response = createSubCategoryRest.getResponse();
- JSONObject jobject = new JSONObject(response);
- assertTrue(jobject.get("name").equals(expectedGroupDefinition.getName()));
- assertTrue(jobject.get("normalizedName").equals(expectedGroupDefinition.getNormalizedName()));
- // assertNotNull(jobject.get("normalizedName"));
- assertNotNull(jobject.get("uniqueId"));
- expectedGroupDefinition.setUniqueId(jobject.get("uniqueId").toString());
-
- }
-
- public static void validateCreateSubCategoryResponse(RestResponse createSubCategoryRest,
- SubCategoryDefinition expectedSubCategoryDefinition) throws Exception {
-
- String response = createSubCategoryRest.getResponse();
- JSONObject jobject = new JSONObject(response);
- assertTrue(jobject.get("name").equals(expectedSubCategoryDefinition.getName()));
- assertNotNull(jobject.get("normalizedName"));
- assertNotNull(jobject.get("uniqueId"));
- }
-
- public static void validateCreateCategoryResponse(RestResponse createCategoryRest,
- CategoryDefinition expectedCategoryDefinition) throws Exception {
- String response = createCategoryRest.getResponse();
- JSONObject jobject = new JSONObject(response);
- assertTrue(jobject.get("name").equals(expectedCategoryDefinition.getName()));
- assertTrue(jobject.get("normalizedName").equals(expectedCategoryDefinition.getNormalizedName()));
- assertNotNull(jobject.get("uniqueId"));
- }
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/CsarValidationUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/CsarValidationUtils.java
deleted file mode 100644
index 05e3874fc0..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/CsarValidationUtils.java
+++ /dev/null
@@ -1,298 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utils.validation;
-
-import static org.testng.AssertJUnit.assertTrue;
-
-import java.nio.charset.StandardCharsets;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.json.simple.JSONArray;
-import org.json.simple.JSONObject;
-import org.json.simple.parser.JSONParser;
-import org.openecomp.sdc.be.model.GroupDefinition;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.ci.tests.datatypes.GroupHeatMetaDefinition;
-import org.openecomp.sdc.ci.tests.datatypes.PropertyHeatMetaDefinition;
-import org.openecomp.sdc.ci.tests.datatypes.TypeHeatMetaDefinition;
-import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
-import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaDefinition;
-import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaNodeTemplatesTopologyTemplateDefinition;
-import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaRequirementsNodeTemplatesDefinition;
-import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
-import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
-import org.openecomp.sdc.ci.tests.utils.rest.ImportRestUtils;
-import org.openecomp.sdc.common.rest.api.RestResponseAsByteArray;
-import org.openecomp.sdc.common.util.ZipUtil;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class CsarValidationUtils {
- private static Logger log = LoggerFactory.getLogger(CsarValidationUtils.class.getName());
-
- public static String getCsarPayload(String csarName, String fileLocation) throws Exception {
-
- RestResponseAsByteArray csar = ImportRestUtils.getCsar(csarName,
- ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
- assertTrue("Return response code different from 200",
- csar.getHttpStatusCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
- Map<String, byte[]> readZip = null;
- byte[] data = csar.getResponse();
- if (data != null && data.length > 0) {
- readZip = ZipUtil.readZip(data);
-
- }
-
- byte[] artifactsBs = readZip.get(fileLocation);
- String str = new String(artifactsBs, StandardCharsets.UTF_8);
-
- return str;
-
- }
-
- public static List<TypeHeatMetaDefinition> getListTypeHeatMetaDefinition(String csarUUID) throws Exception {
-
- String artifactHeatMetaLocation = "Artifacts/HEAT.meta";
- JSONParser parser = new JSONParser();
- String csarPayload = getCsarPayload(csarUUID, artifactHeatMetaLocation);
- if (csarPayload != null) {
- Object parse = parser.parse(csarPayload);
- JSONObject jsonObject = (JSONObject) parse;
- JSONObject jsonObjectImportStructure = (JSONObject) jsonObject.get("importStructure");
- List<TypeHeatMetaDefinition> listHeatMetaDefenition = new ArrayList<TypeHeatMetaDefinition>();
- listHeatMetaDefenition = getArtifactsByGroup(jsonObjectImportStructure, listHeatMetaDefenition);
- return listHeatMetaDefenition;
- }
- return null;
-
- }
-
- protected static List<TypeHeatMetaDefinition> getArtifactsByGroup(JSONObject jsonObjectImportStructure,
- List<TypeHeatMetaDefinition> listHeatMetaDefenition) {
-
- @SuppressWarnings("unchecked")
- Set<Object> typeSet = jsonObjectImportStructure.keySet();
- for (Object type : typeSet) {
- TypeHeatMetaDefinition heatMetaDefenition = new TypeHeatMetaDefinition();
- log.debug(type.toString());
- log.debug("{}", jsonObjectImportStructure.get(type));
- JSONArray array = (JSONArray) jsonObjectImportStructure.get(type);
- heatMetaDefenition.setTypeName((String) type);
- List<GroupHeatMetaDefinition> groupHeatMetaDefinitions = new ArrayList<GroupHeatMetaDefinition>();
- heatMetaDefenition.setGroupHeatMetaDefinition(fetchArtifactByGroup(array, groupHeatMetaDefinitions, true));
- listHeatMetaDefenition.add(heatMetaDefenition);
- }
- return listHeatMetaDefenition;
- }
-
- protected static List<GroupHeatMetaDefinition> fetchArtifactByGroup(JSONArray array,
- List<GroupHeatMetaDefinition> listGroupHeatMetaDefinition, Boolean openNewGroup) {
-
- GroupHeatMetaDefinition groupHeatMetaDefinition;
-
- if (array != null) {
- for (int i = 0; i < array.size(); i++) {
- if (openNewGroup) {
- groupHeatMetaDefinition = new GroupHeatMetaDefinition();
- int groupNumber = listGroupHeatMetaDefinition.size() + 1;
- log.debug("groupName={}", groupNumber);
- groupHeatMetaDefinition.setGroup(groupNumber);
- listGroupHeatMetaDefinition.add(groupHeatMetaDefinition);
- PropertyHeatMetaDefinition propertyHeatMetaDefinition = new PropertyHeatMetaDefinition();
- propertyHeatMetaDefinition.setName("isBase");
- propertyHeatMetaDefinition.setValue(false);
- groupHeatMetaDefinition.setPropertyHeatMetaDefinition(propertyHeatMetaDefinition);
- }
- groupHeatMetaDefinition = listGroupHeatMetaDefinition.get(listGroupHeatMetaDefinition.size() - 1);
- JSONObject jsonObject = (JSONObject) array.get(i);
- @SuppressWarnings("unchecked")
- Set<Object> groupsKey = jsonObject.keySet();
- for (Object groupKey : groupsKey) {
- String groupKeyStr = (String) groupKey;
- if (groupKeyStr.equals("isBase")) {
- PropertyHeatMetaDefinition propertyHeatMetaDefinition = new PropertyHeatMetaDefinition();
- propertyHeatMetaDefinition.setName(groupKeyStr);
- propertyHeatMetaDefinition.setValue((boolean) jsonObject.get(groupKeyStr));
- if (!groupHeatMetaDefinition.getPropertyHeatMetaDefinition()
- .equals(propertyHeatMetaDefinition)) {
- groupHeatMetaDefinition.getPropertyHeatMetaDefinition()
- .setValue((boolean) jsonObject.get(groupKeyStr));
- }
- }
- if (groupKeyStr.equals("fileName") || groupKeyStr.equals("env")) {
- String artifactName = (String) jsonObject.get(groupKeyStr);
- List<String> listArtifactNames = groupHeatMetaDefinition.getArtifactList();
- listArtifactNames.add(artifactName);
- groupHeatMetaDefinition.setArtifactList(listArtifactNames);
- } else {
- if (!groupKeyStr.equals("isBase")) {
- fetchArtifactByGroup((JSONArray) jsonObject.get(groupKeyStr), listGroupHeatMetaDefinition,
- false);
- }
- }
- }
- }
- }
- return listGroupHeatMetaDefinition;
- }
-
- private static Integer getArtifactCount(List<TypeHeatMetaDefinition> listHeatMetaDefenition,
- Boolean isEnvIncluded) {
- int count = 0;
- List<String> uniqeArtifactList = new ArrayList<>();
-
- for (TypeHeatMetaDefinition typeHeatMetaDefinition : listHeatMetaDefenition) {
- for (GroupHeatMetaDefinition groupHeatMetaDefinition : typeHeatMetaDefinition
- .getGroupHeatMetaDefinition()) {
- if (isEnvIncluded) {
- count = count + groupHeatMetaDefinition.getArtifactList().size();
- } else {
- for (String fileName : groupHeatMetaDefinition.getArtifactList()) {
- if (!fileName.contains(".env") && !uniqeArtifactList.contains(fileName)) {
- uniqeArtifactList.add(fileName);
- count = count + 1;
- }
- }
- }
- }
- }
- return count;
- }
-
- private static Integer getGroupCount(List<TypeHeatMetaDefinition> listHeatMetaDefenition) {
- int count = 0;
- for (TypeHeatMetaDefinition typeHeatMetaDefinition : listHeatMetaDefenition) {
- count = count + typeHeatMetaDefinition.getGroupHeatMetaDefinition().size();
- }
- return count;
- }
-
- private static String groupNameBuilder(Resource resource) {
- String separator = "::";
- String module = "module-";
- String groupName = resource.getSystemName() + separator + module;
- return groupName;
- }
-
- public static void validateCsarVfArtifact(String csarUUID, Resource resource) throws Exception {
-
- List<TypeHeatMetaDefinition> listTypeHeatMetaDefinition = getListTypeHeatMetaDefinition(csarUUID);
- assertTrue(
- "check group count, expected: " + getGroupCount(listTypeHeatMetaDefinition) + ", actual: "
- + resource.getGroups().size(),
- getGroupCount(listTypeHeatMetaDefinition) == resource.getGroups().size());
- assertTrue(
- "check artifact count, expected: " + getArtifactCount(listTypeHeatMetaDefinition, false) + ", actual: "
- + resource.getDeploymentArtifacts().size(),
- getArtifactCount(listTypeHeatMetaDefinition, false) == resource.getDeploymentArtifacts().size());
-
- }
-
- public static void validateToscaDefinitonObjectVsResource(ToscaDefinition toscaDefinition, Resource resource)
- throws Exception {
-
- assertTrue(
- "check resource instance count, expected: " + getResourceInstanceCount(toscaDefinition) + ", actual: "
- + resource.getComponentInstances().size(),
- getResourceInstanceCount(toscaDefinition) == resource.getComponentInstances().size());
- assertTrue(
- "check resource instance relation count, expected: " + getResourceInstanceRelationCount(toscaDefinition)
- + ", actual: " + resource.getComponentInstancesRelations().size(),
- getResourceInstanceRelationCount(toscaDefinition) == resource.getComponentInstancesRelations().size());
-
- }
-
- public static Integer getResourceInstanceCount(ToscaDefinition toscaDefinition) {
-
- return toscaDefinition.getToscaTopologyTemplate().getToscaNodeTemplatesTopologyTemplateDefinition().size();
- }
-
- public static Integer getResourceInstanceRelationCount(ToscaDefinition toscaDefinition) {
- int count = 0;
- List<ToscaNodeTemplatesTopologyTemplateDefinition> toscaNodeTemplatesTopologyTemplateDefinition = toscaDefinition
- .getToscaTopologyTemplate().getToscaNodeTemplatesTopologyTemplateDefinition();
- for (int i = 0; i < toscaNodeTemplatesTopologyTemplateDefinition.size(); i++) {
- List<ToscaRequirementsNodeTemplatesDefinition> requirements = toscaNodeTemplatesTopologyTemplateDefinition
- .get(i).getRequirements();
- if (requirements != null) {
- for (ToscaRequirementsNodeTemplatesDefinition requirement : requirements) {
- if (requirement.getNode() != null) {
- count = count + 1;
- }
- }
- }
- }
- return count;
- }
-
- // not finished yet
- private static void validateCsarVfgroup(String csarUUID, Resource resource) {
-
- List<GroupDefinition> groups = resource.getGroups();
- for (GroupDefinition groupDefinition : groups) {
- List<String> artifacts = groupDefinition.getArtifacts();
- assertTrue("group description is null", groupDefinition.getDescription() != null);
- assertTrue("InvariantUUID is null", groupDefinition.getInvariantUUID() != null);
- // groupDefinition.getMembers();
- assertTrue(
- "name format mismatch, expected: " + groupNameBuilder(resource) + "[0-9], actual: "
- + groupDefinition.getName(),
- groupDefinition.getName().contains(groupNameBuilder(resource)));
- // groupDefinition.getProperties();
- // groupDefinition.getPropertyValueCounter();
- assertTrue(groupDefinition.getType().equals(getGroupType()));
- }
-
- String expectedCsarUUID = csarUUID;
- // String expectedToscaResourceName = "org.openecomp.resource.vf." +
- // WordUtils.capitalize(resourceDetails.getName().toLowerCase());
- //
- // assertTrue("csarUUID : " + buildAssertMessage(expectedCsarUUID,
- // resource.getCsarUUID()),
- // expectedCsarUUID.equals(resource.getCsarUUID()));
- // assertTrue("toscaResourceName : " +
- // buildAssertMessage(expectedToscaResourceName,
- // resource.getToscaResourceName()),
- // expectedToscaResourceName.equals(resource.getToscaResourceName()));
- //
- // RestResponse getResourceResponse =
- // ResourceRestUtils.getResource(resource.getUniqueId());
- // Resource getResource =
- // ResponseParser.parseToObjectUsingMapper(getResourceResponse.getResponse(),
- // Resource.class);
- // assertTrue("csarUUID : " + buildAssertMessage(expectedCsarUUID,
- // getResource.getCsarUUID()),
- // expectedCsarUUID.equals(getResource.getCsarUUID()));
- // assertTrue("toscaResourceName : " +
- // buildAssertMessage(expectedToscaResourceName,
- // getResource.getToscaResourceName()),
- // expectedToscaResourceName.equals(getResource.getToscaResourceName()));
-
- }
-
- private static String getGroupType() {
- return "org.openecomp.groups.VfModule";
- }
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/DistributionValidationUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/DistributionValidationUtils.java
deleted file mode 100644
index 46948d8f5b..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/DistributionValidationUtils.java
+++ /dev/null
@@ -1,86 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utils.validation;
-
-import static org.testng.AssertJUnit.assertNotNull;
-
-import java.io.IOException;
-import java.text.ParseException;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-
-import org.openecomp.sdc.be.model.Service;
-import org.openecomp.sdc.ci.tests.utils.DistributionUtils;
-import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils;
-import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
-
-public class DistributionValidationUtils {
-
- public static Map<String, String> verifyDistributedArtifactDownloadUsingDB(String distributionID, Map<String, String> expectedArtifactsMapOfDistributedService, List<String> distributionStatusEnumList) throws Exception {
-
- String action = "DStatus";
- int timer = 0;
- int timeWaitPerArtifcat = 3;
- if(expectedArtifactsMapOfDistributedService.size() != 0){
- timer = (expectedArtifactsMapOfDistributedService.size()/10*15 + expectedArtifactsMapOfDistributedService.size() * timeWaitPerArtifcat * distributionStatusEnumList.size() + 30) * 1000 ;
- }
- for (String distributionStatusList : distributionStatusEnumList){
- for (Entry<String, String> url : expectedArtifactsMapOfDistributedService.entrySet()){
- Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
- body.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, distributionID);
- body.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, url.getValue());
- body.put(AuditingFieldsKeysEnum.AUDIT_STATUS, distributionStatusList);
- Map<String, String> actualAuditRecord = new HashMap<String, String>();
- actualAuditRecord = AuditValidationUtils.retrieveAuditMessagesByPattern(action, body, true);
- while (timer != 0) {
- if(actualAuditRecord.size() == 0 ){
- Thread.sleep(1000);
- actualAuditRecord = AuditValidationUtils.retrieveAuditMessagesByPattern(action, body, true);
- timer-=1000;
- if(timer == 0 && actualAuditRecord.size() == 0){
- assertNotNull("audit record did not found in DB for artifact url: " + url.getValue(), null);
- }
- }else{
- timer = timer - timeWaitPerArtifcat * 1000;
- break;
- }
-
- }
- }
- }
- return null;
- }
-
- public static void validateDistributedArtifactsByAudit(Service service, List<String> distributionStatusList) throws Exception, IOException, ParseException {
- String distributionID;
- AtomicOperationUtils.distributeService(service, true);
- distributionID = DistributionUtils.getLatestServiceDistributionObject(service).getDistributionID();
- if(distributionID != null){
- Map<String, String> expectedArtifactsMapOfDistributedService = DistributionUtils.getArtifactsMapOfDistributedService(service);
- DistributionValidationUtils.verifyDistributedArtifactDownloadUsingDB(distributionID, expectedArtifactsMapOfDistributedService, distributionStatusList);
- }
- else{
- assertNotNull("distributionID is null", distributionID);
- }
- }
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ErrorValidationUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ErrorValidationUtils.java
deleted file mode 100644
index 9bf8bd9230..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ErrorValidationUtils.java
+++ /dev/null
@@ -1,121 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utils.validation;
-
-import static org.testng.AssertJUnit.assertEquals;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.InputStream;
-import java.util.List;
-import java.util.Map;
-
-import org.codehaus.jettison.json.JSONException;
-import org.codehaus.jettison.json.JSONObject;
-import org.openecomp.sdc.ci.tests.config.Config;
-import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo;
-import org.openecomp.sdc.ci.tests.datatypes.enums.ExceptionEnumType;
-import org.openecomp.sdc.ci.tests.utils.Utils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.yaml.snakeyaml.Yaml;
-
-public class ErrorValidationUtils {
-
- static Logger logger = LoggerFactory.getLogger(Utils.class.getName());
-
- public static void checkBodyResponseOnError(String errorType, List<String> variables, String actualResponse)
- throws FileNotFoundException, JSONException {
-
- ErrorInfo errorInfo = parseErrorConfigYaml(errorType);
- JSONObject expectedResponseBody = null;
- if (errorInfo.getMessageId() != null) {
- if (errorInfo.getMessageId().contains("SVC")) {
- expectedResponseBody = restExceptionFormatBuilder(errorInfo.getMessageId(), errorInfo.getMessage(),
- variables, ExceptionEnumType.SERVICE_EXCEPTION.getValue());
- } else {
- expectedResponseBody = restExceptionFormatBuilder(errorInfo.getMessageId(), errorInfo.getMessage(),
- variables, ExceptionEnumType.POLICY_EXCPTION.getValue());
- }
- }
- actualResponse = actualResponse.replaceAll("\\n", "");
- logger.debug("actualResponse - {}",actualResponse);
- logger.debug("expectedResponseBody - {}",expectedResponseBody);
- assertEquals(expectedResponseBody, new JSONObject(actualResponse));
- }
-
- public static String checkUIResponseOnError(String errorType)
- throws FileNotFoundException, JSONException {
-
- ErrorInfo errorInfo = parseErrorConfigYaml(errorType);
- String messageId = errorInfo.getMessageId();
-
- return messageId;
- }
-
- public static JSONObject restExceptionFormatBuilder(String messageId, String text, List<String> variables,
- String type) {
-
- JSONObject simpleElements = new JSONObject();
- JSONObject exceptionType = new JSONObject();
- JSONObject requestError = new JSONObject();
-
- try {
- simpleElements.put("messageId", messageId);
- simpleElements.put("text", text);
- simpleElements.put("variables", variables);
- exceptionType.put(type, simpleElements);
- requestError.put("requestError", exceptionType);
-
- } catch (JSONException e) {
- e.printStackTrace();
- }
-
- return requestError;
-
- }
-
- public static ErrorInfo parseErrorConfigYaml(String error) throws FileNotFoundException {
- Yaml yaml = new Yaml();
- ErrorInfo errInfo = null;
- Config config = Utils.getConfig();
- String errorConfigurationFile = config.getErrorConfigurationFile();
- File file = new File(errorConfigurationFile);
- // File file = new
- // File("../catalog-be/src/main/resources/config/error-configuration.yaml");
- InputStream inputStream = new FileInputStream(file);
- Map<?, ?> map = (Map<?, ?>) yaml.load(inputStream);
- // System.out.println(map.get("errors"));
- @SuppressWarnings("unchecked")
- Map<String, ErrorInfo> errorMap = (Map<String, ErrorInfo>) map.get("errors");
- @SuppressWarnings("unchecked")
- Map<String, Object> errorInfo = (Map<String, Object>) errorMap.get(error);
-
- String message = (String) errorInfo.get("message");
- String messageId = (String) errorInfo.get("messageId");
- int code = (Integer) errorInfo.get("code");
- errInfo = new ErrorInfo(code, message, messageId);
-
- return errInfo;
- }
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ProductValidationUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ProductValidationUtils.java
deleted file mode 100644
index ba5114c1bc..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ProductValidationUtils.java
+++ /dev/null
@@ -1,239 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utils.validation;
-
-import static org.testng.AssertJUnit.assertEquals;
-import static org.testng.AssertJUnit.assertFalse;
-import static org.testng.AssertJUnit.assertTrue;
-
-import java.util.Arrays;
-import java.util.List;
-import java.util.Map;
-import java.util.UUID;
-
-import org.apache.log4j.Logger;
-import org.json.simple.JSONArray;
-import org.json.simple.JSONObject;
-import org.json.simple.JSONValue;
-import org.openecomp.sdc.be.model.Product;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.model.category.CategoryDefinition;
-import org.openecomp.sdc.be.model.category.GroupingDefinition;
-import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
-import org.openecomp.sdc.ci.tests.api.ComponentBaseTest.ComponentOperationEnum;
-import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
-import org.openecomp.sdc.ci.tests.utils.rest.ProductRestUtils;
-import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
-
-public class ProductValidationUtils {
-
- static Logger logger = Logger.getLogger(ProductValidationUtils.class.getName());
-
- public static void compareExpectedAndActualProducts(Product expectedProduct, Product actualProduct) {
- compareExpectedAndActualProducts(expectedProduct, actualProduct, null);
- }
-
- public static void compareExpectedAndActualProducts(Product expectedProduct, Product actualProduct,
- ComponentOperationEnum operation) {
-
- assertEquals(expectedProduct.getName(), actualProduct.getName());
- assertEquals(expectedProduct.getFullName(), actualProduct.getFullName());
- assertEquals(expectedProduct.getDescription(), actualProduct.getDescription());
-
- List<String> expectedContacts = expectedProduct.getContacts();
- List<String> actualContacts = actualProduct.getContacts();
- assertTrue(
- "Expected contacts:" + Arrays.toString(expectedContacts.toArray()) + ", actual contacts:"
- + Arrays.toString(actualContacts.toArray()),
- expectedContacts.size() == actualContacts.size() && expectedContacts.containsAll(actualContacts)
- && actualContacts.containsAll(expectedContacts));
-
- List<String> expectedTags = expectedProduct.getTags();
- List<String> actualTags = actualProduct.getTags();
- assertTrue(
- "Expected tags:" + Arrays.toString(expectedTags.toArray()) + ", actual tags:"
- + Arrays.toString(actualTags.toArray()),
- expectedTags.size() == actualTags.size() && expectedTags.containsAll(actualTags)
- && actualTags.containsAll(expectedTags));
-
- assertEquals(expectedProduct.getLifecycleState(), actualProduct.getLifecycleState());
- assertEquals(expectedProduct.getVersion(), actualProduct.getVersion());
- assertEquals(expectedProduct.isHighestVersion(), actualProduct.isHighestVersion());
- assertEquals(expectedProduct.getNormalizedName(), actualProduct.getNormalizedName());
-
- compareCategories(expectedProduct, actualProduct);
- assertEquals(expectedProduct.getLastUpdaterUserId(), actualProduct.getLastUpdaterUserId());
- if (operation != null) {
- assertEquals(expectedProduct.getCreatorUserId(), actualProduct.getCreatorUserId());
- }
-
- Long lastUpdateDate = actualProduct.getLastUpdateDate();
- Long creationDate = actualProduct.getCreationDate();
- Map<String, String> allVersions = actualProduct.getAllVersions();
-
- if (operation != null) {
- if (operation == ComponentOperationEnum.UPDATE_COMPONENT
- || operation == ComponentOperationEnum.CHANGE_STATE_CHECKOUT
- || operation == ComponentOperationEnum.CHANGE_STATE_CHECKIN
- || operation == ComponentOperationEnum.CHANGE_STATE_UNDO_CHECKOUT) {
- assertTrue("Last update date:" + lastUpdateDate + ", creation date: " + creationDate,
- lastUpdateDate > 0 && creationDate > 0 && lastUpdateDate > creationDate);
- } else {
- assertTrue("Last update date:" + lastUpdateDate + ", creation date: " + creationDate,
- lastUpdateDate > 0 && lastUpdateDate.equals(creationDate));
- }
- }
-
- // Check UUIDs
- // If just created, no way to test the UUIDs themselves
- // If updated, we expect the UUIDs of actual to match the expected
- String uniqueId = actualProduct.getUniqueId();
- if (operation == ComponentOperationEnum.CREATE_COMPONENT) {
- UUID.fromString(uniqueId);
- UUID.fromString(actualProduct.getUUID());
- UUID.fromString(actualProduct.getInvariantUUID());
- assertTrue(allVersions.size() == 1);
- assertTrue(allVersions.get("0.1").equals(uniqueId));
- } else {
- if (operation == ComponentOperationEnum.CHANGE_STATE_CHECKOUT) {
- assertFalse(expectedProduct.getUniqueId().equals(uniqueId));
- // Assigning the updated uniqueId to expected so that it can be
- // passed to further logic
- expectedProduct.setUniqueId(uniqueId);
- } else if (operation != null) {
- assertTrue(expectedProduct.getUniqueId().equals(uniqueId));
- }
- assertEquals(expectedProduct.getUUID(), actualProduct.getUUID());
- assertEquals(expectedProduct.getInvariantUUID(), actualProduct.getInvariantUUID());
- }
- }
-
- private static void compareCategories(Product expectedProduct, Product actualProduct) {
- List<CategoryDefinition> expectedCategories = expectedProduct.getCategories();
- List<CategoryDefinition> actualCategories = actualProduct.getCategories();
- if (expectedCategories != null && actualCategories != null) {
- int expSize = expectedCategories.size();
- int actSize = actualCategories.size();
-
- assertTrue("Expected size:" + expSize + ", actual size:" + actSize, expSize == actSize);
-
- for (CategoryDefinition actualDefinition : actualCategories) {
- int lastIndexOfCat = expectedCategories.lastIndexOf(actualDefinition);
- assertTrue("Actual category " + actualDefinition + " not found in expected.", lastIndexOfCat != -1);
- CategoryDefinition expectedDefinition = expectedCategories.get(lastIndexOfCat);
- List<SubCategoryDefinition> actualSubcategories = actualDefinition.getSubcategories();
- List<SubCategoryDefinition> expectedSubcategories = expectedDefinition.getSubcategories();
- for (SubCategoryDefinition actualSub : actualSubcategories) {
- lastIndexOfCat = expectedSubcategories.lastIndexOf(actualSub);
- assertTrue("Actual subcategory " + actualSub + " not found in expected.", lastIndexOfCat != -1);
- SubCategoryDefinition expectedSub = expectedSubcategories.get(lastIndexOfCat);
- List<GroupingDefinition> actualGroupings = actualSub.getGroupings();
- List<GroupingDefinition> expectedGroupings = expectedSub.getGroupings();
- for (GroupingDefinition actualGrouping : actualGroupings) {
- lastIndexOfCat = expectedGroupings.lastIndexOf(actualGrouping);
- assertTrue("Actual grouping " + actualSub + " not found in expected.", lastIndexOfCat != -1);
- }
- }
- }
-
- for (CategoryDefinition expectedDefinition : expectedCategories) {
- int lastIndexOfCat = actualCategories.lastIndexOf(expectedDefinition);
- assertTrue("Expected category " + expectedDefinition + " not found in actual.", lastIndexOfCat != -1);
- CategoryDefinition actualDefinition = actualCategories.get(lastIndexOfCat);
- List<SubCategoryDefinition> actualSubcategories = actualDefinition.getSubcategories();
- List<SubCategoryDefinition> expectedSubcategories = expectedDefinition.getSubcategories();
- for (SubCategoryDefinition expectedSub : expectedSubcategories) {
- lastIndexOfCat = actualSubcategories.lastIndexOf(expectedSub);
- assertTrue("Expected subcategory " + expectedSub + " not found in actual.", lastIndexOfCat != -1);
- SubCategoryDefinition actualSub = actualSubcategories.get(lastIndexOfCat);
- List<GroupingDefinition> actualGroupings = actualSub.getGroupings();
- List<GroupingDefinition> expectedGroupings = expectedSub.getGroupings();
- for (GroupingDefinition expectedGrouping : expectedGroupings) {
- lastIndexOfCat = actualGroupings.lastIndexOf(expectedGrouping);
- assertTrue("Expected grouping " + expectedGrouping + " not found in actual.",
- lastIndexOfCat != -1);
- }
- }
- }
- }
- }
-
- public static void verifyProductsNotExistInUserFollowedPage(User user, Product... nonExpectedProducts)
- throws Exception {
- String component = "products";
- Boolean isExist;
- Product nonExpectedProduct;
- RestResponse getFollowedPage = ProductRestUtils.getFollowed(user.getUserId());
- JSONArray followedProductes = getListArrayFromRestResponse(getFollowedPage, component);
- if (followedProductes != null) { // if any product exist in followed
- // page
- for (int i = 0; i < nonExpectedProducts.length; i++) {
- nonExpectedProduct = nonExpectedProducts[i];
- isExist = false;
- for (int k = 0; k < followedProductes.size(); k++) {
- JSONObject jobject = (JSONObject) followedProductes.get(k);
- if (jobject.get("uuid").toString().equals(nonExpectedProduct.getUUID())) {
- isExist = true;
- k = followedProductes.size();
- }
- }
- assertFalse(isExist);
- }
- }
-
- }
-
- public static void checkUserFollowedPage(User user, Product... expectedProducts) throws Exception {
- String component = "products";
- Boolean isExist;
- Product expectedProduct;
- RestResponse getFollowedPage = ProductRestUtils.getFollowed(user.getUserId());
- JSONArray followedProductes = getListArrayFromRestResponse(getFollowedPage, component);
- assertTrue("check if any followedProductes received ", followedProductes != null);
- assertTrue("check if any expectedProducts and followedProductes are the same size",
- expectedProducts.length == followedProductes.size());
- for (int i = 0; i < expectedProducts.length; i++) {
- expectedProduct = expectedProducts[i];
- isExist = false;
- for (int k = 0; k < followedProductes.size(); k++) {
- JSONObject jobject = (JSONObject) followedProductes.get(k);
- // if(jobject.get("uuid").toString().equals(expectedProduct.getUUID()))
- if (jobject.get("uniqueId").toString().equals(expectedProduct.getUniqueId())) {
-
- String productString = jobject.toJSONString();
- Product actualProduct = ResponseParser.parseToObjectUsingMapper(productString, Product.class);
- ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, null);
- isExist = true;
- k = followedProductes.size();
- }
- }
- assertTrue(isExist);
- }
- }
-
- private static JSONArray getListArrayFromRestResponse(RestResponse restResponse, String lst) {
- String json = restResponse.getResponse();
- JSONObject jsonResp = (JSONObject) JSONValue.parse(json);
- JSONArray resources = (JSONArray) jsonResp.get(lst);
- return resources;
- }
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ResourceValidationUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ResourceValidationUtils.java
deleted file mode 100644
index 7bbadc5c1b..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ResourceValidationUtils.java
+++ /dev/null
@@ -1,358 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utils.validation;
-
-import static org.testng.AssertJUnit.assertEquals;
-import static org.testng.AssertJUnit.assertTrue;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.openecomp.sdc.be.model.ArtifactDefinition;
-import org.openecomp.sdc.be.model.InterfaceDefinition;
-import org.openecomp.sdc.be.model.Operation;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.category.CategoryDefinition;
-import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.ResourceRespJavaObject;
-import org.openecomp.sdc.ci.tests.datatypes.enums.RespJsonKeysEnum;
-import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
-import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
-
-import com.google.gson.Gson;
-
-public class ResourceValidationUtils {
-
- public static void validateResourceReqVsResp(ResourceReqDetails resourceDetails,
- ResourceRespJavaObject resourceRespJavaObject) {
-
- String expected;
-
- expected = resourceDetails.getDescription();
- assertEquals("resource description - ", expected, resourceRespJavaObject.getDescription());
-
- expected = resourceDetails.getVendorName();
- assertEquals("resource vendorName - ", expected, resourceRespJavaObject.getVendorName());
-
- expected = resourceDetails.getVendorRelease();
- assertEquals("resource vendorReleaseName - ", expected, resourceRespJavaObject.getVendorRelease());
-
- expected = resourceDetails.getContactId();
- assertEquals("resource contactId - ", expected, resourceRespJavaObject.getContactId());
-
- }
-
- public static void validateResourceReqVsResp(ResourceReqDetails resourceDetails, Resource resourceRespJavaObject) {
-
- String expected;
-
- expected = resourceDetails.getDescription();
- assertEquals("resource description - ", expected, resourceRespJavaObject.getDescription());
-
- expected = resourceDetails.getVendorName();
- assertEquals("resource vendorName - ", expected, resourceRespJavaObject.getVendorName());
-
- expected = resourceDetails.getVendorRelease();
- assertEquals("resource vendorReleaseName - ", expected, resourceRespJavaObject.getVendorRelease());
-
- expected = resourceDetails.getContactId();
- assertEquals("resource contactId - ", expected, resourceRespJavaObject.getContactId());
-
- // Validating deduplication of tags
- List<String> expectedTags = resourceDetails.getTags();
- if (expectedTags != null) {
- Set<String> hs = new LinkedHashSet<>(expectedTags);
- expectedTags.clear();
- expectedTags.addAll(hs);
- List<String> receivedTags = resourceRespJavaObject.getTags();
- assertEquals("resource tags - ", expectedTags, receivedTags);
- }
-
- }
-
- public static void validateModelObjects(Resource expected, Resource actual) throws Exception {
-
- compareElements(expected.getUniqueId(), actual.getUniqueId());
- compareElements(expected.getName(), actual.getName());
- compareElements(expected.getVersion(), actual.getVersion());
- compareElements(expected.getCreatorUserId(), actual.getCreatorUserId());
- compareElements(expected.getCreatorFullName(), actual.getCreatorFullName());
- compareElements(expected.getLastUpdaterUserId(), actual.getLastUpdaterUserId());
- compareElements(expected.getLastUpdaterFullName(), actual.getLastUpdaterFullName());
- compareElements(expected.getCreatorFullName(), actual.getCreatorFullName());
- compareElements(expected.getCreationDate(), actual.getCreationDate());
- compareElements(expected.getLastUpdateDate(), actual.getLastUpdateDate());
- compareElements(expected.getDescription(), actual.getDescription());
- compareElements(expected.getIcon(), actual.getIcon());
- compareElements(expected.getLastUpdateDate(), actual.getLastUpdateDate());
- // TODO compare tags
- compareElements(expected.getCategories(), actual.getCategories());
- compareElements(expected.getLifecycleState(), actual.getLifecycleState());
- compareElements(expected.getVendorName(), actual.getVendorName());
- compareElements(expected.getVendorRelease(), actual.getVendorRelease());
- compareElements(expected.getContactId(), actual.getContactId());
- compareElements(expected.getUUID(), actual.getUUID());
- compareElements(expected.getVersion(), actual.getVersion());
-
- }
-
- public static void validateResp(RestResponse restResponse, ResourceRespJavaObject resourceRespJavaObject)
- throws Exception {
-
- Gson gson = new Gson();
- String response = restResponse.getResponse();
-
- validateResp(response, resourceRespJavaObject, gson);
-
- }
-
- public static void validateResp(String response, ResourceRespJavaObject resourceRespJavaObject, Gson gson) {
-
- Map<String, Object> map = new HashMap<String, Object>();
- map = (Map<String, Object>) gson.fromJson(response, map.getClass());
-
- // De-duplicating the tags list for comparison
- List<String> tags = resourceRespJavaObject.getTags();
- if (tags != null) {
- Set<String> hs = new LinkedHashSet<>(tags);
- tags = new ArrayList<String>(hs);
- resourceRespJavaObject.setTags(tags);
- tags = new ArrayList<String>(hs);
- resourceRespJavaObject.setTags(tags);
- }
-
- validateField(map, RespJsonKeysEnum.RESOURCE_NAME.getRespJsonKeyName(), resourceRespJavaObject.getName());
- validateField(map, RespJsonKeysEnum.RESOURCE_DESC.getRespJsonKeyName(),
- resourceRespJavaObject.getDescription());
- // validateField(map, RespJsonKeysEnum.CATEGORIES.getRespJsonKeyName(),
- // resourceRespJavaObject.getCategories());
- validateField(map, RespJsonKeysEnum.VENDOR_NAME.getRespJsonKeyName(), resourceRespJavaObject.getVendorName());
- validateField(map, RespJsonKeysEnum.VENDOR_RELEASE.getRespJsonKeyName(),
- resourceRespJavaObject.getVendorRelease());
- validateField(map, RespJsonKeysEnum.CONTACT_ID.getRespJsonKeyName(), resourceRespJavaObject.getContactId());
- validateField(map, RespJsonKeysEnum.ICON.getRespJsonKeyName(), resourceRespJavaObject.getIcon());
- validateField(map, RespJsonKeysEnum.IS_ABSTRACT.getRespJsonKeyName(),
- Boolean.valueOf(resourceRespJavaObject.getAbstractt()));
- validateField(map, RespJsonKeysEnum.HIGHEST_VERSION.getRespJsonKeyName(),
- Boolean.valueOf(resourceRespJavaObject.getIsHighestVersion()));
- validateField(map, RespJsonKeysEnum.UNIQUE_ID.getRespJsonKeyName(), resourceRespJavaObject.getUniqueId());
- validateField(map, RespJsonKeysEnum.RESOURCE_VERSION.getRespJsonKeyName(), resourceRespJavaObject.getVersion());
- validateField(map, RespJsonKeysEnum.LIFE_CYCLE_STATE.getRespJsonKeyName(),
- resourceRespJavaObject.getLifecycleState());
- validateField(map, RespJsonKeysEnum.TAGS.getRespJsonKeyName(), tags);
- validateField(map, RespJsonKeysEnum.CREATOR_USER_ID.getRespJsonKeyName(),
- resourceRespJavaObject.getCreatorUserId());
- validateField(map, RespJsonKeysEnum.CREATOR_FULL_NAME.getRespJsonKeyName(),
- resourceRespJavaObject.getCreatorFullName());
- validateField(map, RespJsonKeysEnum.LAST_UPDATER_USER_ID.getRespJsonKeyName(),
- resourceRespJavaObject.getLastUpdaterUserId());
- validateField(map, RespJsonKeysEnum.LAST_UPDATER_FULL_NAME.getRespJsonKeyName(),
- resourceRespJavaObject.getLastUpdaterFullName());
- validateField(map, RespJsonKeysEnum.COST.getRespJsonKeyName(), resourceRespJavaObject.getCost());
- validateField(map, RespJsonKeysEnum.LICENSE_TYPE.getRespJsonKeyName(), resourceRespJavaObject.getLicenseType());
- validateField(map, RespJsonKeysEnum.RESOURCE_TYPE.getRespJsonKeyName(),
- resourceRespJavaObject.getResourceType().toString());
- if (resourceRespJavaObject.getResourceType().equals("VF")) {
- validateField(map, RespJsonKeysEnum.DERIVED_FROM.getRespJsonKeyName(), null);
- } else {
- validateField(map, RespJsonKeysEnum.DERIVED_FROM.getRespJsonKeyName(),
- resourceRespJavaObject.getDerivedFrom());
- }
-
- validateCategories(resourceRespJavaObject, map);
-
- String uuid = ResponseParser.getValueFromJsonResponse(response, RespJsonKeysEnum.UUID.getRespJsonKeyName());
- assertTrue("UUID is empty", uuid != null && !uuid.isEmpty());
- }
-
- private static void validateCategories(ResourceRespJavaObject resourceRespJavaObject, Map<String, Object> map) {
- assertTrue(RespJsonKeysEnum.CATEGORIES.getRespJsonKeyName() + " is missing",
- map.containsKey(RespJsonKeysEnum.CATEGORIES.getRespJsonKeyName()));
- Object foundValue = map.get(RespJsonKeysEnum.CATEGORIES.getRespJsonKeyName());
- List<Map<String, Object>> foundList = (List<Map<String, Object>>) foundValue;
- List<CategoryDefinition> excpectedList = resourceRespJavaObject.getCategories();
-
- assertTrue(foundList.size() == excpectedList.size());
- for (int i = 0; i < foundList.size(); i++) {
- CategoryDefinition expCat = excpectedList.get(i);
- Map<String, Object> foun = foundList.get(i);
- assertTrue("expected " + expCat.getName() + " not equal to actual " + foundValue,
- foun.get("name").equals(expCat.getName()));
- }
- }
-
- public static void validateField(Map<String, Object> map, String jsonField, Object expectedValue) {
- if (expectedValue == null) {
- assertTrue(jsonField + " is expected to be null", !map.containsKey(jsonField));
- } else {
- assertTrue(jsonField + " is missing", map.containsKey(jsonField));
- Object foundValue = map.get(jsonField);
- compareElements(expectedValue, foundValue);
- }
- }
-
- public static void compareElements(Object expectedValue, Object foundValue) {
- if (expectedValue instanceof String) {
- assertTrue(foundValue instanceof String);
- assertTrue("expected " + expectedValue + " not equal to actual " + foundValue,
- foundValue.equals(expectedValue));
- }
- /*
- * else if( expectedValue instanceof Number){ assertTrue(foundValue
- * instanceof Number); assertTrue(foundValue == expectedValue); }
- */
- else if (expectedValue instanceof Boolean) {
- assertTrue(foundValue instanceof Boolean);
- assertTrue(foundValue == expectedValue);
- } else if (expectedValue instanceof Map) {
- assertTrue(foundValue instanceof Map);
- Map<String, Object> foundMap = (Map<String, Object>) foundValue;
- Map<String, Object> excpectedMap = (Map<String, Object>) expectedValue;
- assertTrue(foundMap.size() == excpectedMap.size());
- Iterator<String> foundkeyItr = foundMap.keySet().iterator();
- while (foundkeyItr.hasNext()) {
- String foundKey = foundkeyItr.next();
- assertTrue(excpectedMap.containsKey(foundKey));
- compareElements(excpectedMap.get(foundKey), foundMap.get(foundKey));
- }
-
- } else if (expectedValue instanceof List) {
- assertTrue(foundValue instanceof List);
- List<Object> foundList = (List<Object>) foundValue;
- List<Object> excpectedList = (List<Object>) expectedValue;
- assertTrue(foundList.size() == excpectedList.size());
- for (int i = 0; i < foundList.size(); i++) {
- compareElements(excpectedList.get(i), foundList.get(i));
- }
-
- } else {
- assertTrue(foundValue.equals(expectedValue));
- }
- }
-
- public static boolean validateUuidAfterChangingStatus(String oldUuid, String newUuid) {
- return oldUuid.equals(newUuid);
-
- }
-
- public static void validateRespArt(RestResponse restResponse, ResourceRespJavaObject resourceRespJavaObject,
- String interfaze) throws Exception {
-
- Gson gson = new Gson();
- String response = restResponse.getResponse();
-
- Map<String, Object> map = new HashMap<String, Object>();
- map = (Map<String, Object>) gson.fromJson(response, map.getClass());
-
- Resource resource = gson.fromJson(response, Resource.class);
-
- Map<String, ArtifactDefinition> artifacts = resource.getArtifacts();
- Map<String, InterfaceDefinition> interfaces = null;
-
- if (interfaze != null) {
- interfaces = resource.getInterfaces();
- Map<String, Operation> operation = interfaces.get(interfaze).getOperationsMap();
- // operation.get("configure").getUniqueId();
- }
-
- validateField(map, RespJsonKeysEnum.RESOURCE_NAME.getRespJsonKeyName(), resourceRespJavaObject.getName());
- validateField(map, RespJsonKeysEnum.RESOURCE_DESC.getRespJsonKeyName(),
- resourceRespJavaObject.getDescription());
- // validateField(map, RespJsonKeysEnum.CATEGORIES.getRespJsonKeyName(),
- // resourceRespJavaObject.getCategories());
- validateField(map, RespJsonKeysEnum.DERIVED_FROM.getRespJsonKeyName(), resourceRespJavaObject.getDerivedFrom());
- validateField(map, RespJsonKeysEnum.VENDOR_NAME.getRespJsonKeyName(), resourceRespJavaObject.getVendorName());
- validateField(map, RespJsonKeysEnum.VENDOR_RELEASE.getRespJsonKeyName(),
- resourceRespJavaObject.getVendorRelease());
- validateField(map, RespJsonKeysEnum.CONTACT_ID.getRespJsonKeyName(), resourceRespJavaObject.getContactId());
- validateField(map, RespJsonKeysEnum.ICON.getRespJsonKeyName(), resourceRespJavaObject.getIcon());
- validateField(map, RespJsonKeysEnum.IS_ABSTRACT.getRespJsonKeyName(),
- Boolean.valueOf(resourceRespJavaObject.getAbstractt()));
- validateField(map, RespJsonKeysEnum.HIGHEST_VERSION.getRespJsonKeyName(),
- Boolean.valueOf(resourceRespJavaObject.getIsHighestVersion()));
- validateField(map, RespJsonKeysEnum.UNIQUE_ID.getRespJsonKeyName(), resourceRespJavaObject.getUniqueId());
- validateField(map, RespJsonKeysEnum.RESOURCE_VERSION.getRespJsonKeyName(), resourceRespJavaObject.getVersion());
- validateField(map, RespJsonKeysEnum.LIFE_CYCLE_STATE.getRespJsonKeyName(),
- resourceRespJavaObject.getLifecycleState());
- validateField(map, RespJsonKeysEnum.TAGS.getRespJsonKeyName(), resourceRespJavaObject.getTags());
- validateField(map, RespJsonKeysEnum.CREATOR_USER_ID.getRespJsonKeyName(),
- resourceRespJavaObject.getCreatorUserId());
- validateField(map, RespJsonKeysEnum.CREATOR_FULL_NAME.getRespJsonKeyName(),
- resourceRespJavaObject.getCreatorFullName());
- validateField(map, RespJsonKeysEnum.LAST_UPDATER_USER_ID.getRespJsonKeyName(),
- resourceRespJavaObject.getLastUpdaterUserId());
- validateField(map, RespJsonKeysEnum.LAST_UPDATER_FULL_NAME.getRespJsonKeyName(),
- resourceRespJavaObject.getLastUpdaterFullName());
-
- // validate number of artifacts
- if (resourceRespJavaObject.getArtifacts() != null) {
-
- // assertEquals("check number of artifacts",
- // resourceRespJavaObject.getArtifacts().size(), artifacts.size());
- int iterNum = -1;
- ArrayList<String> myArtifacats = new ArrayList<String>();
- Iterator it = artifacts.entrySet().iterator();
- while (it.hasNext()) {
- iterNum++;
- Map.Entry pair = (Map.Entry) it.next();
- // System.out.println(pair.getKey() + " = " + pair.getValue());
- ArtifactDefinition myArtifact = artifacts.get(pair.getKey());
- myArtifacats.add(myArtifact.getEsId());
- it.remove(); // avoids a ConcurrentModificationException
- }
- // assertTrue("check service contains
- // artifacts",myArtifacats.containsAll(resourceRespJavaObject.getArtifacts()));
- }
-
- // validate number of interfaces:
-
- if (interfaze != null) {
- assertEquals("check number of interfaces", resourceRespJavaObject.getInterfaces().size(),
- interfaces.size());
- }
-
- }
-
- public static boolean validateResourceIsAbstartct(List<Resource> resourceList, Boolean bool) {
- if (resourceList != null && resourceList.size() > 0) {
- for (Resource resource : resourceList) {
- if (resource.isAbstract().equals(bool))
- continue;
- else
- return false;
- }
- } else
- return false;
- return true;
- }
-
- public static void validateResourceVersion(Resource resource, String expectedVersion) {
- if (resource != null && !resource.equals("")) {
- assertTrue("expected resource version is: " + expectedVersion + ", but actual is: " + resource.getVersion(),
- resource.getVersion().equals(expectedVersion));
- }
- }
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ServiceValidationUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ServiceValidationUtils.java
deleted file mode 100644
index 2f8a0dffc4..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ServiceValidationUtils.java
+++ /dev/null
@@ -1,131 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utils.validation;
-
-import static org.testng.AssertJUnit.assertEquals;
-import static org.testng.AssertJUnit.assertFalse;
-
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Set;
-
-import org.openecomp.sdc.be.model.DistributionStatusEnum;
-import org.openecomp.sdc.be.model.LifecycleStateEnum;
-import org.openecomp.sdc.be.model.Service;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedResourceAuditJavaObject;
-import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
-import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
-
-public class ServiceValidationUtils {
-
- public static void validateServiceResponseMetaData(ServiceReqDetails serviceDetails, Service service, User user,
- LifecycleStateEnum lifecycleState) {
- validateServiceResponseMetaData(serviceDetails, service, user, user, lifecycleState);
- }
-
- public static void validateServiceResponseMetaData(ServiceReqDetails expectedService, Service service,
- User creatorUser, User updaterUser, LifecycleStateEnum lifeCycleState) {
- List<String> expectedTags = expectedService.getTags();
- expectedTags.add(expectedService.getName());
- List<String> receivedTags = service.getTags();
- if (expectedTags != null) {
- Set<String> hs = new LinkedHashSet<>(expectedTags);
- expectedTags.clear();
- expectedTags.addAll(hs);
- }
-
- assertEquals("Check service name on response after create service", expectedService.getName(),
- service.getName());
- // check size of list
- assertEquals("Check only 1 category returned on response after create service", 1,
- expectedService.getCategories().size());
- assertEquals("Check service name on response after create service", expectedService.getName(),
- service.getName());
- assertEquals("Check categories on response after create service",
- expectedService.getCategories().get(0).getName(), service.getCategories().get(0).getName());
- assertEquals("Check tag list on response after create service", expectedTags, receivedTags);
- assertEquals("Check description on response after create service", expectedService.getDescription(),
- service.getDescription());
- // assertEquals("Check vendor name on response after create service",
- // expectedService.getVendorName(), service.getVendorName());
- // assertEquals("Check vendor release on response after create service",
- // expectedService.getVendorRelease(), service.getVendorRelease());
- assertEquals("Check attContant name on response after create service",
- expectedService.getContactId().toLowerCase(), service.getContactId());
- assertEquals("Check icon name on response after create service", expectedService.getIcon(), service.getIcon());
- assertEquals("Check LastUpdaterUserId after create service", updaterUser.getUserId(),
- service.getLastUpdaterUserId());
- assertEquals("Check LastUpdaterName after create service",
- updaterUser.getFirstName() + " " + updaterUser.getLastName(), service.getLastUpdaterFullName());
- assertEquals("Check CreatorUserId after create service", creatorUser.getUserId(), service.getCreatorUserId());
- assertEquals("Check CreatorName after create service",
- creatorUser.getFirstName() + " " + creatorUser.getLastName(), service.getCreatorFullName());
- assertEquals("Check version after create service", expectedService.getVersion(), service.getVersion());
- // assertEquals("Check UniqueId after create service", SERVICE_PREFIX +
- // serviceDetails.getServiceName().toLowerCase()+"." +
- // serviceBaseVersion, service.getUniqueId());
- assertFalse("Check uuid after create service", service.getUUID().isEmpty());
-
- // assertTrue("check creation date after create service",
- // service.getCreationDate() != null);
- // assertTrue("check update date after create service",
- // service.getLastUpdateDate() != null);
-
- if (lifeCycleState != null)
- assertEquals("Check LifecycleState after create service", lifeCycleState, service.getLifecycleState());
- else
- assertEquals("Check LifecycleState after create service", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT,
- service.getLifecycleState());
- }
-
- public static ExpectedResourceAuditJavaObject constructFieldsForAuditValidation(ServiceReqDetails serviceReqDetails,
- String serviceVersion, User sdncUserDetails) {
-
- ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = new ExpectedResourceAuditJavaObject();
-
- expectedResourceAuditJavaObject.setAction("Create");
- expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId());
- String userFirstLastName = sdncUserDetails.getFirstName() + " " + sdncUserDetails.getLastName();
- expectedResourceAuditJavaObject.setModifierName(userFirstLastName);
- expectedResourceAuditJavaObject.setStatus("200");
- expectedResourceAuditJavaObject.setDesc("OK");
- expectedResourceAuditJavaObject.setResourceName(serviceReqDetails.getName());
- expectedResourceAuditJavaObject.setResourceType("Service");
- expectedResourceAuditJavaObject.setPrevVersion(String.valueOf(Float.parseFloat(serviceVersion) - 0.1f));
- expectedResourceAuditJavaObject.setCurrVersion(serviceVersion);
- expectedResourceAuditJavaObject.setPrevState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
- expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
- expectedResourceAuditJavaObject.setComment(null);
-
- return expectedResourceAuditJavaObject;
-
- }
-
- public static void validateDistrubtionStatusValue(RestResponse response,
- DistributionStatusEnum expectedDistributionValue) throws Exception {
- String actualDistributionValue = ResponseParser.getValueFromJsonResponse(response.getResponse(),
- "distributionStatus");
- assertEquals(expectedDistributionValue.name(), actualDistributionValue);
- }
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/TestYamlParser.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/TestYamlParser.java
deleted file mode 100644
index dde27d5cbd..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/TestYamlParser.java
+++ /dev/null
@@ -1,92 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utils.validation;
-
-import java.io.File;
-import java.io.IOException;
-import java.nio.charset.StandardCharsets;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.util.Map;
-import java.util.Set;
-
-import org.junit.Rule;
-import org.junit.rules.TestName;
-import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
-import org.openecomp.sdc.common.util.ZipUtil;
-import org.testng.annotations.Test;
-import org.yaml.snakeyaml.Yaml;
-
-
-
-
-public class TestYamlParser extends ComponentBaseTest{
-
-
-
-
- @Rule
- public static TestName name = new TestName();
-
- public TestYamlParser() {
- super(name, TestYamlParser.class.getName());
- }
-
-
-
-
-
- @Test
- public void testYaml() throws IOException{
-
- System.out.println("");
-
- File file = new File("\\\\Comp-1\\FileIO\\Stop.txt");
-
-
- //read file
-
-
- Map<String, byte[]> readZip = null;
- Path path = Paths.get("C:\\Users\\ys9693\\Documents\\csar\\attributesWithProporties\\attributesWithProporties.csar");
- byte[] data = Files.readAllBytes(path);
- if (data != null && data.length > 0) {
- readZip = ZipUtil.readZip(data);
-
- }
-
- byte[] artifactsBs = readZip.get("Definitions/VF_RI2_G6.yaml");
- String str = new String(artifactsBs, StandardCharsets.UTF_8);
-
-
-
-
- Yaml yaml = new Yaml();
- Map<String, Object> load = (Map<String, Object>) yaml.load(str);
- Map<String, Object> topology_template = (Map<String, Object>) load.get("topology_template");
- Map<String, Object> node_templates = (Map<String, Object>) topology_template.get("node_templates");
-
- Set<String> keySet = node_templates.keySet();
- }
-
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/UserValidationUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/UserValidationUtils.java
deleted file mode 100644
index 31e2327e40..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/UserValidationUtils.java
+++ /dev/null
@@ -1,275 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utils.validation;
-
-import static org.testng.AssertJUnit.assertEquals;
-import static org.testng.AssertJUnit.assertTrue;
-
-import java.util.List;
-
-import org.apache.commons.lang.StringUtils;
-import org.openecomp.sdc.be.dao.utils.UserStatusEnum;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo;
-import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
-import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
-import org.openecomp.sdc.ci.tests.users.AddUserAuditMessageInfo;
-import org.openecomp.sdc.ci.tests.users.UserAuditJavaObject;
-import org.openecomp.sdc.ci.tests.utils.DbUtils;
-import org.openecomp.sdc.ci.tests.utils.Utils;
-
-import com.google.gson.Gson;
-import com.google.gson.JsonArray;
-import com.google.gson.JsonElement;
-import com.google.gson.JsonObject;
-import com.google.gson.JsonParser;
-
-public class UserValidationUtils {
- public static void compareExpectedAndActualUsers(User expected, User actual) {
-
- String actualFirstName = actual.getFirstName();
- String expectedFirstName = expected.getFirstName();
- assertEquals("check user first name - ", expectedFirstName, actualFirstName);
-
- String actualLastName = actual.getLastName();
- String expectedLastName = expected.getLastName();
- assertEquals("check user last name - ", expectedLastName, actualLastName);
-
- String actualUserId = actual.getUserId();
- String expectedUserId = expected.getUserId();
- assertEquals("check user UserId - ", expectedUserId, actualUserId);
-
- String actualEmail = actual.getEmail();
- String expectedEmail = expected.getEmail();
- assertEquals("check user email - ", expectedEmail, actualEmail);
-
- Long actualLastLoginTime = actual.getLastLoginTime();
- Long expectedLastLoginTime = expected.getLastLoginTime();
- assertEquals("check user last login time - ", expectedLastLoginTime, actualLastLoginTime);
-
- String actualRole = actual.getRole();
- if (expected.getRole() == null) {
- String expectedRole = UserRoleEnum.DESIGNER.name();
- assertEquals("check user role - ", expectedRole, actualRole);
- } else {
- String expectedRole = expected.getRole();
- assertEquals("check user role - ", expectedRole, actualRole);
- }
-
- UserStatusEnum actualStatus = expected.getStatus();
- UserStatusEnum expectedStatus = expected.getStatus();
- assertEquals("check user status - ", expectedStatus, actualStatus);
- }
-
- public static void validateDeleteUserAuditMessage(User sdncUserDetails, User sdncModifierDetails,
- String responseCode, String responseMessage, AddUserAuditMessageInfo addUserAuditMessageInfo) {
- String action = "DeleteUser";
- validateUserAuditMessage(sdncUserDetails, sdncModifierDetails, responseCode, responseMessage,
- addUserAuditMessageInfo, action);
-
- }
-
- private static void validateUserAuditMessage(User sdncUserDetails, User sdncModifierDetails, String responseCode,
- String responseMessage, AddUserAuditMessageInfo addUserAuditMessageInfo, String expectedAction) {
-
- assertEquals("check audit action - ", expectedAction, addUserAuditMessageInfo.getACTION());
-
- // String expectedModifierFirstLastName =
- // sdncModifierDetails.getFirstName() + " " +
- // sdncModifierDetails.getLastName();
- // assertEquals("check audit modifier name - ",
- // expectedModifierFirstLastName,
- // addUserAuditMessageInfo.getMODIFIER_NAME());
- String fullName = sdncModifierDetails.getFullName();
- if (sdncModifierDetails.getFullName().equals(" ")) {
- fullName = "";
- }
- String expectedModifierId = fullName + "(" + sdncModifierDetails.getUserId() + ")";
- assertEquals("check audit modifier uid - ", expectedModifierId, addUserAuditMessageInfo.getMODIFIER());
-
- String expectedUserFirstLastName = sdncUserDetails.getFirstName() + " " + sdncUserDetails.getLastName();
- if (expectedUserFirstLastName.equals("null null")) {
- expectedUserFirstLastName = "";
- }
-
- String email = (sdncUserDetails.getEmail() == null) ? "" : sdncUserDetails.getEmail();
- String role = (sdncUserDetails.getRole() == null) ? "DESIGNER" : sdncUserDetails.getRole();
-
- String formatedUser = String.format("%s,%s,%s,%s", sdncUserDetails.getUserId(), expectedUserFirstLastName,
- email, role);
-
- //
- // String expectedUserFirstLastName = sdncUserDetails.getFirstName() + "
- // " + sdncUserDetails.getLastName();
- // if (expectedUserFirstLastName.equals("null null")) {
- // expectedUserFirstLastName = "";
- // }
- //
- // String expectedUserFirstLastName = "";
- // expectedUserFirstLastName += sdncUserDetails.getFirstName() == null ?
- // "" : sdncUserDetails.getFirstName();
- // String lastName = sdncUserDetails.getLastName() == null ? "" :
- // sdncUserDetails.getLastName();
- // if (expectedUserFirstLastName.isEmpty()) {
- // expectedUserFirstLastName = lastName;
- // } else {
- // expectedUserFirstLastName += " " + lastName;
- // }
-
- assertEquals("check audit user name - ", formatedUser, addUserAuditMessageInfo.getUSER());
-
- // String expectedUserUid = sdncUserDetails.getUserId();
- // assertEquals("check audit user uid - ", expectedUserUid,
- // addUserAuditMessageInfo.getUSER_UID());
- //
- // String expectedUserEmail = sdncUserDetails.getEmail() == null ? "" :
- // sdncUserDetails.getEmail();
- // //TODO: esofer check with Andrey. Audit return "" but in user we have
- // null
- // assertEquals("check audit user email - ", expectedUserEmail,
- // addUserAuditMessageInfo.getUSER_EMAIL());
- //
- // String expectedUserRole = sdncUserDetails.getRole();
- // if (expectedUserRole ==null){
- // expectedUserRole = "DESIGNER";
- // assertEquals("check audit user role - ", expectedUserRole,
- // addUserAuditMessageInfo.getUSER_ROLE());
- // }else{
- // assertEquals("check audit user role - ", expectedUserRole,
- // addUserAuditMessageInfo.getUSER_ROLE());
- // }
-
- String expectedUserResponseCode = responseCode;
- assertEquals("check audit user response code - ", expectedUserResponseCode,
- addUserAuditMessageInfo.getSTATUS());
-
- String expectedUserResponseMessage = responseMessage;
- assertEquals("check audit user response message - ", expectedUserResponseMessage,
- addUserAuditMessageInfo.getDESC());
-
- }
-
- public static void validateDataAgainstAuditDB_access(User sdncUserDetails, UserAuditJavaObject auditJavaObject,
- RestResponse restResponse, ErrorInfo errorInfo, List<String> variables) {
-
- validateAuditDataAgainstAuditDbInAccess(sdncUserDetails, auditJavaObject, restResponse, errorInfo, variables);
-
- }
-
- public static void validateAuditDataAgainstAuditDbInAccess(User sdncUserDetails,
- UserAuditJavaObject auditJavaObject, RestResponse restResponse, ErrorInfo errorInfo,
- List<String> variables) {
-
- String expected;
-
- expected = "Access";
- assertEquals("ACTION- ", expected, auditJavaObject.getACTION());
-
- if (sdncUserDetails.getFirstName() != StringUtils.EMPTY && sdncUserDetails.getLastName() != StringUtils.EMPTY) {
- expected = sdncUserDetails.getFirstName() + " " + sdncUserDetails.getLastName();
- } else {
- expected = StringUtils.EMPTY;
- }
- String formatedUser = String.format("%s(%s)", expected, sdncUserDetails.getUserId());
- assertTrue(
- "check audit user: expected start with - " + formatedUser + " ,actual - " + auditJavaObject.getUSER(),
- auditJavaObject.getUSER().startsWith(formatedUser));
-
- expected = restResponse.getErrorCode().toString();
- assertEquals("check audit user status code - ", expected, auditJavaObject.getSTATUS());
-
- if (restResponse.getErrorCode() == 200 || restResponse.getErrorCode() == 201) {
- expected = errorInfo.getMessage();
- } else {
- expected = AuditValidationUtils.buildAuditDescription(errorInfo, variables);
- }
-
- assertEquals("check audit user desc - ", expected, auditJavaObject.getDESC());
- }
-
- public static void validateUserDetailsOnResponse(User sdncUserDetails, String userDetailsOnResponse) {
-
- String actualFirstName = Utils.getJsonObjectValueByKey(userDetailsOnResponse, "firstName");
- String expectedFirstName = sdncUserDetails.getFirstName();
- assertEquals("check user first name - ", expectedFirstName, actualFirstName);
-
- String actualLastName = Utils.getJsonObjectValueByKey(userDetailsOnResponse, "lastName");
- String expectedLastName = sdncUserDetails.getLastName();
- assertEquals("check user last name - ", expectedLastName, actualLastName);
-
- String actualUserId = Utils.getJsonObjectValueByKey(userDetailsOnResponse, "userId");
- String expectedUserId = sdncUserDetails.getUserId();
- assertEquals("check user UserId - ", expectedUserId, actualUserId);
-
- String actualEmail = Utils.getJsonObjectValueByKey(userDetailsOnResponse, "email");
- String expectedEmail = sdncUserDetails.getEmail();
- assertEquals("check user email - ", expectedEmail, actualEmail);
-
- String actualRole = Utils.getJsonObjectValueByKey(userDetailsOnResponse, "role");
- if (sdncUserDetails.getRole() == null) {
- String expectedRole = UserRoleEnum.DESIGNER.name();
- assertEquals("check user role - ", expectedRole, actualRole);
- } else {
- String expectedRole = sdncUserDetails.getRole();
- assertEquals("check user role - ", expectedRole, actualRole);
- }
-
- String actualStatus = Utils.getJsonObjectValueByKey(userDetailsOnResponse, "status");
- String expectedStatus = sdncUserDetails.getStatus().name();
- assertEquals("check user status - ", expectedStatus, actualStatus);
-
- }
-
- public static AddUserAuditMessageInfo getAddUserAuditMessage(String action) throws Exception {
-
- Gson gson = new Gson();
- String index = "auditingevents*";
- String type = "useradminevent";
- String pattern = "/_search?q=ACTION:\"" + action + "\"";
- String auditingMessage = DbUtils.retrieveAuditMessagesByPattern(pattern);
- // String auditingMessage = retrieveAuditMessageByIndexType(index, type,
- // pattern);
- JsonElement jElement = new JsonParser().parse(auditingMessage);
- JsonObject jObject = jElement.getAsJsonObject();
- JsonObject hitsObject = (JsonObject) jObject.get("hits");
- JsonArray hitsArray = (JsonArray) hitsObject.get("hits");
- // for (int i = 0; i < hitsArray.size();){
- if (hitsArray != null) {
- JsonObject jHitObject = (JsonObject) hitsArray.get(0);
- JsonObject jSourceObject = (JsonObject) jHitObject.get("_source");
- AddUserAuditMessageInfo addUserAuditMessageInfo = new AddUserAuditMessageInfo();
- addUserAuditMessageInfo = gson.fromJson(jSourceObject, AddUserAuditMessageInfo.class);
- return addUserAuditMessageInfo;
- }
- return null;
-
- }
-
- public static void validateAddUserAuditMessage(User sdncUserDetails, User sdncModifierDetails, String responseCode,
- String responseMessage, AddUserAuditMessageInfo addUserAuditMessageInfo) {
-
- String action = "AddUser";
- validateUserAuditMessage(sdncUserDetails, sdncModifierDetails, responseCode, responseMessage,
- addUserAuditMessageInfo, action);
-
- }
-
-}