diff options
Diffstat (limited to 'test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils')
33 files changed, 1960 insertions, 2059 deletions
diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/CsarParserUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/CsarParserUtils.java index cd6687be0e..157377f47f 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/CsarParserUtils.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/CsarParserUtils.java @@ -64,7 +64,7 @@ public class CsarParserUtils { Object parse = parser.parse(csarPayload); JSONObject jsonObject = (JSONObject) parse; JSONObject jsonObjectImportStructure = (JSONObject) jsonObject.get(ToscaParameterConstants.IMPORT_STRUCTURE); - List<TypeHeatMetaDefinition> listHeatMetaDefenition = new ArrayList<TypeHeatMetaDefinition>(); + List<TypeHeatMetaDefinition> listHeatMetaDefenition = new ArrayList<>(); listHeatMetaDefenition = getArtifactsByGroup(jsonObjectImportStructure, listHeatMetaDefenition); return listHeatMetaDefenition; } @@ -82,7 +82,7 @@ public class CsarParserUtils { log.debug("{}", jsonObjectImportStructure.get(type)); JSONArray array = (JSONArray) jsonObjectImportStructure.get(type); heatMetaDefenition.setTypeName((String) type); - List<GroupHeatMetaDefinition> groupHeatMetaDefinitions = new ArrayList<GroupHeatMetaDefinition>(); + List<GroupHeatMetaDefinition> groupHeatMetaDefinitions = new ArrayList<>(); heatMetaDefenition.setGroupHeatMetaDefinition(fetchArtifactByGroupFromJsonArray(array, groupHeatMetaDefinitions, true, false)); listHeatMetaDefenition.add(heatMetaDefenition); } @@ -108,6 +108,16 @@ public class CsarParserUtils { } groupHeatMetaDefinition = listGroupHeatMetaDefinition.get(listGroupHeatMetaDefinition.size() - 1); JSONObject jsonObject = (JSONObject) array.get(i); + if (openNewGroup) { + String groupName; + int lastIndexOfDot = jsonObject.get("fileName").toString().lastIndexOf("."); + if(lastIndexOfDot == -1){ + groupName = jsonObject.get("fileName").toString(); + }else { + groupName = jsonObject.get("fileName").toString().substring(0, lastIndexOfDot); + } + groupHeatMetaDefinition.setGroupName(groupName); + } fetchArtifactByGroupFromJsonObject(listGroupHeatMetaDefinition, groupHeatMetaDefinition, jsonObject, isNested); } } diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/DistributionUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/DistributionUtils.java index 35c25b7157..835ef6ebb3 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/DistributionUtils.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/DistributionUtils.java @@ -40,6 +40,7 @@ import org.openecomp.sdc.ci.tests.api.Urls; import org.openecomp.sdc.ci.tests.config.Config; import org.openecomp.sdc.ci.tests.datatypes.DistributionMonitorObject; import org.openecomp.sdc.ci.tests.datatypes.ServiceDistributionStatus; +import org.openecomp.sdc.ci.tests.datatypes.enums.DistributionNotificationStatusEnum; 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; @@ -51,6 +52,7 @@ import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils; import com.clearspring.analytics.util.Pair; import com.google.gson.Gson; +import fj.data.Either; public class DistributionUtils extends BaseRestUtils{ diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/ToscaParserUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/ToscaParserUtils.java index 0c193ad13c..f345aad60c 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/ToscaParserUtils.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/ToscaParserUtils.java @@ -43,7 +43,7 @@ import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaTopologyTemplateDefinitio 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.http.client.api.HttpResponse; import org.openecomp.sdc.common.util.ZipUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -193,8 +193,8 @@ public class ToscaParserUtils { public static String getCsarPayload(String csarName, String yamlFileLocation) throws Exception { - RestResponseAsByteArray csar = ImportRestUtils.getCsar(csarName, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); - assertTrue("Return response code different from 200", csar.getHttpStatusCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + HttpResponse<byte []> csar = ImportRestUtils.getCsar(csarName, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)); + assertTrue("Return response code different from 200", csar.getStatusCode() == BaseRestUtils.STATUS_CODE_SUCCESS); byte[] data = csar.getResponse(); return getDataFromZipFileByBytes(yamlFileLocation, data); diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/Utils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/Utils.java index 3515191433..05dcc7e663 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/Utils.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/Utils.java @@ -34,6 +34,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Map.Entry; +import java.util.concurrent.TimeUnit; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; @@ -228,6 +229,15 @@ public final class Utils { return config; } + public static Config getConfigHandleException() { + Config config = null; + try{ + config = Config.instance(); + }catch (Exception e){ + System.out.println("Configuration file not found. " + e); + } + return config; + } // public void uploadNormativeTypes() throws IOException{ // Config config = getConfig(); // String[] normativeTypes = {"root", "compute", "blockStorage", @@ -686,4 +696,12 @@ public final class Utils { long epoch = date.getTime(); return epoch; } + + public static Long getActionDuration(Runnable func) throws Exception{ + long startTime = System.nanoTime(); + func.run(); + long estimateTime = System.nanoTime(); + long duration = TimeUnit.NANOSECONDS.toSeconds(estimateTime - startTime); + return duration; + } } diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/cassandra/CassandraUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/cassandra/CassandraUtils.java index bd1066a662..aa68392adc 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/cassandra/CassandraUtils.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/cassandra/CassandraUtils.java @@ -21,10 +21,10 @@ package org.openecomp.sdc.ci.tests.utils.cassandra; import java.io.FileNotFoundException; +import com.datastax.driver.core.policies.*; 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; @@ -38,188 +38,212 @@ 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.policies.ConstantReconnectionPolicy; +import com.datastax.driver.core.policies.DCAwareRoundRobinPolicy; +import com.datastax.driver.core.policies.DefaultRetryPolicy; +import com.datastax.driver.core.policies.LoadBalancingPolicy; +import com.datastax.driver.core.policies.TokenAwarePolicy; 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<>(); + private static Logger logger = LoggerFactory.getLogger(CassandraUtils.class.getName()); + + protected static Cluster cluster = null; + protected static Session session; + + public static void initConnection(String keyspace) throws FileNotFoundException { + List<String> cassandraHosts = new ArrayList<>(); + try { + cassandraHosts.add(Utils.getConfig().getCassandraHost()); + long reconnectTimeout = 30000; + + logger.debug("creating cluster to hosts:{} with reconnect timeout:{}", cassandraHosts, reconnectTimeout); + Cluster.Builder clusterBuilder = Cluster.builder() + .withReconnectionPolicy(new ConstantReconnectionPolicy(reconnectTimeout)) + .withRetryPolicy(DefaultRetryPolicy.INSTANCE); + + cassandraHosts.forEach(host -> clusterBuilder.addContactPoint(host)); + enableAuthentication(clusterBuilder); + enableSsl(clusterBuilder); + setLocalDc(clusterBuilder); + + cluster = clusterBuilder.build(); + session = cluster.connect(keyspace); + } catch (Exception e) { + logger.info("** CassandraClient isn't connected to {}", cassandraHosts); + } + } + + private static void enableAuthentication(Cluster.Builder clusterBuilder) throws FileNotFoundException { + boolean authenticate = Utils.getConfig().getCassandraAuthenticate(); + if (authenticate) { + String username = Utils.getConfig().getCassandraUsername(); + String password = Utils.getConfig().getCassandraPassword(); + if (username == null || password == null) { + logger.error("authentication is enabled but username or password were not supplied."); + } else { + clusterBuilder.withCredentials(username, password); + } + + } + } + + private static void enableSsl(Cluster.Builder clusterBuilder) throws FileNotFoundException { + boolean ssl = Utils.getConfig().getCassandraSsl(); + if (ssl) { + String truststorePath = Utils.getConfig().getCassandraTruststorePath(); + String truststorePassword = Utils.getConfig().getCassandraTruststorePassword(); + if (truststorePath == null || truststorePassword == null) { + logger.error("ssl is enabled but truststorePath or truststorePassword were not supplied."); + } else { + System.setProperty("javax.net.ssl.trustStore", truststorePath); + System.setProperty("javax.net.ssl.trustStorePassword", truststorePassword); + clusterBuilder.withSSL(); + } + } + } + + + private static void setLocalDc(Cluster.Builder clusterBuilder) throws FileNotFoundException { + String localDataCenter = Utils.getConfig().getLocalDataCenter(); + if (localDataCenter != null) { + logger.info("localDatacenter was provided, setting Cassndra clint to use datacenter: {} as local.", localDataCenter); + LoadBalancingPolicy tokenAwarePolicy = new TokenAwarePolicy(DCAwareRoundRobinPolicy.builder().withLocalDc(localDataCenter).build()); + clusterBuilder.withLoadBalancingPolicy(tokenAwarePolicy); + } else { + logger.info("localDatacenter was provided, the driver will use the datacenter of the first contact point that was reached at initialization"); + } + } + + public static void truncateTable(String keyspace, String tableName) throws FileNotFoundException { + + if (session == null || session.isClosed()) { + initConnection(keyspace); + } + + try (Cluster cluster = CassandraUtils.cluster){ + + 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"); + } + } + } + + 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 ); - // } + + 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; + } + + + } diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/AtomicOperationUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/AtomicOperationUtils.java index 56c350f471..e81c63fa53 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/AtomicOperationUtils.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/AtomicOperationUtils.java @@ -38,18 +38,22 @@ 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.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.enums.AssetTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +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.ComponentInstanceProperty; import org.openecomp.sdc.be.model.DistributionStatusEnum; +import org.openecomp.sdc.be.model.GroupDefinition; 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.be.model.GroupDefinition; import org.openecomp.sdc.ci.tests.api.ComponentBaseTest; import org.openecomp.sdc.ci.tests.api.ExtentTestActions; import org.openecomp.sdc.ci.tests.api.Urls; @@ -76,6 +80,7 @@ import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; import org.openecomp.sdc.ci.tests.utils.CsarToscaTester; import org.openecomp.sdc.ci.tests.utils.DistributionUtils; import org.openecomp.sdc.ci.tests.utils.Utils; +import org.openecomp.sdc.ci.tests.utils.Utils; import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils; import org.openecomp.sdc.ci.tests.utils.rest.AssetRestUtils; import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils; @@ -118,7 +123,7 @@ public final class AtomicOperationUtils { public static Either<Resource, RestResponse> importResource(String filePath, String fileName) { try { User designer = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); - ImportReqDetails importReqDetails = ElementFactory.getDefaultImportResource("ciTmpVFC"); + ImportReqDetails importReqDetails = ElementFactory.getDefaultImportResource(ElementFactory.getResourcePrefix()); importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, filePath, fileName); RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, designer, null); return buildResourceFromResponse(importResourceResponse); @@ -127,6 +132,26 @@ public final class AtomicOperationUtils { } } + public static Either<Resource, RestResponse> importResource(ImportReqDetails importReqDetails, String filePath, String fileName, User userRole, Boolean validateState) { + try { + importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, filePath, fileName); + RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, userRole, null); + + if (validateState) { + assertTrue("Import resource failed with error: " + importResourceResponse.getResponse(),importResourceResponse.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED); + } + + if (importResourceResponse.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) { + Resource resourceResponseObject = ResponseParser.convertResourceResponseToJavaObject(importResourceResponse.getResponse()); + return Either.left(resourceResponseObject); + } + return Either.right(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); @@ -134,7 +159,7 @@ public final class AtomicOperationUtils { RestResponse resourceResp = ResourceRestUtils.createResource(defaultResource, defaultUser); if (validateState) { - assertTrue(resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED); + assertTrue("Create resource failed with error: " + resourceResp.getResponse(),resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED); } if (resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) { @@ -153,7 +178,7 @@ public final class AtomicOperationUtils { RestResponse resourceResp = ResourceRestUtils.createResource(resourceDetails, defaultUser); if (validateState) { - assertTrue(resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED); + assertTrue("Create resource failed with error: " + resourceResp.getResponse(),resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED); } if (resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) { @@ -192,7 +217,7 @@ public final class AtomicOperationUtils { RestResponse resourceResp = ResourceRestUtils.createResource(defaultResource, defaultUser); if (validateState) { - assertTrue("actual result: " + resourceResp.getResponseMessage(), resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED); + assertTrue("Create resource failed with error: " + resourceResp.getResponse(), resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED); } if (resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) { @@ -210,7 +235,7 @@ public final class AtomicOperationUtils { RestResponse resourceResp = ResourceRestUtils.updateResource(resourceReqDetails, defaultUser, resourceReqDetails.getUniqueId()); if (validateState) { - assertTrue(resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_SUCCESS); + assertTrue("Update resource failed with error: " + resourceResp.getResponse(),resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_SUCCESS); } if (resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_SUCCESS) { @@ -231,7 +256,7 @@ public final class AtomicOperationUtils { RestResponse createServiceResp = ServiceRestUtils.createService(serviceDetails, defaultUser); if (validateState) { - assertTrue(createServiceResp.getErrorCode() == ServiceRestUtils.STATUS_CODE_CREATED); + assertTrue("Create service failed with error: " + createServiceResp.getResponse(),createServiceResp.getErrorCode() == ServiceRestUtils.STATUS_CODE_CREATED); } if (createServiceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) { @@ -247,7 +272,7 @@ public final class AtomicOperationUtils { RestResponse createServiceResp = ServiceRestUtils.createService(serviceDetails, defaultUser); if (validateState) { - assertTrue(createServiceResp.getErrorCode() == ServiceRestUtils.STATUS_CODE_CREATED); + assertTrue("Create service failed with error: " + createServiceResp.getResponse(),createServiceResp.getErrorCode() == ServiceRestUtils.STATUS_CODE_CREATED); } if (createServiceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) { @@ -262,7 +287,7 @@ public final class AtomicOperationUtils { RestResponse createServiceResp = ServiceRestUtils.createService(serviceDetails, defaultUser); if (validateState) { - assertTrue(createServiceResp.getErrorCode() == ServiceRestUtils.STATUS_CODE_CREATED); + assertTrue("Create service failed with error: " + createServiceResp.getResponse(),createServiceResp.getErrorCode() == ServiceRestUtils.STATUS_CODE_CREATED); } if (createServiceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) { @@ -329,10 +354,8 @@ public final class AtomicOperationUtils { component = getComponentObject(component, userRole); return Pair.of(component, null); } - // List<LifeCycleStatesEnum> lifeCycleStatesEnumOrigList = new - // ArrayList<LifeCycleStatesEnum>(EnumSet.allOf(LifeCycleStatesEnum.class)); - ArrayList<String> lifeCycleStatesEnumList = new ArrayList<String>(); + ArrayList<String> lifeCycleStatesEnumList = new ArrayList<>(); if (curentCompState.equals(LifeCycleStatesEnum.CHECKIN) && targetState.equals(LifeCycleStatesEnum.CHECKOUT)) { lifeCycleStatesEnumList.add(LifeCycleStatesEnum.CHECKIN.toString()); lifeCycleStatesEnumList.add(LifeCycleStatesEnum.CHECKOUT.toString()); @@ -395,16 +418,14 @@ public final class AtomicOperationUtils { } if (validateState) { - assertTrue(approveDistribution.getErrorCode() == ProductRestUtils.STATUS_CODE_SUCCESS); - assertTrue(distributionService.getErrorCode() == ProductRestUtils.STATUS_CODE_SUCCESS); + assertTrue("Distribution approve failed with error: " + approveDistribution.getResponse(),approveDistribution.getErrorCode() == ProductRestUtils.STATUS_CODE_SUCCESS); + assertTrue("Distribute service failed with error: " + distributionService.getResponse(),distributionService.getErrorCode() == ProductRestUtils.STATUS_CODE_SUCCESS); return distributionService; } return distributionService; - } - - + public static void toscaValidation(Component component, String vnfFile) throws Exception { ISdcCsarHelper fdntCsarHelper; @@ -476,6 +497,34 @@ public final class AtomicOperationUtils { } } + public static Either<ComponentInstance, RestResponse> addComponentInstanceToComponentContainer(Component compInstParent, Component compContainer, UserRoleEnum userRole, Boolean validateState, String positionX, String positionY) { + try { + User defaultUser = ElementFactory.getDefaultUser(userRole); + ComponentInstanceReqDetails componentInstanceDetails = ElementFactory.getComponentInstance(compInstParent); + componentInstanceDetails.setPosX(positionX); + componentInstanceDetails.setPosY(positionY); + RestResponse createComponentInstance = ComponentInstanceRestUtils.createComponentInstance(componentInstanceDetails, defaultUser, compContainer); + + if (validateState) { + if (createComponentInstance.getErrorCode() == ServiceRestUtils.STATUS_CODE_NOT_FOUND) + { + throw new SkipException("Open bug DE262001"); + } + else{ + assertTrue("error - " + createComponentInstance.getErrorCode() + "instead - " + ServiceRestUtils.STATUS_CODE_CREATED, 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()); @@ -619,7 +668,7 @@ public final class AtomicOperationUtils { 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>(); + Map<String, PropertyReqDetails> propertyToSend = new HashMap<>(); propertyToSend.put(propDetails.getName(), propDetails); Gson gson = new Gson(); RestResponse addPropertyResponse = PropertyRestUtils.createProperty(resourceDetails.getUniqueId(), gson.toJson(propertyToSend), defaultUser); @@ -641,7 +690,7 @@ public final class AtomicOperationUtils { 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>(); + Map<String, PropertyReqDetails> propertyToSend = new HashMap<>(); propertyToSend.put(propDetails.getName(), propDetails); Gson gson = new Gson(); RestResponse addPropertyResponse = PropertyRestUtils.updateProperty(resourceDetails.getUniqueId(), propertyUniqueId, gson.toJson(propertyToSend), defaultUser); @@ -668,7 +717,7 @@ public final class AtomicOperationUtils { User defaultUser = ElementFactory.getDefaultUser(userRole); PropertyReqDetails propDetails = ElementFactory.getPropertyDetails(propertyType); - Map<String, PropertyReqDetails> propertyToSend = new HashMap<String, PropertyReqDetails>(); + Map<String, PropertyReqDetails> propertyToSend = new HashMap<>(); propertyToSend.put(propDetails.getName(), propDetails); Gson gson = new Gson(); RestResponse addPropertyResponse = PropertyRestUtils.createProperty(resourceDetails.getUniqueId(), gson.toJson(propertyToSend), defaultUser); @@ -687,6 +736,23 @@ public final class AtomicOperationUtils { return Either.right(addPropertyResponse); } + public static Either<GroupDefinition, RestResponse> updateGroupPropertyOnResource(List<PropertyDataDefinition> propertyObject, Resource resource, String groupId, User user, Boolean validateState) throws Exception { + + Gson gson = new Gson(); + RestResponse updateGroupPropertyResponse = PropertyRestUtils.updateGroupProperty(resource, groupId, gson.toJson(propertyObject), user); + + if (validateState) { + assertTrue("update group property to resource failed: " + updateGroupPropertyResponse.getResponseMessage(), updateGroupPropertyResponse.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + } + + if (updateGroupPropertyResponse.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS) { + GroupDefinition responseGroupDefinition = ResponseParser.convertPropertyResponseToObject(updateGroupPropertyResponse.getResponse()); + return Either.left(responseGroupDefinition); + } + return Either.right(updateGroupPropertyResponse); + } + + public static RestResponse createDefaultConsumer(Boolean validateState) { try { ConsumerDataDefinition defaultConsumerDefinition = ElementFactory.getDefaultConsumerDetails(); @@ -725,7 +791,7 @@ public final class AtomicOperationUtils { } private static final long serialVersionUID = 1L; - }; + } /** * Import resource from CSAR @@ -801,11 +867,11 @@ public final class AtomicOperationUtils { url = String.format(Urls.UI_DOWNLOAD_RESOURCE_ARTIFACT, config.getCatalogBeHost(), config.getCatalogBePort(), component.getUniqueId(), component.getToscaArtifacts().get(artifactType).getUniqueId()); } String userId = component.getLastUpdaterUserId(); - Map<String, String> headersMap = new HashMap<String, String>(); - headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json"); - headersMap.put(HttpHeaderEnum.CACHE_CONTROL.getValue(), "no-cache"); + Map<String, String> headersMap = new HashMap<>(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), BaseRestUtils.contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.CACHE_CONTROL.getValue(), BaseRestUtils.cacheControlHeader); headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), basicAuthentication); - headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci"); + headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), BaseRestUtils.xEcompInstanceId); if (userId != null) { headersMap.put(HttpHeaderEnum.USER_ID.getValue(), userId); } @@ -818,7 +884,7 @@ public final class AtomicOperationUtils { } - public static RestResponse getDistributionStatusByDistributionId(String distributionId ,Boolean validateState) { + public static RestResponse getDistributionStatusByDistributionId(String distributionId, Boolean validateState) { try { User defaultUser = ElementFactory.getDefaultUser(UserRoleEnum.OPS); @@ -834,12 +900,11 @@ public final class AtomicOperationUtils { } } - public static Either <RestResponse, Map<String, List<DistributionMonitorObject>>> getSortedDistributionStatusMap(Service service ,Boolean validateState) { + public static Either <RestResponse, Map<String, List<DistributionMonitorObject>>> getSortedDistributionStatusMap(Service service, Boolean validateState) { try { ServiceDistributionStatus serviceDistributionObject = DistributionUtils.getLatestServiceDistributionObject(service); RestResponse response = getDistributionStatusByDistributionId(serviceDistributionObject.getDistributionID(), true); - if(validateState) { assertTrue(response.getErrorCode() == ResourceRestUtils.STATUS_CODE_SUCCESS); } @@ -863,36 +928,39 @@ public final class AtomicOperationUtils { * @throws Exception */ public static Boolean distributeAndValidateService(Service service, int pollingCount, int pollingInterval) throws Exception { - + int firstPollingInterval = 30000; //this value define first be polling topic time, should change if DC configuration changed Boolean statusFlag = true; AtomicOperationUtils.distributeService(service, true); - TimeUnit.MILLISECONDS.sleep(pollingInterval); + TimeUnit.MILLISECONDS.sleep(firstPollingInterval); int timeOut = pollingCount * pollingInterval; + com.clearspring.analytics.util.Pair<Boolean,Map<String,List<String>>> verifyDistributionStatus = null; + while (timeOut > 0) { Map<String,List<DistributionMonitorObject>> sortedDistributionStatusMap = AtomicOperationUtils.getSortedDistributionStatusMap(service, true).right().value(); - com.clearspring.analytics.util.Pair<Boolean,Map<String,List<String>>> verifyDistributionStatus = DistributionUtils.verifyDistributionStatus(sortedDistributionStatusMap); + verifyDistributionStatus = DistributionUtils.verifyDistributionStatus(sortedDistributionStatusMap); if(verifyDistributionStatus.left.equals(false)){ - if((verifyDistributionStatus.right != null && ! verifyDistributionStatus.right.isEmpty()) && timeOut == 0){ - for(Entry<String, List<String>> entry : verifyDistributionStatus.right.entrySet()){ - if(ComponentBaseTest.getExtendTest() != null){ - ComponentBaseTest.getExtendTest().log(Status.INFO, "Consumer: " + entry.getKey() + " failed on following: "+ entry.getValue()); - statusFlag = false; - }else{ - System.out.println("Consumer: " + entry.getKey() + " failed on following: "+ entry.getValue()); - } - } - } TimeUnit.MILLISECONDS.sleep(pollingInterval); timeOut-=pollingInterval; }else { timeOut = 0; } } + + if((verifyDistributionStatus.right != null && ! verifyDistributionStatus.right.isEmpty())){ + for(Entry<String, List<String>> entry : verifyDistributionStatus.right.entrySet()){ + if(ComponentBaseTest.getExtendTest() != null){ + ComponentBaseTest.getExtendTest().log(Status.INFO, "Consumer: " + entry.getKey() + " failed on following: "+ entry.getValue()); + }else{ + System.out.println("Consumer: [" + entry.getKey() + "] failed on following: "+ entry.getValue()); + } + } + statusFlag = false; + } return statusFlag; } public static Boolean distributeAndValidateService(Service service) throws Exception { - return distributeAndValidateService(service, 6, 10000); + return distributeAndValidateService(service, 10, 10000); } } diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/ElementFactory.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/ElementFactory.java index 8224f08018..d1701241fe 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/ElementFactory.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/ElementFactory.java @@ -20,49 +20,18 @@ 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.*; 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.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.*; +import org.openecomp.sdc.ci.tests.datatypes.enums.*; 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; @@ -72,6 +41,12 @@ import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils; import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; import org.openecomp.sdc.common.util.ValidationUtils; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + public class ElementFactory { private static final String CI_SERVICE = "ciService"; @@ -131,6 +106,10 @@ public class ElementFactory { } // New + public static ResourceReqDetails getDefaultResourceByType(ResourceTypeEnum ResourceType, String resourceName, ResourceCategoryEnum resourceCategory, String vendorName, String vendorModelNumber) { + return getDefaultResourceByType(resourceName, NormativeTypesEnum.ROOT, resourceCategory, "jh0003", ResourceType.toString(), vendorName, vendorModelNumber); + } + public static ResourceReqDetails getDefaultResourceByType(ResourceTypeEnum ResourceType, String resourceName) { return getDefaultResourceByType(resourceName, NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, "jh0003", ResourceType.toString()); } @@ -154,10 +133,10 @@ public class ElementFactory { 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>(); + ArrayList<String> resourceTags = new ArrayList<>(); resourceTags.add(resourceName); - ArrayList<String> derivedFrom = new ArrayList<String>(); + ArrayList<String> derivedFrom = new ArrayList<>(); derivedFrom.add(derived.normativeName); String vendorName = "ATT Tosca"; String vendorRelease = "1.0.0.wd03"; @@ -177,10 +156,10 @@ public class ElementFactory { 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>(); + ArrayList<String> resourceTags = new ArrayList<>(); resourceTags.add(resourceName); - ArrayList<String> derivedFrom = new ArrayList<String>(); + ArrayList<String> derivedFrom = new ArrayList<>(); derivedFrom.add(derived.getToscaResourceName()); String vendorName = "ATT Tosca"; String vendorRelease = "1.0.0.wd03"; @@ -200,7 +179,7 @@ public class ElementFactory { 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>(); + ArrayList<String> resourceTags = new ArrayList<>(); resourceTags.add(resourceName); ArrayList<String> derivedFrom = null; if (derived != null) { @@ -216,6 +195,25 @@ public class ElementFactory { return resourceDetails; } + public static ResourceReqDetails getDefaultResourceByType(String resourceName, NormativeTypesEnum derived, ResourceCategoryEnum category, String contactId, String resourceType, String vendorName, String vendorModelNumber) { + 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<>(); + resourceTags.add(resourceName); + ArrayList<String> derivedFrom = null; + if (derived != null) { + derivedFrom = new ArrayList<>(); + derivedFrom.add(derived.normativeName); + } + 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()); + resourceDetails.setResourceVendorModelNumber(vendorModelNumber); + return resourceDetails; + } + public static ResourceReqDetails getRandomCategoryResource() { ResourceReqDetails resourceDetails = getDefaultResource(ResourceCategoryEnum.getRandomElement()); return resourceDetails; @@ -224,7 +222,7 @@ public class ElementFactory { 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>(); + ArrayList<String> resourceTags = new ArrayList<>(); resourceTags.add(resourceName); String vendorName = "ATT Tosca"; String vendorRelease = "1.0.0.wd03"; @@ -239,11 +237,11 @@ public class ElementFactory { 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>(); + ArrayList<String> resourceTags = new ArrayList<>(); resourceTags.add(resourceName); ArrayList<String> derivedFrom = null; if (derived != null) { - derivedFrom = new ArrayList<String>(); + derivedFrom = new ArrayList<>(); derivedFrom.add(derived.normativeName); } String vendorName = "ATT Tosca"; @@ -310,7 +308,7 @@ public class ElementFactory { public static ServiceReqDetails getDefaultService(String serviceName, ServiceCategoriesEnum category, String contactId) { serviceName = (serviceName + generateUUIDforSufix()); - ArrayList<String> tags = new ArrayList<String>(); + ArrayList<String> tags = new ArrayList<>(); tags.add("serviceTag"); tags.add("serviceTag1"); tags.add(serviceName); @@ -965,12 +963,12 @@ public class ElementFactory { ProductReqDetails product = new ProductReqDetails(productName); productName = (productName + generateUUIDforSufix()); product.setName(productName); - ArrayList<String> tags = new ArrayList<String>(); + ArrayList<String> tags = new ArrayList<>(); tags.add(productName); product.setTags(tags); product.setProjectCode("12345"); product.setIcon("myIcon"); - ArrayList<String> contacts = new ArrayList<String>(); + ArrayList<String> contacts = new ArrayList<>(); // contacts.add(ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_STRATEGIST1).getUserId()); // contacts.add(ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_STRATEGIST2).getUserId()); contacts.add(ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_MANAGER1).getUserId()); diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/FileHandling.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/FileHandling.java index 9759653af2..7af18dd3b7 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/FileHandling.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/FileHandling.java @@ -20,6 +20,7 @@ package org.openecomp.sdc.ci.tests.utils.general; +import com.aventstack.extentreports.Status; import static org.testng.AssertJUnit.assertTrue; import java.io.BufferedOutputStream; @@ -51,6 +52,15 @@ import org.openecomp.sdc.common.util.GeneralUtility; import org.yaml.snakeyaml.Yaml; import com.aventstack.extentreports.Status; +import java.io.*; +import java.nio.file.Paths; +import java.util.*; +import java.util.zip.ZipEntry; +import java.util.zip.ZipException; +import java.util.zip.ZipFile; +import java.util.zip.ZipInputStream; + +import static org.testng.AssertJUnit.assertTrue; public class FileHandling { @@ -94,7 +104,6 @@ public class FileHandling { return dataTypesMap; } // ------------------------------------------------------------------------------------------------- - /** * @param folder, folder name under "Files" folder @@ -154,7 +163,7 @@ public class FileHandling { public static String getVnfRepositoryPath() { return getFilePath("VNFs"); } - + public static String getPortMirroringRepositoryPath() { return getFilePath("PortMirroring"); } diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/FileUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/FileUtils.java index 28964e2f7e..f0ca9dd517 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/FileUtils.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/FileUtils.java @@ -104,8 +104,7 @@ public class FileUtils { return loadPayloadFile(newList, pattern, isBase64); } - public static String loadPayloadFile(List<String> listFileName, String pattern, Boolean isBase64) - throws IOException { + public static String loadPayloadFile(List<String> listFileName, String pattern, Boolean isBase64) throws IOException { String fileName; String payload = null; fileName = FileUtils.getFilePathFromListByPattern(listFileName, pattern); diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/OnboardingUtillViaApis.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/OnboardingUtillViaApis.java index 76e4c51b3f..8637a9ba7a 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/OnboardingUtillViaApis.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/OnboardingUtillViaApis.java @@ -30,15 +30,17 @@ import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; -import java.util.HashMap; import java.util.List; import java.util.Map; +import com.aventstack.extentreports.Status; +import com.clearspring.analytics.util.Pair; +import com.google.gson.Gson; +import fj.data.Either; import org.apache.commons.codec.binary.Base64; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.ci.tests.api.ExtentTestActions; import org.openecomp.sdc.ci.tests.api.Urls; import org.openecomp.sdc.ci.tests.config.Config; import org.openecomp.sdc.ci.tests.datatypes.AmdocsLicenseMembers; @@ -53,7 +55,6 @@ import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; import org.openecomp.sdc.ci.tests.utils.Utils; import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils; -import com.aventstack.extentreports.Status; import com.clearspring.analytics.util.Pair; import com.google.gson.Gson; @@ -61,28 +62,28 @@ import fj.data.Either; public class OnboardingUtillViaApis { - protected static Map<String, String> prepareHeadersMap(String userId) { - 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(), userId); - return headersMap; - } - +// protected static Map<String, String> prepareHeadersMap(String userId) { +// 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(), userId); +// return headersMap; +// } + public static Pair<String, VendorSoftwareProductObject> createVspViaApis(ResourceReqDetails resourceReqDetails, String filepath, String vnfFile, User user) throws Exception { VendorSoftwareProductObject vendorSoftwareProductObject = new VendorSoftwareProductObject(); - ExtentTestActions.log(Status.INFO, String.format("Create Vendor License")); - AmdocsLicenseMembers amdocsLicenseMembers = OnboardingUtils.createVendorLicense(user); - Pair<String, Map<String, String>> createVendorSoftwareProduct = OnboardingUtils.createVendorSoftwareProduct(resourceReqDetails, vnfFile, filepath, user, amdocsLicenseMembers); - Map<String, String> map = createVendorSoftwareProduct.right; - vendorSoftwareProductObject.setAttContact(map.get("attContact")); - vendorSoftwareProductObject.setCategory(map.get("category")); - vendorSoftwareProductObject.setComponentId(map.get("componentId")); - vendorSoftwareProductObject.setDescription(map.get("description")); - vendorSoftwareProductObject.setSubCategory(map.get("subCategory")); - vendorSoftwareProductObject.setVendorName(map.get("vendorName")); - vendorSoftwareProductObject.setVspId(map.get("vspId")); + + AmdocsLicenseMembers amdocsLicenseMembers = VendorLicenseModelRestUtils.createVendorLicense(user); + Pair<String, VendorSoftwareProductObject> createVendorSoftwareProduct = VendorSoftwareProductRestUtils.createVendorSoftwareProduct(resourceReqDetails, vnfFile, filepath, user, amdocsLicenseMembers); + VendorSoftwareProductObject map = createVendorSoftwareProduct.right; + vendorSoftwareProductObject.setAttContact(map.getAttContact()); + vendorSoftwareProductObject.setCategory(map.getCategory()); + vendorSoftwareProductObject.setComponentId(map.getComponentId()); + vendorSoftwareProductObject.setDescription(map.getDescription()); + vendorSoftwareProductObject.setSubCategory(map.getSubCategory()); + vendorSoftwareProductObject.setVendorName(map.getVendorName()); + vendorSoftwareProductObject.setVspId(map.getVspId()); Pair<String, VendorSoftwareProductObject> pair = new Pair<String, VendorSoftwareProductObject>(createVendorSoftwareProduct.left, vendorSoftwareProductObject); return pair; } @@ -109,18 +110,18 @@ public class OnboardingUtillViaApis { return resource; }*/ - - public static Resource createResourceFromVSP(ResourceReqDetails resourceDetails, UserRoleEnum user) throws Exception { - Resource resource = AtomicOperationUtils.createResourceByResourceDetails(resourceDetails, user, true).left().value(); - - return resource; - } - public static Resource createResourceFromVSP(ResourceReqDetails resourceDetails) throws Exception { Resource resource = AtomicOperationUtils.createResourceByResourceDetails(resourceDetails, UserRoleEnum.DESIGNER, true).left().value(); - return resource; + } + + public static Resource createResourceFromVSP(ResourceReqDetails resourceDetails, UserRoleEnum userRole) throws Exception { + Resource resource = AtomicOperationUtils.createResourceByResourceDetails(resourceDetails, userRole, true).left().value(); + return resource; + + } + public static void downloadToscaCsarToDirectory(Component component, File file) { try { Either<String, RestResponse> componentToscaArtifactPayload = AtomicOperationUtils.getComponenetArtifactPayload(component, "assettoscacsar"); @@ -236,7 +237,7 @@ public class OnboardingUtillViaApis { Config config = Utils.getConfig(); String url = String.format(Urls.GET_VENDOR_SOFTWARE_PRODUCT, config.getCatalogBeHost(), config.getCatalogBePort(), vspId); String userId = user.getUserId(); - Map<String, String> headersMap = prepareHeadersMap(userId); + Map<String, String> headersMap = OnboardingUtils.prepareHeadersMap(userId); headersMap.put(HttpHeaderEnum.X_ECOMP_REQUEST_ID_HEADER.getValue(), "123456"); headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "*/*"); headersMap.put("Accept-Encoding", "gzip, deflate, br"); diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/OnboardingUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/OnboardingUtils.java index dc38d40064..c1950dfd08 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/OnboardingUtils.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/OnboardingUtils.java @@ -20,268 +20,98 @@ package org.openecomp.sdc.ci.tests.utils.general; -import static org.testng.AssertJUnit.assertEquals; - -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.util.Arrays; +import java.util.Calendar; import java.util.HashMap; -import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.UUID; -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.mime.MultipartEntityBuilder; -import org.apache.http.entity.mime.content.FileBody; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.json.JSONException; -import org.json.JSONObject; -import org.json.simple.JSONArray; -import org.json.simple.JSONValue; import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.ci.tests.api.ComponentBaseTest; import org.openecomp.sdc.ci.tests.api.Urls; import org.openecomp.sdc.ci.tests.config.Config; -import org.openecomp.sdc.ci.tests.datatypes.AmdocsLicenseMembers; -import org.openecomp.sdc.ci.tests.datatypes.LicensingData; -import org.openecomp.sdc.ci.tests.datatypes.LicensingVersion; -import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; -import org.openecomp.sdc.ci.tests.datatypes.VendorSoftwareProductObject; -import org.openecomp.sdc.ci.tests.datatypes.VendorSoftwareProductObjectReqDetails; -import org.openecomp.sdc.ci.tests.datatypes.enums.CvfcTypeEnum; -import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum; 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.rest.BaseRestUtils; -import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser; -import com.aventstack.extentreports.Status; -import com.clearspring.analytics.util.Pair; -import com.google.gson.Gson; +import java.util.*; public class OnboardingUtils { /** * excluded VNF file list */ - protected static List<String> exludeVnfList = -// new ArrayList<String>(); - - Arrays.asList( - -// new VNFs - "Vhss-epc-rdm3-lab-vf-0921-v2.0-MOBILITY-10-20.zip", "Apndns-1710-vf-v3.0-10-20.zip", - "HeatCandidate_2017-09-22_01-48_55Name_2016-182-asbg-nsbg-tsbg-v1.0-(VOIP).zip", "HeatCandidate_2017-09-22_01-47_55Name_2016-182-asbg-nsbg-tsbg-v7.0-(VOIP).zip", - "Efmc-dbe-nin-v24.0-VOIP-10-20.zip", "VF_LMSP_v5-062317-V3.0-(Mobility).zip", "base_bwks_nfm_volume-236262502.zip", - -// newest failed VNFs - "HeatCandidate_2017-09-20_15-07_66Name_2016-20-visbc1vf-v4.0-(VOIP).zip", - "HeatCandidate_2017-09-20_15-06_66Name_2016-20-visbc1vf-v6.0-(VOIP).zip", "1-Vf-zrdm5bpxtc02-092017-(MOBILITY)_v3.0.zip", - "1-2017-491-4vshaken-HTTP-CM-vf-(VOIP)_v2.0.zip" - - ); + public static List<String> exludeVnfList = +// new ArrayList<>(); + Arrays.asList( +// DUPLICATE_RESOURCE_ID_IN_DIFFERENT_FILES: + "2017-376_vMOG_11_1.zip", + "HeatCandidate_2017-09-20_15-06_66Name_2016-20-visbc1vf-v6.0-(VOIP).zip", + "1 Apndns-1710-vf v3.0.zip", + "1 AVPN_vRE_BV_volume-V2.zip", + "1-Vf-zrdm5bpxtc02-092017-(MOBILITY)_v3.0.zip", + "1-Mobility_vprobe_fe_11_2_1_vf_(MOBILITY)_v1.0.zip", +// ORCHESTRATION_NOT_FOUND: + "1-2017-491-4vshaken-HTTP-CM-vf-(VOIP)_v2.0.zip", +// did not succeed to create package of new VSP expected:<200> but was:<500>: + "1-Riverbed-WANx1710VFv_v2.0.zip", + "1-LMSP_v5-062317_v3.0.zip", + "1-VF-Cisco-vCSR-1710_v2.0.zip", + "1-mDNS-preload_1710-0914_v3.0.zip", + "1-Firewall_170_Pala_Aloto_VF_v2.0.zip", + "2-mDNS-preload-1710-0914_v3.1VF.zip", + "1-2016-233_xsp_bfsa_nin2-vf-V1.0-VOIP-10-20.zip", +// did not succeed to submit new VSP expected:<200> but was:<417> + "1-VF_vEPDG_v4.0.zip", + "1-VF-2017-491_9vShaken-F5-LB_v1.0.zip", + "2-2016-73_Mow-AVPN-vpe-BV-L_v1.0.zip", + "VF-2017389vTSBCDPA2-v4.0.zip", + "1-vEPDG_V1.0(3).zip", + "1-vHSS-EPC-RDM3-Lab-VF-0830_V3.0.zip", + "2-2016-73_Mow-AVPN-vPE-BV-L_VF_V2.0_1027.zip", + "1-ADIOD_base_vPE_BV_v9.0.zip", + "Vhss-epc-rdm3-lab-vf-0921-v2.0-MOBILITY-10-20.zip", + "1-Vhss-epc-rdm3-lab-vf-0921_VF00816v2.0-MOBILITY-10-20.zip", + "1-VF-vUSP-CCF-DB-0620_v1.0base_vDB.zip", + "1-Vusp_vhss-ims_cm-repo1_V1.zip", + "1-base_vepdg_volume_v4.0.zip", + "1-Vocg_1710-2017-509(2)_v1.0.zip", + "1-2016-20-vISBC3VF_v3.0.zip", + "Apndns-1710-vf-v3.0-10-20.zip", + "1-VF-EFMC_DBE_Nin_v27.0.zip", + "2-APNDNS_1710-VF_v4.0.zip", + "1-Mow_adig_vpe_bv-V3.0.zip", + "1-VF-2017-488_ADOID_vPE_v9.0.zip", + "1-MOBT_Nimbus_3_Sprint-1.zip", + "1-VF-2017-491_9vShaken-CM_v1.0.zip", + "1-VF_zrdm5bpxtc02_092017_v2.0.zip", +// Error: TOSCA yaml file %1 cannot be modeled to VF as it does not contain \u0027topology_template + "1-VF-Checkpoint_vFW-1710_v1.0.zip" + ); /** * additional files to exludeVnfList files for tosca parser tests */ protected static List<String> exludeVnfListForToscaParser = //new ArrayList<String>(); - Arrays.asList("1-Vvig-062017-(MOBILITY)_v5.1.zip", - "HeatCandidate_2017-09-22_01-43_57Name_2017389vtsbc4vf-v1.0-(VOIP).zip", - "1-Mvm-sbc-1710-092017-(MOBILITY)_v7.0.zip", - "1-2017-492-5vshaken-SIP-AS-vf-(VOIP)_v2.0.zip", - "HeatCandidate_2017-09-20_13-37_70Name_2017-491-4vshaken-HTTP-CM-vf-v1.0-(VOIP)_10202017.zip", "1-201712-488-adiod-vpe-(Layer-0-3)_v2.0.zip", - "2017-502.zip", - "1-2017-505-urlb-vhepe-(Layer-0-3)_v2.0.zip", - "2017-376_vMOG_11_1.zip", - "HeatCandidate_2017-09-22_00-55_62Name_2017-491-6vshaken-http-cm-vf-v1.0-(VOIP).zip", "HeatCandidate_2017-09-22_01-30_60Name_Vdbe-vsp-15.1x49-d50.3-v3.0-(VOIP).zip", - "HeatCandidate_2017-09-22_01-35_59Name_2017-418-afx-v1.0.zip", - "1-2017-488-adiod-vpe-(Layer-0-3)_v-5.0.zip", - "HeatCandidate_2017-09-22_01-42_57Name_2017389vtsbc4vf-v10.0-(VOIP).zip", - "HeatCandidate_2017-09-20_13-47_68Name_2017-492-5vshaken-SIP-AS-vf-v1.0-(VOIP)_10202017.zip", "1-2016-20-visbc3vf-(VOIP)_v2.1.zip", - "1-2017-404_vUSP_vCCF_AIC3.0-(VOIP)_v6.0.zip", "1-2017389vtsbc4vf-(VOIP)_v11.0.zip", - "HeatCandidate_2017-09-22_01-32_60Name_Vdbe-vsp-15.1x49-d50.3-v1.0-(VOIP).zip", "1-2017-418-afx-v1.1.zip"); + Arrays.asList( + "1-Vvig-062017-(MOBILITY)_v5.1.zip", + "1-Mvm-sbc-1710-092017-(MOBILITY)_v7.0.zip", + "1-2017-492-5vshaken-SIP-AS-vf-(VOIP)_v2.0.zip", + "1-201712-488-adiod-vpe-(Layer-0-3)_v2.0.zip", + "2017-502.zip", + "1-2017-505-urlb-vhepe-(Layer-0-3)_v2.0.zip", + "2017-376_vMOG_11_1.zip", + "HeatCandidate_2017-09-22_01-30_60Name_Vdbe-vsp-15.1x49-d50.3-v3.0-(VOIP).zip", + "HeatCandidate_2017-09-22_01-42_57Name_2017389vtsbc4vf-v10.0-(VOIP).zip", + "HeatCandidate_2017-09-20_13-47_68Name_2017-492-5vshaken-SIP-AS-vf-v1.0-(VOIP)_10202017.zip", + "1-2016-20-visbc3vf-(VOIP)_v2.1.zip", + "1-2017-404_vUSP_vCCF_AIC3.0-(VOIP)_v6.0.zip", + "1-2017389vtsbc4vf-(VOIP)_v11.0.zip" + ); - public OnboardingUtils() { - } - - public static Pair<String, Map<String, String>> createVendorSoftwareProduct(ResourceReqDetails resourceReqDetails, String heatFileName, String filepath, User user, AmdocsLicenseMembers amdocsLicenseMembers, Map<CvfcTypeEnum, String> cvfcArtifacts) - throws Exception { - - Pair<String, Map<String, String>> pair = createVSP(resourceReqDetails, heatFileName, filepath, user, amdocsLicenseMembers); - String vspid = pair.right.get("vspId"); - if(cvfcArtifacts != null && ! cvfcArtifacts.isEmpty()){ - OnboardingUtils.addCvfcArtifacts(cvfcArtifacts, vspid, user, null); - - } - prepareVspForUse(user, vspid, "0.1"); - return pair; - } - - public static Pair<String, Map<String, String>> createVendorSoftwareProduct(ResourceReqDetails resourceReqDetails, String heatFileName, String filepath, User user, AmdocsLicenseMembers amdocsLicenseMembers) - throws Exception { - - Map<CvfcTypeEnum, String> cvfcArtifacts = new HashMap<>(); - return createVendorSoftwareProduct(resourceReqDetails, heatFileName, filepath, user, amdocsLicenseMembers, cvfcArtifacts); - } - -// duplicate function - public static void prepareVspForUse(User user, String vspid, String vspVersion) throws Exception { - - RestResponse checkin = OnboardingUtils.checkinVendorSoftwareProduct(vspid, user, vspVersion); - assertEquals("did not succeed to checking new VSP", 200, checkin.getErrorCode().intValue()); - - RestResponse submit = OnboardingUtils.submitVendorSoftwareProduct(vspid, user, vspVersion); - assertEquals("did not succeed to submit new VSP", 200, submit.getErrorCode().intValue()); - - RestResponse createPackage = OnboardingUtils.createPackageOfVendorSoftwareProduct(vspid, user, vspVersion); - assertEquals("did not succeed to create package of new VSP ", 200, createPackage.getErrorCode().intValue()); - -// ComponentBaseTest.getExtendTest().log(Status.INFO, "Succeeded in creating the vendor software product"); - } - - public static VendorSoftwareProductObject createAndFillVendorSoftwareProduct(ResourceReqDetails resourceReqDetails, String heatFileName, String filePath, User user, AmdocsLicenseMembers amdocsLicenseMembers, Map<CvfcTypeEnum, String> cvfcArtifacts) - throws Exception { - - Pair<String, Map<String, String>> createVendorSoftwareProduct = OnboardingUtils.createVendorSoftwareProduct(resourceReqDetails, heatFileName, filePath, user, amdocsLicenseMembers, cvfcArtifacts); - VendorSoftwareProductObject vendorSoftwareProductObject = fillVendorSoftwareProductObjectWithMetaData(heatFileName, createVendorSoftwareProduct); - return vendorSoftwareProductObject; - - } - - public static void updateVendorLicense(AmdocsLicenseMembers amdocsLicenseMembers, User user, String vlmVersion) throws Exception { - - RestResponse checkoutVendorLicense = checkoutVendorLicense(amdocsLicenseMembers.getVendorId(), user, vlmVersion); - assertEquals("did not succeed to checkout vendor license", 200, checkoutVendorLicense.getErrorCode().intValue()); - - RestResponse checkinVendorLicense = checkinVendorLicense(amdocsLicenseMembers.getVendorId(), user, vlmVersion); - assertEquals("did not succeed to checkin vendor license", 200, checkinVendorLicense.getErrorCode().intValue()); - - RestResponse submitVendorLicense = submitVendorLicense(amdocsLicenseMembers.getVendorId(), user, vlmVersion); - assertEquals("did not succeed to submit vendor license", 200, submitVendorLicense.getErrorCode().intValue()); - - if(ComponentBaseTest.getExtendTest() != null){ - ComponentBaseTest.getExtendTest().log(Status.INFO, "Succeeded in updating the vendor license"); - } - } - - public static Pair<String, Map<String, String>> createVSP(ResourceReqDetails resourceReqDetails, String heatFileName, String filepath, User user, AmdocsLicenseMembers amdocsLicenseMembers) throws Exception { - String vspName = handleFilename(heatFileName); - - if(ComponentBaseTest.getExtendTest() != null){ - ComponentBaseTest.getExtendTest().log(Status.INFO, "Starting to create the vendor software product"); - } - - Pair<RestResponse, Map<String, String>> createNewVspPair = createNewVendorSoftwareProduct(resourceReqDetails, vspName, amdocsLicenseMembers, user); - RestResponse createNewVendorSoftwareProduct = createNewVspPair.left; - assertEquals("did not succeed to create new VSP", 200,createNewVendorSoftwareProduct.getErrorCode().intValue()); - String vspid = ResponseParser.getValueFromJsonResponse(createNewVendorSoftwareProduct.getResponse(), "vspId"); - String componentId = ResponseParser.getValueFromJsonResponse(createNewVendorSoftwareProduct.getResponse(), "componentId"); - - Map<String, String> vspMeta = createNewVspPair.right; - Map<String, String> vspObject = new HashMap<String, String>(); - Iterator<String> iterator = vspMeta.keySet().iterator(); - while(iterator.hasNext()){ - Object key = iterator.next(); - Object value = vspMeta.get(key); - vspObject.put(key.toString(), value.toString()); - } - vspObject.put("vspId", vspid); - vspObject.put("componentId", componentId); - vspObject.put("vendorName", amdocsLicenseMembers.getVendorLicenseName()); - vspObject.put("attContact", user.getUserId()); - - RestResponse uploadHeatPackage = uploadHeatPackage(filepath, heatFileName, vspid, user, "0.1"); - assertEquals("did not succeed to upload HEAT package", 200, uploadHeatPackage.getErrorCode().intValue()); - - RestResponse validateUpload = validateUpload(vspid, user, "0.1"); - assertEquals("did not succeed to validate upload process, reason: " + validateUpload.getResponse(), 200, validateUpload.getErrorCode().intValue()); - - Pair<String, Map<String, String>> pair = new Pair<String, Map<String, String>>(vspName, vspObject); - - return pair; - } - - public static void updateVspWithVfcArtifacts(String filepath, String vspId, String updatedSnmpPoll, String updatedSnmpTrap, String componentId, User user, String vspVersion) throws Exception{ - RestResponse checkout = checkoutVendorSoftwareProduct(vspId, user, vspVersion); - assertEquals("did not succeed to checkout new VSP", 200, checkout.getErrorCode().intValue()); -// ExtentTestActions.log(Status.INFO, "Deleting SNMP POLL"); - deleteArtifactByType(componentId, vspId, user, CvfcTypeEnum.SNMP_POLL); -// ExtentTestActions.log(Status.INFO, "Deleting SNMP TRAP"); - deleteArtifactByType(componentId, vspId, user, CvfcTypeEnum.SNMP_TRAP); - addVFCArtifacts(filepath, updatedSnmpPoll, updatedSnmpTrap, vspId, user, componentId); - prepareVspForUse(user, vspId, vspVersion); - } - - private static RestResponse deleteArtifactByType(String componentId, String vspId, User user, CvfcTypeEnum snmpType) throws Exception - { - Config config = Utils.getConfig(); - String url = String.format(Urls.DELETE_AMDOCS_ARTIFACT_BY_TYPE, config.getCatalogBeHost(),config.getCatalogBePort(), vspId, componentId, snmpType.getValue()); - String userId = user.getUserId(); - Map<String, String> headersMap = prepareHeadersMap(userId); - - HttpRequest http = new HttpRequest(); - RestResponse response = http.httpSendDelete(url, headersMap); - return response; - } - -// duplicated method - public static String updateVendorSoftwareProduct(String vspId, String HeatFileName, String filepath, User user, String vspVersion) - throws Exception, Throwable { - String vspName = OnboardingUtils.handleFilename(HeatFileName); - ComponentBaseTest.getExtendTest().log(Status.INFO, "Starting to update the vendor software product"); - - RestResponse checkout = OnboardingUtils.checkoutVendorSoftwareProduct(vspId, user, vspVersion); - assertEquals("did not succeed to checkout new VSP", 200, checkout.getErrorCode().intValue()); - - RestResponse uploadHeatPackage = OnboardingUtils.uploadHeatPackage(filepath, HeatFileName, vspId, user, vspVersion); - assertEquals("did not succeed to upload HEAT package", 200, uploadHeatPackage.getErrorCode().intValue()); - - RestResponse validateUpload = OnboardingUtils.validateUpload(vspId, user, vspVersion); - assertEquals("did not succeed to validate upload process", 200, validateUpload.getErrorCode().intValue()); - - RestResponse checkin = OnboardingUtils.checkinVendorSoftwareProduct(vspId, user, vspVersion); - assertEquals("did not succeed to checking VSP", 200, checkin.getErrorCode().intValue()); - - RestResponse submit = OnboardingUtils.submitVendorSoftwareProduct(vspId, user, vspVersion); - assertEquals("did not succeed to submit VSP", 200, submit.getErrorCode().intValue()); - - RestResponse createPackage = OnboardingUtils.createPackageOfVendorSoftwareProduct(vspId, user, vspVersion); - assertEquals("did not succeed to update package of VSP ", 200, createPackage.getErrorCode().intValue()); - - ComponentBaseTest.getExtendTest().log(Status.INFO, "Succeeded in updating the vendor software product"); - - return vspName; - } - - public static void updateVendorSoftwareProductToNextVersion(VendorSoftwareProductObject vendorSoftwareProductObject, String toVspVersion, User user) - throws Exception, Throwable { - - RestResponse checkout = checkoutVendorSoftwareProduct(vendorSoftwareProductObject.getVspId(), user, vendorSoftwareProductObject.getVersion()); - assertEquals("did not succeed to checkout new VSP", 200, checkout.getErrorCode().intValue()); - - RestResponse checkin = checkinVendorSoftwareProduct(vendorSoftwareProductObject.getVspId(), user, vendorSoftwareProductObject.getVersion()); - assertEquals("did not succeed to checking VSP", 200, checkin.getErrorCode().intValue()); - - RestResponse submit = submitVendorSoftwareProduct(vendorSoftwareProductObject.getVspId(), user, vendorSoftwareProductObject.getVersion()); - assertEquals("did not succeed to submit VSP", 200, submit.getErrorCode().intValue()); - - vendorSoftwareProductObject.setVersion(toVspVersion); - } - public static String handleFilename(String heatFileName) { - final String namePrefix = "ciVFOnboarded-"; + final String namePrefix = String.format("%sVF%s", ElementFactory.getResourcePrefix(), "Onboarded-"); final String nameSuffix = "-" + getShortUUID(); String subHeatFileName = heatFileName.substring(0, heatFileName.lastIndexOf(".")); @@ -299,498 +129,22 @@ public class OnboardingUtils { return vnfName; } - public static String addVFCArtifacts(String filepath, String snmpPoll, String snmpTrap, String vspid, User user, String vspComponentId) throws Exception{ - vspComponentId = (vspComponentId == null) ? getVSPComponentId(vspid, user) : vspComponentId; - if (vspComponentId != null){ - if (snmpPoll != null){ -// ExtentTestActions.log(Status.INFO, "Adding VFC artifact of type SNMP POLL with the file " + snmpPoll); - RestResponse uploadSnmpPollArtifact = uploadSnmpPollArtifact(filepath, snmpPoll, vspid, user, vspComponentId); - assertEquals("Did not succeed to add SNMP POLL", 200, uploadSnmpPollArtifact.getErrorCode().intValue()); - } - if (snmpTrap != null){ -// ExtentTestActions.log(Status.INFO, "Adding VFC artifact of type SNMP TRAP with the file " + snmpTrap); - RestResponse uploadSnmpTrapArtifact = uploadSnmpTrapArtifact(filepath, snmpTrap, vspid, user, vspComponentId); - assertEquals("Did not succeed to add SNMP TRAP", 200, uploadSnmpTrapArtifact.getErrorCode().intValue()); - } - } - - return vspComponentId; - } - - public static String addCvfcArtifacts(Map<CvfcTypeEnum, String> componentVfcArtifacts, String vspid, User user, String vspComponentId) throws Exception{ - vspComponentId = (vspComponentId == null) ? getVSPComponentId(vspid, user) : vspComponentId; - if (vspComponentId != null){ - for(Map.Entry<CvfcTypeEnum, String> entry : componentVfcArtifacts.entrySet()){ -// ExtentTestActions.log(Status.INFO, "Adding VFC artifact of type " + entry.getKey().getValue() + " with the file " + entry.getValue()); - RestResponse uploadSnmpPollArtifact = uploadCvfcArtifact(entry.getValue(), entry.getKey().getValue(), vspid, user, vspComponentId); - assertEquals("Did not succeed to add " + entry.getKey().getValue(), BaseRestUtils.STATUS_CODE_SUCCESS, uploadSnmpPollArtifact.getErrorCode().intValue()); - } - } - return vspComponentId; - } - - public static String addVFCArtifacts(String filepath, String snmpPoll, String snmpTrap, String vspid, User user) throws Exception{ - return addVFCArtifacts(filepath, snmpPoll, snmpTrap, vspid, user, null); - } - - public static RestResponse uploadCvfcArtifact(String filepath, String cvfcType, String vspid, User user, String vspComponentId) throws FileNotFoundException, IOException, ClientProtocolException { - Config config = Utils.getConfig(); - String snmpPollUrl = String.format(Urls.UPLOAD_AMDOCS_ARTIFACT, config.getCatalogBeHost(),config.getCatalogBePort(), vspid, vspComponentId, cvfcType); - return uploadFile(filepath, null, snmpPollUrl, user); - } - - - private static RestResponse uploadSnmpPollArtifact(String filepath, String zipArtifact, String vspid, User user, - String vspComponentId) throws FileNotFoundException, IOException, ClientProtocolException { - Config config = Utils.getConfig(); - String snmpPollUrl = String.format(Urls.UPLOAD_SNMP_POLL_ARTIFACT, config.getCatalogBeHost(),config.getCatalogBePort(), vspid, vspComponentId); - return uploadFile(filepath, zipArtifact, snmpPollUrl, user); - } - - private static RestResponse uploadSnmpTrapArtifact(String filepath, String zipArtifact, String vspid, User user, - String vspComponentId) throws FileNotFoundException, IOException, ClientProtocolException { - Config config = Utils.getConfig(); - String snmpTrapUrl = String.format(Urls.UPLOAD_SNMP_POLL_ARTIFACT, config.getCatalogBeHost(),config.getCatalogBePort(), vspid, vspComponentId); - return uploadFile(filepath, zipArtifact, snmpTrapUrl, user); - } - - private static RestResponse deleteSnmpArtifact(String componentId, String vspId, User user, SnmpTypeEnum snmpType) throws Exception - { - Config config = Utils.getConfig(); - String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-software-products/%s/versions/0.1/components/%s/monitors/%s", - config.getCatalogBeHost(),config.getCatalogBePort(), vspId, componentId, snmpType.getValue()); - String userId = user.getUserId(); - - Map<String, String> headersMap = prepareHeadersMap(userId); - - HttpRequest http = new HttpRequest(); - RestResponse response = http.httpSendDelete(url, headersMap); - return response; - } - - private static String getVSPComponentId(String vspid, User user) throws Exception, JSONException { - RestResponse components = getVSPComponents(vspid, user); - String response = components.getResponse(); - Map<String, Object> responseMap = (Map<String, Object>) JSONValue.parse(response); - JSONArray results = (JSONArray)responseMap.get("results"); - for (Object res : results){ - Map<String, Object> compMap= (Map<String, Object>) JSONValue.parse(res.toString()); - String componentId = compMap.get("id").toString(); - return componentId; - } - return null; - } - - private static RestResponse getVSPComponents(String vspid, User user) throws Exception{ - Config config = Utils.getConfig(); - String url = String.format(Urls.GET_VSP_COMPONENTS, config.getCatalogBeHost(),config.getCatalogBePort(), vspid); - String userId = user.getUserId(); - - Map<String, String> headersMap = prepareHeadersMap(userId); - - HttpRequest http = new HttpRequest(); - RestResponse response = http.httpSendGet(url, headersMap); - return response; - } - - private static RestResponse getVLMComponentByVersion(String vlmId, String vlmVersion, User user) throws Exception{ - Config config = Utils.getConfig(); - String url = String.format(Urls.GET_VLM_COMPONENT_BY_VERSION, config.getCatalogBeHost(),config.getCatalogBePort(), vlmId,vlmVersion); - String userId = user.getUserId(); - - Map<String, String> headersMap = prepareHeadersMap(userId); - - HttpRequest http = new HttpRequest(); - RestResponse response = http.httpSendGet(url, headersMap); - return response; - } - - public static boolean validateVspExist(String vspId, String vspVersion, User user) throws Exception { - RestResponse restResponse = getVSPComponentByVersion(vspId, vspVersion, user); - assertEquals(String.format("Vsp version not updated, reponse message: %s", restResponse.getResponse()),restResponse.getErrorCode().intValue(),200); - return (restResponse.getErrorCode()==200); - } - - public static boolean validateVlmExist(String vlmId, String vlmVersion, User user) throws Exception { - RestResponse restResponse = getVLMComponentByVersion(vlmId, vlmVersion, user); - assertEquals(String.format("VLM version not updated, reponse code message: %s", restResponse.getResponse()),restResponse.getErrorCode().intValue(),200); - return (restResponse.getErrorCode()==200); - } - - - private static RestResponse getVSPComponentByVersion(String vspId, String vspVersion, User user) throws Exception{ - Config config = Utils.getConfig(); - String url = String.format(Urls.GET_VSP_COMPONENT_BY_VERSION, config.getCatalogBeHost(),config.getCatalogBePort(), vspId,vspVersion); - String userId = user.getUserId(); - - Map<String, String> headersMap = prepareHeadersMap(userId); - - HttpRequest http = new HttpRequest(); - RestResponse response = http.httpSendGet(url, headersMap); - return response; - } - -// Duplicate method - public static AmdocsLicenseMembers createVendorLicense(User user) throws Exception { - - AmdocsLicenseMembers amdocsLicenseMembers; -// ComponentBaseTest.getExtendTest().log(Status.INFO, "Starting to create the vendor license"); - String vendorLicenseName = "ciLicense" + OnboardingUtils.getShortUUID(); - RestResponse vendorLicenseResponse = OnboardingUtils.createVendorLicenseModels_1(vendorLicenseName, user); - assertEquals("did not succeed to create vendor license model", 200, vendorLicenseResponse.getErrorCode().intValue()); - String vendorId = ResponseParser.getValueFromJsonResponse(vendorLicenseResponse.getResponse(), "value"); - - RestResponse vendorKeyGroupsResponse = OnboardingUtils.createVendorKeyGroups_2(vendorId, user); - assertEquals("did not succeed to create vendor key groups", 200, vendorKeyGroupsResponse.getErrorCode().intValue()); - String keyGroupId = ResponseParser.getValueFromJsonResponse(vendorKeyGroupsResponse.getResponse(), "value"); - - RestResponse vendorEntitlementPool = OnboardingUtils.createVendorEntitlementPool_3(vendorId, user); - assertEquals("did not succeed to create vendor entitlement pool", 200, vendorEntitlementPool.getErrorCode().intValue()); - String entitlementPoolId = ResponseParser.getValueFromJsonResponse(vendorEntitlementPool.getResponse(), "value"); - - RestResponse vendorLicenseFeatureGroups = OnboardingUtils.createVendorLicenseFeatureGroups_4(vendorId, keyGroupId, entitlementPoolId, user); - assertEquals("did not succeed to create vendor license feature groups", 200, vendorLicenseFeatureGroups.getErrorCode().intValue()); - String featureGroupId = ResponseParser.getValueFromJsonResponse(vendorLicenseFeatureGroups.getResponse(), "value"); - - RestResponse vendorLicenseAgreement = OnboardingUtils.createVendorLicenseAgreement_5(vendorId, featureGroupId, user); - assertEquals("did not succeed to create vendor license agreement", 200, vendorLicenseAgreement.getErrorCode().intValue()); - String vendorLicenseAgreementId = ResponseParser.getValueFromJsonResponse(vendorLicenseAgreement.getResponse(), "value"); - - RestResponse checkinVendorLicense = OnboardingUtils.checkinVendorLicense(vendorId, user, "0.1"); - assertEquals("did not succeed to checkin vendor license", 200, checkinVendorLicense.getErrorCode().intValue()); - - RestResponse submitVendorLicense = OnboardingUtils.submitVendorLicense(vendorId, user, "0.1"); - assertEquals("did not succeed to submit vendor license", 200, submitVendorLicense.getErrorCode().intValue()); - -// ComponentBaseTest.getExtendTest().log(Status.INFO, "Succeeded in creating the vendor license"); - - amdocsLicenseMembers = new AmdocsLicenseMembers(vendorId, vendorLicenseName, vendorLicenseAgreementId, featureGroupId); - amdocsLicenseMembers.setVersion("1.0"); // Once object created and submitted, his initial version is 1.0 - - return amdocsLicenseMembers; - } public static String getShortUUID() { return UUID.randomUUID().toString().split("-")[0]; } - private static RestResponse actionOnComponent(String vspid, String action, String onboardComponent, User user, String componentVersion) - throws Exception { + private static RestResponse actionOnComponent(String vspid, String body, String onboardComponent, User user, String componentVersion) throws Exception { Config config = Utils.getConfig(); String url = String.format(Urls.ACTION_ON_COMPONENT, config.getCatalogBeHost(), config.getCatalogBePort(), onboardComponent, vspid, componentVersion); String userId = user.getUserId(); - - JSONObject jObject = new JSONObject(); - jObject.put("action", action); - - Map<String, String> headersMap = prepareHeadersMap(userId); - - HttpRequest http = new HttpRequest(); - RestResponse response = http.httpSendPut(url, jObject.toString(), headersMap); - return response; - } - - - public static RestResponse checkinVendorLicense(String vspid, User user, String vlmVersion) throws Exception { - return actionOnComponent(vspid, "Checkin", "vendor-license-models", user, vlmVersion); - } - - public static RestResponse checkoutVendorLicense(String vspid, User user, String vlmVersion) throws Exception { - return actionOnComponent(vspid, "Checkout", "vendor-license-models", user, vlmVersion); - } - - public static RestResponse submitVendorLicense(String vspid, User user, String vlmVersion) throws Exception { - return actionOnComponent(vspid, "Submit", "vendor-license-models", user, vlmVersion); - } - - public static RestResponse createVendorLicenseModels_1(String name, User user) throws Exception { - Config config = Utils.getConfig(); - String url = String.format(Urls.CREATE_VENDOR_LISENCE_MODELS, config.getCatalogBeHost(), - config.getCatalogBePort()); - String userId = user.getUserId(); - - JSONObject jObject = new JSONObject(); - jObject.put("vendorName", name); - jObject.put("description", "new vendor license model"); - jObject.put("iconRef", "icon"); - - Map<String, String> headersMap = prepareHeadersMap(userId); - - HttpRequest http = new HttpRequest(); - RestResponse response = http.httpSendPost(url, jObject.toString(), headersMap); - return response; - - } - - public static RestResponse createVendorLicenseAgreement_5(String vspid, String featureGroupId, User user) - throws Exception { - Config config = Utils.getConfig(); - String url = String.format(Urls.CREATE_VENDOR_LISENCE_AGREEMENT, config.getCatalogBeHost(), config.getCatalogBePort(), vspid); - String userId = user.getUserId(); - - JSONObject licenseTermpObject = new JSONObject(); - licenseTermpObject.put("choice", "Fixed_Term"); - licenseTermpObject.put("other", ""); - - JSONObject jObjectBody = new JSONObject(); - jObjectBody.put("name", "abc"); - jObjectBody.put("description", "new vendor license agreement"); - jObjectBody.put("requirementsAndConstrains", "abc"); - jObjectBody.put("licenseTerm", licenseTermpObject); - jObjectBody.put("addedFeatureGroupsIds", Arrays.asList(featureGroupId).toArray()); - - Map<String, String> headersMap = prepareHeadersMap(userId); - - HttpRequest http = new HttpRequest(); - RestResponse response = http.httpSendPost(url, jObjectBody.toString(), headersMap); - return response; - } - - public static RestResponse createVendorLicenseFeatureGroups_4(String vspid, String licenseKeyGroupId, - String entitlementPoolId, User user) throws Exception { - Config config = Utils.getConfig(); - String url = String.format(Urls.CREATE_VENDOR_LISENCE_FEATURE_GROUPS, config.getCatalogBeHost(), config.getCatalogBePort(), vspid); - String userId = user.getUserId(); - - JSONObject jObject = new JSONObject(); - jObject.put("name", "xyz"); - jObject.put("description", "new vendor license feature groups"); - jObject.put("partNumber", "123abc456"); - jObject.put("manufacturerReferenceNumber", "5"); - jObject.put("addedLicenseKeyGroupsIds", Arrays.asList(licenseKeyGroupId).toArray()); - jObject.put("addedEntitlementPoolsIds", Arrays.asList(entitlementPoolId).toArray()); - - Map<String, String> headersMap = prepareHeadersMap(userId); - - HttpRequest http = new HttpRequest(); - RestResponse response = http.httpSendPost(url, jObject.toString(), headersMap); - return response; - - } - - public static RestResponse createVendorEntitlementPool_3(String vspid, User user) throws Exception { - Config config = Utils.getConfig(); - String url = String.format(Urls.CREATE_VENDOR_LISENCE_ENTITLEMENT_POOL, config.getCatalogBeHost(), config.getCatalogBePort(), vspid); - String userId = user.getUserId(); - - JSONObject jEntitlementMetricObject = new JSONObject(); - jEntitlementMetricObject.put("choice", "CPU"); - jEntitlementMetricObject.put("other", ""); - - JSONObject jAggregationFunctionObject = new JSONObject(); - jAggregationFunctionObject.put("choice", "Peak"); - jAggregationFunctionObject.put("other", ""); - - JSONObject jOperationalScope = new JSONObject(); - jOperationalScope.put("choices", Arrays.asList("Availability_Zone").toArray()); - jOperationalScope.put("other", ""); - - JSONObject jTimeObject = new JSONObject(); - jTimeObject.put("choice", "Hour"); - jTimeObject.put("other", ""); - - JSONObject jObjectBody = new JSONObject(); - jObjectBody.put("name", "def"+ getShortUUID()); - jObjectBody.put("description", "new vendor license entitlement pool"); - jObjectBody.put("thresholdValue", "23"); - jObjectBody.put("thresholdUnits", "Absolute"); - jObjectBody.put("entitlementMetric", jEntitlementMetricObject); - jObjectBody.put("increments", "abcd"); - jObjectBody.put("aggregationFunction", jAggregationFunctionObject); - jObjectBody.put("operationalScope", jOperationalScope); - jObjectBody.put("time", jTimeObject); - jObjectBody.put("manufacturerReferenceNumber", "123aaa"); - - Map<String, String> headersMap = prepareHeadersMap(userId); - - HttpRequest http = new HttpRequest(); - RestResponse response = http.httpSendPost(url, jObjectBody.toString(), headersMap); - return response; - } - - public static RestResponse createVendorKeyGroups_2(String vspid, User user) throws Exception { - Config config = Utils.getConfig(); - String url = String.format(Urls.CREATE_VENDOR_LISENCE_KEY_GROUPS, config.getCatalogBeHost(), config.getCatalogBePort(), vspid); - String userId = user.getUserId(); - - JSONObject jOperationalScope = new JSONObject(); - jOperationalScope.put("choices", Arrays.asList("Tenant").toArray()); - jOperationalScope.put("other", ""); - - JSONObject jObjectBody = new JSONObject(); - jObjectBody.put("name", "keyGroup" + getShortUUID()); - jObjectBody.put("description", "new vendor license key group"); - jObjectBody.put("operationalScope", jOperationalScope); - jObjectBody.put("type", "Universal"); - Map<String, String> headersMap = prepareHeadersMap(userId); HttpRequest http = new HttpRequest(); - RestResponse response = http.httpSendPost(url, jObjectBody.toString(), headersMap); - return response; - } - - public static Pair<RestResponse, Map<String, String>> createNewVendorSoftwareProduct(ResourceReqDetails resourceReqDetails, String vspName, AmdocsLicenseMembers amdocsLicenseMembers, User user) throws Exception { - Map<String, String> vspMetadta = new HashMap<String, String>(); - - Config config = Utils.getConfig(); - String url = String.format(Urls.CREATE_VENDOR_SOFTWARE_PRODUCT, config.getCatalogBeHost(), config.getCatalogBePort()); - String userId = user.getUserId(); - VendorSoftwareProductObject vendorSoftwareProductObject = new VendorSoftwareProductObject(); - LicensingData licensingData = new LicensingData(amdocsLicenseMembers.getVendorLicenseAgreementId(), Arrays.asList(amdocsLicenseMembers.getFeatureGroupId())); - LicensingVersion licensingVersion = new LicensingVersion("1.0", "1.0"); - ResourceCategoryEnum resourceCategoryEnum = ResourceCategoryEnum.findEnumNameByValues(resourceReqDetails.getCategories().get(0).getName(), resourceReqDetails.getCategories().get(0).getSubcategories().get(0).getName()); - - vendorSoftwareProductObject.setLicensingVersion(licensingVersion); - - vendorSoftwareProductObject.setName(vspName); - vendorSoftwareProductObject.setDescription(resourceReqDetails.getDescription()); - vendorSoftwareProductObject.setCategory(resourceCategoryEnum.getCategoryUniqeId()); - vendorSoftwareProductObject.setSubCategory(resourceCategoryEnum.getSubCategoryUniqeId()); - vendorSoftwareProductObject.setOnboardingMethod("NetworkPackage"); - vendorSoftwareProductObject.setVendorName(amdocsLicenseMembers.getVendorLicenseName()); - vendorSoftwareProductObject.setVendorId(amdocsLicenseMembers.getVendorId()); - vendorSoftwareProductObject.setIcon("icon"); - vendorSoftwareProductObject.setLicensingData(licensingData); - - vspMetadta.put("description", resourceReqDetails.getDescription()); - vspMetadta.put("category", resourceCategoryEnum.getCategory()); - vspMetadta.put("subCategory", resourceCategoryEnum.getSubCategory()); - - Map<String, String> headersMap = prepareHeadersMap(userId); - HttpRequest http = new HttpRequest(); - Gson gson = new Gson(); - String body = gson.toJson(vendorSoftwareProductObject); - - RestResponse response = http.httpSendPost(url, body, headersMap); - return new Pair<RestResponse, Map<String, String>>(response, vspMetadta); - } - - public static RestResponse validateUpload(String vspid, User user, String vspVersion) throws Exception { - Config config = Utils.getConfig(); - String url = String.format(Urls.VALIDATE_UPLOAD, config.getCatalogBeHost(), config.getCatalogBePort(), vspid,vspVersion); - - String userId = user.getUserId(); - - Map<String, String> headersMap = prepareHeadersMap(userId); - HttpRequest http = new HttpRequest(); - - String body =null; - RestResponse response = http.httpSendPut(url, body, headersMap); - return response; } - public static RestResponse uploadHeatPackage(String filepath, String filename, String vspid, User user, String vspVersion) throws Exception { - Config config = Utils.getConfig(); - String url = String.format(Urls.UPLOAD_HEAT_PACKAGE, config.getCatalogBeHost(), config.getCatalogBePort(), vspid, vspVersion); - return uploadFile(filepath, filename, url, user); - } - - private static RestResponse uploadFile(String filepath, String filename, String url, User user) - throws FileNotFoundException, IOException, ClientProtocolException { - CloseableHttpResponse response = null; - - MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create(); - mpBuilder.addPart("upload", new FileBody(getTestZipFile(filepath, filename))); - - Map<String, String> headersMap = prepareHeadersMap(user.getUserId()); - headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "multipart/form-data"); - - CloseableHttpClient client = HttpClients.createDefault(); - try { - HttpPost httpPost = new HttpPost(url); - RestResponse restResponse = new RestResponse(); - - Iterator<String> iterator = headersMap.keySet().iterator(); - while (iterator.hasNext()) { - String key = iterator.next(); - String value = headersMap.get(key); - httpPost.addHeader(key, value); - } - httpPost.setEntity(mpBuilder.build()); - response = client.execute(httpPost); - HttpEntity entity = response.getEntity(); - String responseBody = null; - if (entity != null) { - InputStream instream = entity.getContent(); - try { - StringWriter writer = new StringWriter(); - IOUtils.copy(instream, writer); - responseBody = writer.toString(); - } finally { - instream.close(); - } - } - - restResponse.setErrorCode(response.getStatusLine().getStatusCode()); - restResponse.setResponse(responseBody); - - return restResponse; - - } finally { - closeResponse(response); - closeHttpClient(client); - - } - } - - private static void closeResponse(CloseableHttpResponse response) { - try { - if (response != null) { - response.close(); - } - } catch (IOException e) { - System.out.println(String.format("failed to close client or response: %s", e.getMessage())); - } - } - - private static void closeHttpClient(CloseableHttpClient client) { - try { - if (client != null) { - client.close(); - } - } catch (IOException e) { - System.out.println(String.format("failed to close client or response: %s", e.getMessage())); - } - } - -// private static File getTestZipFile(String filepath, String filename) throws IOException { -// Config config = Utils.getConfig(); -// String sourceDir = config.getImportResourceTestsConfigDir(); -// java.nio.file.Path filePath = FileSystems.getDefault().getPath(filepath + File.separator + filename); -// return filePath.toFile(); -// } - - private static File getTestZipFile(String filepath, String filename) throws IOException { - Config config = Utils.getConfig(); - String sourceDir = config.getImportResourceTestsConfigDir(); - java.nio.file.Path filePath; - if(filename == null){ - filePath = FileSystems.getDefault().getPath(filepath); - }else{ - filePath = FileSystems.getDefault().getPath(filepath + File.separator + filename); - } - return filePath.toFile(); - } - - public static RestResponse checkinVendorSoftwareProduct(String vspid, User user, String vspVersion) throws Exception { - return actionOnComponent(vspid, "Checkin", "vendor-software-products", user, vspVersion); - } - - public static RestResponse checkoutVendorSoftwareProduct(String vspid, User user, String vspVersion) throws Exception { - return actionOnComponent(vspid, "Checkout", "vendor-software-products", user, vspVersion); - } - - public static RestResponse submitVendorSoftwareProduct(String vspid, User user, String vspVersion) throws Exception { - return actionOnComponent(vspid, "Submit", "vendor-software-products", user, vspVersion); - } - - public static RestResponse createPackageOfVendorSoftwareProduct(String vspid, User user, String vspVersion) throws Exception { - return actionOnComponent(vspid, "Create_Package", "vendor-software-products", user, vspVersion); - } - protected static Map<String, String> prepareHeadersMap(String userId) { Map<String, String> headersMap = new HashMap<String, String>(); headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json"); @@ -799,193 +153,7 @@ public class OnboardingUtils { return headersMap; } - public static VendorSoftwareProductObject updateVSPWithNewVLMParameters(VendorSoftwareProductObject vendorSoftwareProductObject, - AmdocsLicenseMembers amdocsLicenseMembers, User user, String vspCurrentVersion, String vspNextVersion) throws Exception { - - LicensingVersion licensingVersion = new LicensingVersion(amdocsLicenseMembers.getLicenseVersionId(),amdocsLicenseMembers.getLicenseVersionId()); - LicensingData licensingData = new LicensingData(amdocsLicenseMembers.getVendorLicenseAgreementId(), Arrays.asList(amdocsLicenseMembers.getFeatureGroupId())); - vendorSoftwareProductObject.setVendorId(amdocsLicenseMembers.getVendorId()); - vendorSoftwareProductObject.setVendorName(amdocsLicenseMembers.getVendorLicenseName()); - vendorSoftwareProductObject.setLicensingVersion(licensingVersion); - vendorSoftwareProductObject.setLicensingData(licensingData); - - VendorSoftwareProductObjectReqDetails vendorSoftwareProductObjectReqDetails = new VendorSoftwareProductObjectReqDetails( - vendorSoftwareProductObject.getName(), - vendorSoftwareProductObject.getDescription(), - vendorSoftwareProductObject.getCategory(), - vendorSoftwareProductObject.getSubCategory(), - vendorSoftwareProductObject.getVendorId(), - vendorSoftwareProductObject.getVendorName(), - licensingVersion, - licensingData, - vendorSoftwareProductObject.getOnboardingMethod(), - vendorSoftwareProductObject.getNetworkPackageName(), - vendorSoftwareProductObject.getOnboardingOrigin()); - - Gson gson = new Gson(); - String json = gson.toJson(vendorSoftwareProductObjectReqDetails); - - RestResponse checkout = checkoutVendorSoftwareProduct(vendorSoftwareProductObject.getVspId(), user, "1.0"); - assertEquals("did not succeed to checkout new VSP", 200, checkout.getErrorCode().intValue()); - - Config config = Utils.getConfig(); - String url = String.format(Urls.UPDATE_VSP, config.getCatalogBeHost(), config.getCatalogBePort(), vendorSoftwareProductObject.getVspId(), vspCurrentVersion); - String userId = user.getUserId(); - - Map<String, String> headersMap = prepareHeadersMap(userId); - HttpRequest http = new HttpRequest(); - - RestResponse response = http.httpSendPut(url, json, headersMap); - - RestResponse checkin = checkinVendorSoftwareProduct(vendorSoftwareProductObject.getVspId(), user, vspCurrentVersion); - assertEquals("did not succeed to checking VSP", 200, checkin.getErrorCode().intValue()); - - RestResponse submit = submitVendorSoftwareProduct(vendorSoftwareProductObject.getVspId(), user, vspCurrentVersion); - assertEquals("did not succeed to submit VSP", 200, submit.getErrorCode().intValue()); - - vendorSoftwareProductObject.setVersion(vspNextVersion); - - return vendorSoftwareProductObject; - } - -// private static void importUpdateVSP(Pair<String, Map<String, String>> vsp, boolean isUpdate) throws Exception{ -// String vspName = vsp.left; -// Map<String, String> vspMetadata = vsp.right; -// boolean vspFound = HomePage.searchForVSP(vspName); -// -// if (vspFound){ -// -// List<WebElement> elemenetsFromTable = HomePage.getElemenetsFromTable(); -//// WebDriverWait wait = new WebDriverWait(GeneralUIUtils.getDriver(), 30); -//// WebElement findElement = wait.until(ExpectedConditions.visibilityOf(elemenetsFromTable.get(1))); -//// findElement.click(); -// elemenetsFromTable.get(1).click(); -// GeneralUIUtils.waitForLoader(); -// -// if (isUpdate){ -// GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ImportVfRepository.UPDATE_VSP.getValue()); -// -// } -// else{ -// GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ImportVfRepository.IMPORT_VSP.getValue()); -// } -// -// String lifeCycleState = ResourceGeneralPage.getLifeCycleState(); -// boolean needCheckout = lifeCycleState.equals(LifeCycleStateEnum.CHECKIN.getValue()) || lifeCycleState.equals(LifeCycleStateEnum.CERTIFIED.getValue()); -// if (needCheckout) -// { -// try { -// ResourceGeneralPage.clickCheckoutButton(); -// Assert.assertTrue(ResourceGeneralPage.getLifeCycleState().equals(LifeCycleStateEnum.CHECKOUT.getValue()), "Did not succeed to checkout"); -// -// } catch (Exception e) { -// ExtentTestActions.log(Status.ERROR, "Did not succeed to checkout"); -// e.printStackTrace(); -// } -// GeneralUIUtils.waitForLoader(); -// } -// -// //Metadata verification -// VfVerificator.verifyOnboardedVnfMetadata(vspName, vspMetadata); -// -// ExtentTestActions.log(Status.INFO, "Clicking create/update VNF"); -// String duration = GeneralUIUtils.getActionDuration(() -> waitUntilVnfCreated()); -// ExtentTestActions.log(Status.INFO, "Succeeded in importing/updating " + vspName, duration); -// } -// else{ -// Assert.fail("Did not find VSP named " + vspName); -// } -// } -// private static void waitUntilVnfCreated() { -// GeneralUIUtils.clickOnElementByTestIdWithoutWait(DataTestIdEnum.GeneralElementsEnum.CREATE_BUTTON.getValue()); -// GeneralUIUtils.waitForLoader(60*10); -// GeneralUIUtils.waitForAngular(); -// GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.GeneralElementsEnum.CHECKIN_BUTTON.getValue()); -// } -// -// public static void updateVSP(Pair<String, Map<String, String>> vsp) throws Exception{ -// ExtentTestActions.log(Status.INFO, "Updating VSP " + vsp.left); -// importUpdateVSP(vsp, true); -// } -// -// public static void importVSP(Pair<String, Map<String, String>> vsp) throws Exception{ -// ExtentTestActions.log(Status.INFO, "Importing VSP " + vsp.left); -// importUpdateVSP(vsp, false); -// } -// -// public static void updateVnfAndValidate(String filepath, Pair<String, Map<String, String>> vsp, String updatedVnfFile, User user) throws Exception, Throwable { -// ExtentTestActions.log(Status.INFO, String.format("Going to update the VNF with %s......", updatedVnfFile)); -// System.out.println(String.format("Going to update the VNF with %s......", updatedVnfFile)); -// -// Map<String, String> vspMap = vsp.right; -// String vspId = vspMap.get("vspId"); -// -// updateVendorSoftwareProduct(vspId, updatedVnfFile, filepath, user); -// HomePage.showVspRepository(); -// updateVSP(vsp); -// ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); -// DeploymentArtifactPage.verifyArtifactsExistInTable(filepath, updatedVnfFile); -// } -// -// public static Pair<String, Map<String, String>> onboardAndValidate(String filepath, String vnfFile, User user) throws Exception { -// ExtentTestActions.log(Status.INFO, String.format("Going to onboard the VNF %s", vnfFile)); -// System.out.println(String.format("Going to onboard the VNF %s", vnfFile)); -// -// AmdocsLicenseMembers amdocsLicenseMembers = createVendorLicense(user); -// Pair<String, Map<String, String>> createVendorSoftwareProduct = createVendorSoftwareProduct(vnfFile, filepath, user, amdocsLicenseMembers); -// String vspName = createVendorSoftwareProduct.left; -// -// DownloadManager.downloadCsarByNameFromVSPRepository(vspName, createVendorSoftwareProduct.right.get("vspId")); -// File latestFilefromDir = FileHandling.getLastModifiedFileNameFromDir(); -// -// ExtentTestActions.log(Status.INFO, String.format("Searching for onboarded %s", vnfFile)); -// HomePage.showVspRepository(); -// ExtentTestActions.log(Status.INFO,String.format("Going to import %s", vnfFile.substring(0, vnfFile.indexOf(".")))); -// importVSP(createVendorSoftwareProduct); -// -// ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); -// -// // Verify deployment artifacts -// Map<String, Object> combinedMap = ArtifactFromCsar.combineHeatArtifacstWithFolderArtifacsToMap(latestFilefromDir.getAbsolutePath()); -// -// LinkedList<HeatMetaFirstLevelDefinition> deploymentArtifacts = ((LinkedList<HeatMetaFirstLevelDefinition>) combinedMap.get("Deployment")); -// ArtifactsCorrelationManager.addVNFartifactDetails(vspName, deploymentArtifacts); -// -// List<String> heatEnvFilesFromCSAR = deploymentArtifacts.stream().filter(e -> e.getType().equals("HEAT_ENV")). -// map(e -> e.getFileName()). -// collect(Collectors.toList()); -// -// validateDeploymentArtifactsVersion(deploymentArtifacts, heatEnvFilesFromCSAR); -// -// DeploymentArtifactPage.verifyArtifactsExistInTable(filepath, vnfFile); -// return createVendorSoftwareProduct; -// } -// -// public static void validateDeploymentArtifactsVersion(LinkedList<HeatMetaFirstLevelDefinition> deploymentArtifacts, -// List<String> heatEnvFilesFromCSAR) { -// String artifactVersion; -// String artifactName; -// -// for(HeatMetaFirstLevelDefinition deploymentArtifact: deploymentArtifacts) { -// artifactVersion = "1"; -// -// if(deploymentArtifact.getType().equals("HEAT_ENV")) { -// continue; -// } else if(deploymentArtifact.getFileName().contains(".")) { -// artifactName = deploymentArtifact.getFileName().trim().substring(0, deploymentArtifact.getFileName().lastIndexOf(".")); -// } else { -// artifactName = deploymentArtifact.getFileName().trim(); -// } -// -// if (heatEnvFilesFromCSAR.contains(artifactName + ".env")){ -// artifactVersion = "2"; -// } -// ArtifactUIUtils.validateArtifactNameVersionType(artifactName, artifactVersion, deploymentArtifact.getType()); -// } -// } - - /** * @return * The method returns VNF names list from Files directory under sdc-vnfs repository @@ -993,11 +161,30 @@ public class OnboardingUtils { public static List<String> getVnfNamesFileList() { String filepath = FileHandling.getVnfRepositoryPath(); List<String> fileNamesFromFolder = FileHandling.getZipFileNamesFromFolder(filepath); + //Please remove the hardcoded configuration ONAP Tal G!!!!!! fileNamesFromFolder.removeAll(exludeVnfList); + //List<String> halfResourceListByDay = divideListByDayOfMonth(fileNamesFromFolder); + //System.out.println(halfResourceListByDay.toString()); return fileNamesFromFolder; } /** + * @param vnfNamesFileList + * @return divide List according to day of month, if day of month is even as get first half part of the List, else - second + */ + public static List<String> divideListByDayOfMonth(List<String> vnfNamesFileList){ + + Calendar cal = Calendar.getInstance(); + int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH)+1; + int filesCount = vnfNamesFileList.size(); + if(dayOfMonth%2 == 0){ + return vnfNamesFileList.subList(0,filesCount/2); + }else{ + return vnfNamesFileList.subList(filesCount/2, filesCount); + } + } + + /** * @return * The method returns VNF names list from Files directory under sdc-vnfs repository excluding zip files that known as failed in tosca parser */ @@ -1007,41 +194,6 @@ public class OnboardingUtils { return fileNamesFromFolder; } - public static VendorSoftwareProductObject fillVendorSoftwareProductObjectWithMetaData(String vnfFile, Pair<String, Map<String, String>> createVendorSoftwareProduct) { - VendorSoftwareProductObject vendorSoftwareProductObject = new VendorSoftwareProductObject(); - Map<String, String> map = createVendorSoftwareProduct.right; - vendorSoftwareProductObject.setAttContact(map.get("attContact")); - vendorSoftwareProductObject.setCategory(map.get("category")); - vendorSoftwareProductObject.setComponentId(map.get("componentId")); - vendorSoftwareProductObject.setDescription(map.get("description")); - vendorSoftwareProductObject.setSubCategory(map.get("subCategory")); - vendorSoftwareProductObject.setVendorName(map.get("vendorName")); - vendorSoftwareProductObject.setVspId(map.get("vspId")); - vendorSoftwareProductObject.setName(createVendorSoftwareProduct.left); - String[] arrFileNameAndExtension = vnfFile.split("\\."); - vendorSoftwareProductObject.setOnboardingMethod("NetworkPackage"); - vendorSoftwareProductObject.setNetworkPackageName(arrFileNameAndExtension[0]); - vendorSoftwareProductObject.setOnboardingOrigin(arrFileNameAndExtension[1]); - - return vendorSoftwareProductObject; - } - - public static void updateVendorSoftwareProductToNextVersion(VendorSoftwareProductObject vendorSoftwareProductObject, String toVspVersion, User user, String filepath, String heatFileName) - throws Exception, Throwable { - - RestResponse checkout = checkoutVendorSoftwareProduct(vendorSoftwareProductObject.getVspId(), user, vendorSoftwareProductObject.getVersion()); - assertEquals("did not succeed to checkout new VSP", 200, checkout.getErrorCode().intValue()); - - RestResponse uploadHeatPackage = uploadHeatPackage(filepath, heatFileName, vendorSoftwareProductObject.getVspId(), user, "1.1"); - assertEquals("did not succeed to upload HEAT package", 200, uploadHeatPackage.getErrorCode().intValue()); - - RestResponse validateUpload = validateUpload(vendorSoftwareProductObject.getVspId(), user, "1.1"); - assertEquals("did not succeed to validate upload process, reason: " + validateUpload.getResponse(), 200, validateUpload.getErrorCode().intValue()); - - prepareVspForUse(user,vendorSoftwareProductObject.getVspId(),toVspVersion); - - vendorSoftwareProductObject.setVersion(toVspVersion); - } public static Object[][] filterObjectArrWithExcludedVnfs(Object[][] objectArr) { diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/SnmpTypeEnum.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/SnmpTypeEnum.java index 366962ef0a..71038920ae 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/SnmpTypeEnum.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/SnmpTypeEnum.java @@ -20,6 +20,56 @@ package org.openecomp.sdc.ci.tests.utils.general; +import static org.testng.AssertJUnit.assertEquals; + +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.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.stream.Collectors; + +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.mime.MultipartEntityBuilder; +import org.apache.http.entity.mime.content.FileBody; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.json.JSONException; +import org.json.JSONObject; +import org.json.simple.JSONArray; +import org.json.simple.JSONValue; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.AmdocsLicenseMembers; + +import org.openecomp.sdc.ci.tests.datatypes.HeatMetaFirstLevelDefinition; + +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.execute.devCI.ArtifactFromCsar; + + +import org.openecomp.sdc.ci.tests.utils.Utils; +import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser; + +import org.testng.Assert; + +import com.aventstack.extentreports.Status; +import com.clearspring.analytics.util.Pair; + enum SnmpTypeEnum{ SNMP_POLL ("snmp"), SNMP_TRAP ("snmp-trap"); diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/VendorLicenseModelRestUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/VendorLicenseModelRestUtils.java new file mode 100644 index 0000000000..ec368df621 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/VendorLicenseModelRestUtils.java @@ -0,0 +1,285 @@ +package org.openecomp.sdc.ci.tests.utils.general; + +import com.aventstack.extentreports.Status; +import org.json.JSONObject; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.api.ComponentBaseTest; +import org.openecomp.sdc.ci.tests.api.Urls; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.AmdocsLicenseMembers; +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.rest.ResponseParser; + +import java.util.Arrays; +import java.util.Map; + +import static org.testng.AssertJUnit.assertEquals; + +public class VendorLicenseModelRestUtils { + + public static void updateVendorLicense(AmdocsLicenseMembers amdocsLicenseMembers, User user, Boolean isVlmUpdated) throws Exception { + +// create major method + RestResponse creationMethodVendorLicense = creationMethodVendorLicense(amdocsLicenseMembers, user); + assertEquals("did not succeed to create method for vendor license", 200, creationMethodVendorLicense.getErrorCode().intValue()); + amdocsLicenseMembers.setVersion(ResponseParser.getValueFromJsonResponse(creationMethodVendorLicense.getResponse(), "id")); + + if(isVlmUpdated) { +// TODO update vlm do nothing +// commit + RestResponse commitVendorLicense = commitVendorLicense(amdocsLicenseMembers, user); + assertEquals("did not succeed to commit vendor license", 200, commitVendorLicense.getErrorCode().intValue()); + } + +// submit + RestResponse submitVendorLicense = submitVendorLicense(amdocsLicenseMembers, user); + assertEquals("did not succeed to submit vendor license", 200, submitVendorLicense.getErrorCode().intValue()); + + if(ComponentBaseTest.getExtendTest() != null){ + ComponentBaseTest.getExtendTest().log(Status.INFO, "Succeeded in updating the vendor license"); + } + } + + private static RestResponse getVLMComponentByVersion(String vlmId, String vlmVersion, User user) throws Exception{ + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_VLM_COMPONENT_BY_VERSION, config.getCatalogBeHost(),config.getCatalogBePort(), vlmId,vlmVersion); + String userId = user.getUserId(); + + Map<String, String> headersMap = OnboardingUtils.prepareHeadersMap(userId); + + HttpRequest http = new HttpRequest(); + RestResponse response = http.httpSendGet(url, headersMap); + return response; + } + + public static boolean validateVlmExist(String vlmId, String vlmVersion, User user) throws Exception { + RestResponse restResponse = getVLMComponentByVersion(vlmId, vlmVersion, user); + assertEquals(String.format("VLM version not updated, reponse code message: %s", restResponse.getResponse()),restResponse.getErrorCode().intValue(),200); + return (restResponse.getErrorCode()==200); + } + + public static AmdocsLicenseMembers createVendorLicense(User user) throws Exception { + + AmdocsLicenseMembers amdocsLicenseMembers; +// ComponentBaseTest.getExtendTest().log(Status.INFO, "Starting to create the vendor license"); + String vendorLicenseName = "ciLicense" + OnboardingUtils.getShortUUID(); + RestResponse vendorLicenseResponse = createVendorLicenseModels_1(vendorLicenseName, user); + assertEquals("did not succeed to create vendor license model", 200, vendorLicenseResponse.getErrorCode().intValue()); + String vendorId = ResponseParser.getValueFromJsonResponse(vendorLicenseResponse.getResponse(), "itemId"); + String versionId = ResponseParser.getValueFromJsonResponse(vendorLicenseResponse.getResponse(), "version:id"); + + RestResponse vendorKeyGroupsResponse = createVendorKeyGroups_2(vendorId, versionId, user); + assertEquals("did not succeed to create vendor key groups", 200, vendorKeyGroupsResponse.getErrorCode().intValue()); + String keyGroupId = ResponseParser.getValueFromJsonResponse(vendorKeyGroupsResponse.getResponse(), "value"); + + RestResponse vendorEntitlementPool = createVendorEntitlementPool_3(vendorId, versionId, user); + assertEquals("did not succeed to create vendor entitlement pool", 200, vendorEntitlementPool.getErrorCode().intValue()); + String entitlementPoolId = ResponseParser.getValueFromJsonResponse(vendorEntitlementPool.getResponse(), "value"); + + RestResponse vendorLicenseFeatureGroups = createVendorLicenseFeatureGroups_4(vendorId, versionId, keyGroupId, entitlementPoolId, user); + assertEquals("did not succeed to create vendor license feature groups", 200, vendorLicenseFeatureGroups.getErrorCode().intValue()); + String featureGroupId = ResponseParser.getValueFromJsonResponse(vendorLicenseFeatureGroups.getResponse(), "value"); + + RestResponse vendorLicenseAgreement = createVendorLicenseAgreement_5(vendorId, versionId, featureGroupId, user); + assertEquals("did not succeed to create vendor license agreement", 200, vendorLicenseAgreement.getErrorCode().intValue()); + String vendorLicenseAgreementId = ResponseParser.getValueFromJsonResponse(vendorLicenseAgreement.getResponse(), "value"); + +// RestResponse checkinVendorLicense = OnboardingUtils.checkinVendorLicense(vendorId, user, versionId); +// assertEquals("did not succeed to checkin vendor license", 200, checkinVendorLicense.getErrorCode().intValue()); + + amdocsLicenseMembers = new AmdocsLicenseMembers(vendorId, vendorLicenseName, vendorLicenseAgreementId, featureGroupId); + amdocsLicenseMembers.setVersion(versionId); // Once object created and submitted, his initial version is 1.0 + + RestResponse submitVendorLicense = submitVendorLicense(amdocsLicenseMembers, user); + assertEquals("did not succeed to submit vendor license", 200, submitVendorLicense.getErrorCode().intValue()); + +// ComponentBaseTest.getExtendTest().log(Status.INFO, "Succeeded in creating the vendor license"); + + return amdocsLicenseMembers; + } + + private static RestResponse actionOnComponent(String vspid, String body, String onboardComponent, User user, String componentVersion) throws Exception { + Config config = Utils.getConfig(); + String url = String.format(Urls.ACTION_ON_COMPONENT, config.getCatalogBeHost(), config.getCatalogBePort(), onboardComponent, vspid, componentVersion); + String userId = user.getUserId(); + Map<String, String> headersMap = OnboardingUtils.prepareHeadersMap(userId); + + HttpRequest http = new HttpRequest(); + RestResponse response = http.httpSendPut(url, body, headersMap); + return response; + } + + private static RestResponse createMethodVendorLicense(String vendorId, String body, String onboardComponent, User user, String componentVersion) throws Exception { + Config config = Utils.getConfig(); + String url = String.format(Urls.CREATE_METHOD, config.getCatalogBeHost(), config.getCatalogBePort(), onboardComponent, vendorId, componentVersion); + String userId = user.getUserId(); + Map<String, String> headersMap = OnboardingUtils.prepareHeadersMap(userId); + + HttpRequest http = new HttpRequest(); + RestResponse response = http.httpSendPost(url, body, headersMap); + return response; + } + + public static RestResponse submitVendorLicense(AmdocsLicenseMembers amdocsLicenseMembers, User user) throws Exception { + return actionOnComponent(amdocsLicenseMembers.getVendorId(), "{\"action\":\"Submit\"}", "vendor-license-models", user, amdocsLicenseMembers.getVersion()); + } + + /** + * @param amdocsLicenseMembers + * @param user + * @return + * checkOut exist VLM method + * @throws Exception + */ + public static RestResponse creationMethodVendorLicense(AmdocsLicenseMembers amdocsLicenseMembers, User user) throws Exception { + String messageBody = "{\"description\":\"2.0\",\"creationMethod\":\"major\"}"; + return createMethodVendorLicense(amdocsLicenseMembers.getVendorId(), messageBody, "items", user, amdocsLicenseMembers.getVersion()); + } + + public static RestResponse commitVendorLicense(AmdocsLicenseMembers amdocsLicenseMembers, User user) throws Exception { + String messageBody = "{\"action\":\"Commit\",\"commitRequest\":{\"message\":\"commit\"}}"; + return actionOnComponent(amdocsLicenseMembers.getVendorId(), messageBody, "items", user, amdocsLicenseMembers.getVersion()); + } + + public static RestResponse createVendorLicenseModels_1(String name, User user) throws Exception { + Config config = Utils.getConfig(); + String url = String.format(Urls.CREATE_VENDOR_LISENCE_MODELS, config.getCatalogBeHost(), config.getCatalogBePort()); + String userId = user.getUserId(); + + JSONObject jObject = new JSONObject(); + jObject.put("vendorName", name); + jObject.put("description", "new vendor license model"); + jObject.put("iconRef", "icon"); + + Map<String, String> headersMap = OnboardingUtils.prepareHeadersMap(userId); + + HttpRequest http = new HttpRequest(); + RestResponse response = http.httpSendPost(url, jObject.toString(), headersMap); + return response; + + } + + public static RestResponse createVendorLicenseAgreement_5(String vspid, String versionId, String featureGroupId, User user) + throws Exception { + Config config = Utils.getConfig(); + String url = String.format(Urls.CREATE_VENDOR_LISENCE_AGREEMENT, config.getCatalogBeHost(), config.getCatalogBePort(), vspid, versionId); + String userId = user.getUserId(); + + JSONObject licenseTermpObject = new JSONObject(); + licenseTermpObject.put("choice", "Fixed_Term"); + licenseTermpObject.put("other", ""); + + JSONObject jObjectBody = new JSONObject(); + jObjectBody.put("name", "abc"); + jObjectBody.put("description", "new vendor license agreement"); + jObjectBody.put("requirementsAndConstrains", "abc"); + jObjectBody.put("licenseTerm", licenseTermpObject); + jObjectBody.put("addedFeatureGroupsIds", Arrays.asList(featureGroupId).toArray()); + + Map<String, String> headersMap = OnboardingUtils.prepareHeadersMap(userId); + + HttpRequest http = new HttpRequest(); + RestResponse response = http.httpSendPost(url, jObjectBody.toString(), headersMap); + return response; + } + + public static RestResponse createVendorLicenseFeatureGroups_4(String vspid, String versionId, String licenseKeyGroupId, + String entitlementPoolId, User user) throws Exception { + Config config = Utils.getConfig(); + String url = String.format(Urls.CREATE_VENDOR_LISENCE_FEATURE_GROUPS, config.getCatalogBeHost(), config.getCatalogBePort(), vspid, versionId); + String userId = user.getUserId(); + + JSONObject jObject = new JSONObject(); + jObject.put("name", "xyz"); + jObject.put("description", "new vendor license feature groups"); + jObject.put("partNumber", "123abc456"); + jObject.put("manufacturerReferenceNumber", "5"); + jObject.put("addedLicenseKeyGroupsIds", Arrays.asList(licenseKeyGroupId).toArray()); + jObject.put("addedEntitlementPoolsIds", Arrays.asList(entitlementPoolId).toArray()); + + Map<String, String> headersMap = OnboardingUtils.prepareHeadersMap(userId); + + HttpRequest http = new HttpRequest(); + RestResponse response = http.httpSendPost(url, jObject.toString(), headersMap); + return response; + + } + + public static RestResponse createVendorEntitlementPool_3(String vspid, String versionId, User user) throws Exception { + Config config = Utils.getConfig(); + String url = String.format(Urls.CREATE_VENDOR_LISENCE_ENTITLEMENT_POOL, config.getCatalogBeHost(), config.getCatalogBePort(), vspid, versionId); + String userId = user.getUserId(); + + JSONObject jEntitlementMetricObject = new JSONObject(); + jEntitlementMetricObject.put("choice", "CPU"); + jEntitlementMetricObject.put("other", ""); + + JSONObject jAggregationFunctionObject = new JSONObject(); + jAggregationFunctionObject.put("choice", "Peak"); + jAggregationFunctionObject.put("other", ""); + + JSONObject jOperationalScope = new JSONObject(); + jOperationalScope.put("choices", Arrays.asList("Availability_Zone").toArray()); + jOperationalScope.put("other", ""); + + JSONObject jTimeObject = new JSONObject(); + jTimeObject.put("choice", "Hour"); + jTimeObject.put("other", ""); + + JSONObject jObjectBody = new JSONObject(); + jObjectBody.put("name", "def"+ OnboardingUtils.getShortUUID()); + jObjectBody.put("description", "new vendor license entitlement pool"); + jObjectBody.put("thresholdValue", "23"); + jObjectBody.put("thresholdUnits", "Absolute"); + jObjectBody.put("entitlementMetric", jEntitlementMetricObject); + jObjectBody.put("increments", "abcd"); + jObjectBody.put("aggregationFunction", jAggregationFunctionObject); + jObjectBody.put("operationalScope", jOperationalScope); + jObjectBody.put("time", jTimeObject); + jObjectBody.put("manufacturerReferenceNumber", "123aaa"); + + Map<String, String> headersMap = OnboardingUtils.prepareHeadersMap(userId); + + HttpRequest http = new HttpRequest(); + RestResponse response = http.httpSendPost(url, jObjectBody.toString(), headersMap); + return response; + } + + public static RestResponse createVendorKeyGroups_2(String vspid, String versionId, User user) throws Exception { + Config config = Utils.getConfig(); + String url = String.format(Urls.CREATE_VENDOR_LISENCE_KEY_GROUPS, config.getCatalogBeHost(), config.getCatalogBePort(), vspid, versionId); + String userId = user.getUserId(); + + JSONObject jOperationalScope = new JSONObject(); + jOperationalScope.put("choices", Arrays.asList("Tenant").toArray()); + jOperationalScope.put("other", ""); + + JSONObject jObjectBody = new JSONObject(); + jObjectBody.put("name", "keyGroup" + OnboardingUtils.getShortUUID()); + jObjectBody.put("description", "new vendor license key group"); + jObjectBody.put("operationalScope", jOperationalScope); + jObjectBody.put("type", "Universal"); + + Map<String, String> headersMap = OnboardingUtils.prepareHeadersMap(userId); + + HttpRequest http = new HttpRequest(); + RestResponse response = http.httpSendPost(url, jObjectBody.toString(), headersMap); + return response; + } + + public static RestResponse validateUpload(String vspid, User user, String vspVersion) throws Exception { + String body = null; + Config config = Utils.getConfig(); + String url = String.format(Urls.VALIDATE_UPLOAD, config.getCatalogBeHost(), config.getCatalogBePort(), vspid,vspVersion); + String userId = user.getUserId(); + + Map<String, String> headersMap = OnboardingUtils.prepareHeadersMap(userId); + HttpRequest http = new HttpRequest(); + RestResponse response = http.httpSendPut(url, body, headersMap); + + return response; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/VendorSoftwareProductRestUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/VendorSoftwareProductRestUtils.java new file mode 100644 index 0000000000..c3b0a28f03 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/VendorSoftwareProductRestUtils.java @@ -0,0 +1,697 @@ +package org.openecomp.sdc.ci.tests.utils.general; + +import com.aventstack.extentreports.Status; +import com.clearspring.analytics.util.Pair; +import com.google.gson.Gson; +import org.apache.commons.io.IOUtils; +import org.apache.http.HttpEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.mime.MultipartEntityBuilder; +import org.apache.http.entity.mime.content.FileBody; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.json.simple.JSONArray; +import org.json.simple.JSONValue; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.api.ComponentBaseTest; +import org.openecomp.sdc.ci.tests.api.Urls; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.*; +import org.openecomp.sdc.ci.tests.datatypes.enums.CvfcTypeEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum; +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.rest.BaseRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; +import java.nio.file.FileSystems; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import static org.testng.AssertJUnit.assertEquals; + +public class VendorSoftwareProductRestUtils { + + public static Pair<String, VendorSoftwareProductObject> createVendorSoftwareProduct(ResourceReqDetails resourceReqDetails, String heatFileName, String filepath, User user, AmdocsLicenseMembers amdocsLicenseMembers, Map<CvfcTypeEnum, String> cvfcArtifacts) + throws Exception { + + Pair<String, VendorSoftwareProductObject> pair = createVSP(resourceReqDetails, heatFileName, filepath, user, amdocsLicenseMembers); + if(cvfcArtifacts != null && ! cvfcArtifacts.isEmpty()){ + addCvfcArtifacts(cvfcArtifacts, user, pair.right); + } + prepareVspForUse(user, pair.right, true); + return pair; + } + + public static Pair<String, VendorSoftwareProductObject> createVendorSoftwareProduct(ResourceReqDetails resourceReqDetails, String heatFileName, String filepath, User user, AmdocsLicenseMembers amdocsLicenseMembers) + throws Exception { + + Map<CvfcTypeEnum, String> cvfcArtifacts = new HashMap<>(); + return createVendorSoftwareProduct(resourceReqDetails, heatFileName, filepath, user, amdocsLicenseMembers, cvfcArtifacts); + } + + /** + * @param user user + * @param vendorSoftwareProductObject vendorSoftwareProductObject + * @param isVspUpdated - in case isVspUpdated = false the commit API should not be issued + * the method do commit, submit and create package + * @throws Exception + */ + public static void prepareVspForUse(User user, VendorSoftwareProductObject vendorSoftwareProductObject, Boolean isVspUpdated) throws Exception { + + if(isVspUpdated) { + RestResponse commit = commitVendorSoftwareProduct(vendorSoftwareProductObject, user); + assertEquals("did not succeed to commit new VSP", 200, commit.getErrorCode().intValue()); + } + RestResponse submit = submitVendorSoftwareProduct(vendorSoftwareProductObject.getVspId(), user, vendorSoftwareProductObject.getComponentId()); + assertEquals("did not succeed to submit new VSP", 200, submit.getErrorCode().intValue()); + + RestResponse createPackage = createPackageOfVendorSoftwareProduct(vendorSoftwareProductObject.getVspId(), user, vendorSoftwareProductObject.getComponentId()); + assertEquals("did not succeed to create package of new VSP ", 200, createPackage.getErrorCode().intValue()); + + } + + public static VendorSoftwareProductObject createAndFillVendorSoftwareProduct(ResourceReqDetails resourceReqDetails, String heatFileName, String filePath, User user, AmdocsLicenseMembers amdocsLicenseMembers, Map<CvfcTypeEnum, String> cvfcArtifacts) + throws Exception { + + Pair<String, VendorSoftwareProductObject> createVendorSoftwareProduct = createVendorSoftwareProduct(resourceReqDetails, heatFileName, filePath, user, amdocsLicenseMembers, cvfcArtifacts); + VendorSoftwareProductObject vendorSoftwareProductObject = fillVendorSoftwareProductObjectWithMetaData(heatFileName, createVendorSoftwareProduct); + return vendorSoftwareProductObject; + + } + + + public static Pair<String, VendorSoftwareProductObject> createVSP(ResourceReqDetails resourceReqDetails, String heatFileName, String filepath, User user, AmdocsLicenseMembers amdocsLicenseMembers) throws Exception { + String vspName = handleFilename(heatFileName); + + if(ComponentBaseTest.getExtendTest() != null){ + ComponentBaseTest.getExtendTest().log(Status.INFO, "Starting to create the vendor software product"); + } + + Pair<RestResponse, VendorSoftwareProductObject> createNewVspPair = createNewVendorSoftwareProduct(resourceReqDetails, vspName, amdocsLicenseMembers, user); + assertEquals("did not succeed to create new VSP", 200,createNewVspPair.left.getErrorCode().intValue()); + + RestResponse uploadHeatPackage = uploadHeatPackage(filepath, heatFileName, createNewVspPair.right, user); + assertEquals("did not succeed to upload HEAT package", 200, uploadHeatPackage.getErrorCode().intValue()); + + RestResponse validateUpload = validateUpload(createNewVspPair.right, user); + assertEquals("did not succeed to validate upload process, reason: " + validateUpload.getResponse(), 200, validateUpload.getErrorCode().intValue()); + + Pair<String, VendorSoftwareProductObject> pair = new Pair<>(vspName, createNewVspPair.right); + return pair; + } + + public static void updateVspWithVfcArtifacts(String filepath, String updatedSnmpPoll, String updatedSnmpTrap, String componentInstanceId, User user, VendorSoftwareProductObject vendorSoftwareProductObject) throws Exception{ + RestResponse checkout = creationMethodVendorSoftwareProduct(vendorSoftwareProductObject, user); + assertEquals("did not succeed to checkout new VSP", 200, checkout.getErrorCode().intValue()); +// ExtentTestActions.log(Status.INFO, "Deleting SNMP POLL"); + deleteArtifactByType(componentInstanceId, vendorSoftwareProductObject, user, CvfcTypeEnum.SNMP_POLL); +// ExtentTestActions.log(Status.INFO, "Deleting SNMP TRAP"); + deleteArtifactByType(componentInstanceId, vendorSoftwareProductObject, user, CvfcTypeEnum.SNMP_TRAP); + addVFCArtifacts(filepath, updatedSnmpPoll, updatedSnmpTrap, vendorSoftwareProductObject, user, componentInstanceId); + prepareVspForUse(user, vendorSoftwareProductObject, true); + } + + private static RestResponse deleteArtifactByType(String componentInstanceId, VendorSoftwareProductObject vendorSoftwareProductObject, User user, CvfcTypeEnum snmpType) throws Exception + { + Config config = Utils.getConfig(); + String url = String.format(Urls.DELETE_AMDOCS_ARTIFACT_BY_TYPE, config.getCatalogBeHost(), config.getCatalogBePort(), vendorSoftwareProductObject.getVspId(), vendorSoftwareProductObject.getComponentId(), componentInstanceId, snmpType.getValue()); + String userId = user.getUserId(); + Map<String, String> headersMap = OnboardingUtils.prepareHeadersMap(userId); + + HttpRequest http = new HttpRequest(); + RestResponse response = http.httpSendDelete(url, headersMap); + return response; + } + + public static void updateVendorSoftwareProductToNextVersion(VendorSoftwareProductObject vendorSoftwareProductObject, User user, Boolean isVspUpdated) throws Throwable { + + RestResponse createMethod = creationMethodVendorSoftwareProduct(vendorSoftwareProductObject, user); + assertEquals("did not succeed to createMethod for new VSP", 200, createMethod.getErrorCode().intValue()); + prepareVspForUse(user,vendorSoftwareProductObject, isVspUpdated); + + } + + public static String handleFilename(String heatFileName) { + final String namePrefix = String.format("%sVF%s", ElementFactory.getResourcePrefix(), "Onboarded-"); + final String nameSuffix = "-" + OnboardingUtils.getShortUUID(); + + String subHeatFileName = heatFileName.substring(0, heatFileName.lastIndexOf(".")); + + if ((namePrefix + subHeatFileName + nameSuffix).length() >= 50) { + subHeatFileName = subHeatFileName.substring(0, 50 - namePrefix.length() - nameSuffix.length()); + } + + if (subHeatFileName.contains("(") || subHeatFileName.contains(")")) { + subHeatFileName = subHeatFileName.replace("(", "-"); + subHeatFileName = subHeatFileName.replace(")", "-"); + } + + String vnfName = namePrefix + subHeatFileName + nameSuffix; + return vnfName; + } + + public static String addVFCArtifacts(String filepath, String snmpPoll, String snmpTrap, VendorSoftwareProductObject vendorSoftwareProductObject, User user, String componentInstanceId) throws Exception{ + componentInstanceId = (componentInstanceId == null) ? getVspComponentId(vendorSoftwareProductObject, user) : componentInstanceId; + if (componentInstanceId != null){ + if (snmpPoll != null){ +// ExtentTestActions.log(Status.INFO, "Adding VFC artifact of type SNMP POLL with the file " + snmpPoll); + RestResponse uploadSnmpPollArtifact = uploadSnmpPollArtifact(filepath, snmpPoll, vendorSoftwareProductObject, user, componentInstanceId); + assertEquals("Did not succeed to add SNMP POLL", 200, uploadSnmpPollArtifact.getErrorCode().intValue()); + } + if (snmpTrap != null){ +// ExtentTestActions.log(Status.INFO, "Adding VFC artifact of type SNMP TRAP with the file " + snmpTrap); + RestResponse uploadSnmpTrapArtifact = uploadSnmpTrapArtifact(filepath, snmpTrap, vendorSoftwareProductObject, user, componentInstanceId); + assertEquals("Did not succeed to add SNMP TRAP", 200, uploadSnmpTrapArtifact.getErrorCode().intValue()); + } + } + + return componentInstanceId; + } + + public static String addCvfcArtifacts(Map<CvfcTypeEnum, String> componentVfcArtifacts, User user, VendorSoftwareProductObject vendorSoftwareProductObject) throws Exception{ + String componentInstanceId = getVspComponentId(vendorSoftwareProductObject, user); + if (componentInstanceId != null){ + for(Map.Entry<CvfcTypeEnum, String> entry : componentVfcArtifacts.entrySet()){ +// ExtentTestActions.log(Status.INFO, "Adding VFC artifact of type " + entry.getKey().getValue() + " with the file " + entry.getValue()); + RestResponse uploadSnmpPollArtifact = uploadCvfcArtifact(entry.getValue(), entry.getKey().getValue(), user, vendorSoftwareProductObject, componentInstanceId); + assertEquals("Did not succeed to add " + entry.getKey().getValue(), BaseRestUtils.STATUS_CODE_SUCCESS, uploadSnmpPollArtifact.getErrorCode().intValue()); + } + } + return componentInstanceId; + } + + public static String addVFCArtifacts(String filepath, String snmpPoll, String snmpTrap, VendorSoftwareProductObject vendorSoftwareProductObject, User user) throws Exception{ + return addVFCArtifacts(filepath, snmpPoll, snmpTrap, vendorSoftwareProductObject, user, null); + } + + public static RestResponse uploadCvfcArtifact(String filepath, String cvfcType, User user, VendorSoftwareProductObject vendorSoftwareProductObject, String componentInstanceId) throws IOException { + Config config = Utils.getConfig(); + String snmpPollUrl = String.format(Urls.UPLOAD_AMDOCS_ARTIFACT, config.getCatalogBeHost(),config.getCatalogBePort(), vendorSoftwareProductObject.getVspId(), vendorSoftwareProductObject.getComponentId(), componentInstanceId, cvfcType); + return uploadFile(filepath, null, snmpPollUrl, user); + } + + + private static RestResponse uploadSnmpPollArtifact(String filepath, String zipArtifact, VendorSoftwareProductObject vendorSoftwareProductObject, User user, String componentInstanceId) throws IOException { + Config config = Utils.getConfig(); + String snmpPollUrl = String.format(Urls.UPLOAD_SNMP_POLL_ARTIFACT, config.getCatalogBeHost(),config.getCatalogBePort(), vendorSoftwareProductObject.getVspId(), vendorSoftwareProductObject.getComponentId(), componentInstanceId); + return uploadFile(filepath, zipArtifact, snmpPollUrl, user); + } + + private static RestResponse uploadSnmpTrapArtifact(String filepath, String zipArtifact, VendorSoftwareProductObject vendorSoftwareProductObject, User user, String vspComponentId) throws IOException { + Config config = Utils.getConfig(); + String snmpTrapUrl = String.format(Urls.UPLOAD_SNMP_POLL_ARTIFACT, config.getCatalogBeHost(),config.getCatalogBePort(), vendorSoftwareProductObject.getVspId(), vendorSoftwareProductObject.getComponentId(), vspComponentId); + return uploadFile(filepath, zipArtifact, snmpTrapUrl, user); + } + + private static RestResponse deleteSnmpArtifact(String componentId, String vspId, User user, SnmpTypeEnum snmpType) throws Exception + { + Config config = Utils.getConfig(); + String url = String.format(Urls.DELETE_AMDOCS_ARTIFACT_BY_TYPE, config.getCatalogBeHost(),config.getCatalogBePort(), vspId, componentId, snmpType.getValue()); + String userId = user.getUserId(); + + Map<String, String> headersMap = OnboardingUtils.prepareHeadersMap(userId); + + HttpRequest http = new HttpRequest(); + RestResponse response = http.httpSendDelete(url, headersMap); + return response; + } + + + /** + * @param vendorSoftwareProductObject VendorSoftwareProductObject + * @param user user object + * @return return first found component instance Id from list + * @throws Exception Exception + */ + private static String getVspComponentId(VendorSoftwareProductObject vendorSoftwareProductObject, User user) throws Exception { + RestResponse componentList = getVSPComponents(vendorSoftwareProductObject, user); + String response = componentList.getResponse(); + Map<String, Object> responseMap = (Map<String, Object>) JSONValue.parse(response); + JSONArray results = (JSONArray)responseMap.get("results"); + for (Object res : results){ + Map<String, Object> componentMap = (Map<String, Object>) JSONValue.parse(res.toString()); + String componentInstanceId = componentMap.get("id").toString(); + return componentInstanceId; + } + return null; + } + + private static RestResponse getVSPComponents(VendorSoftwareProductObject vendorSoftwareProductObject, User user) throws Exception{ + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_VSP_COMPONENTS, config.getCatalogBeHost(),config.getCatalogBePort(), vendorSoftwareProductObject.getVspId(), vendorSoftwareProductObject.getComponentId()); + Map<String, String> headersMap = OnboardingUtils.prepareHeadersMap(user.getUserId()); + + HttpRequest http = new HttpRequest(); + RestResponse response = http.httpSendGet(url, headersMap); + return response; + } + + + + public static boolean validateVspExist(VendorSoftwareProductObject vendorSoftwareProductObject, User user) throws Exception { + RestResponse restResponse = getVSPComponentByVersion(vendorSoftwareProductObject, user); + assertEquals(String.format("Vsp version not updated, reponse message: %s", restResponse.getResponse()),restResponse.getErrorCode().intValue(),200); + return (restResponse.getErrorCode()==200); + } + + + private static RestResponse getVSPComponentByVersion(VendorSoftwareProductObject vendorSoftwareProductObject, User user) throws Exception{ + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_VSP_COMPONENT_BY_VERSION, config.getCatalogBeHost(),config.getCatalogBePort(), vendorSoftwareProductObject.getVspId(), vendorSoftwareProductObject.getComponentId()); + String userId = user.getUserId(); + + Map<String, String> headersMap = OnboardingUtils.prepareHeadersMap(userId); + + HttpRequest http = new HttpRequest(); + RestResponse response = http.httpSendGet(url, headersMap); + return response; + } + + private static RestResponse actionOnComponent(String vspid, String body, String onboardComponent, User user, String componentVersion) throws Exception { + Config config = Utils.getConfig(); + String url = String.format(Urls.ACTION_ON_COMPONENT, config.getCatalogBeHost(), config.getCatalogBePort(), onboardComponent, vspid, componentVersion); + String userId = user.getUserId(); + Map<String, String> headersMap = OnboardingUtils.prepareHeadersMap(userId); + + HttpRequest http = new HttpRequest(); + RestResponse response = http.httpSendPut(url, body, headersMap); + return response; + } + + public static Pair<RestResponse, VendorSoftwareProductObject> createNewVendorSoftwareProduct(ResourceReqDetails resourceReqDetails, String vspName, AmdocsLicenseMembers amdocsLicenseMembers, User user) throws Exception { + + Config config = Utils.getConfig(); + String url = String.format(Urls.CREATE_VENDOR_SOFTWARE_PRODUCT, config.getCatalogBeHost(), config.getCatalogBePort()); + String userId = user.getUserId(); + VendorSoftwareProductObject vendorSoftwareProductObject = new VendorSoftwareProductObject(); + LicensingData licensingData = new LicensingData(amdocsLicenseMembers.getVendorLicenseAgreementId(), Arrays.asList(amdocsLicenseMembers.getFeatureGroupId())); + ResourceCategoryEnum resourceCategoryEnum = ResourceCategoryEnum.findEnumNameByValues(resourceReqDetails.getCategories().get(0).getName(), resourceReqDetails.getCategories().get(0).getSubcategories().get(0).getName()); + + vendorSoftwareProductObject.setName(vspName); + vendorSoftwareProductObject.setDescription(resourceReqDetails.getDescription()); + vendorSoftwareProductObject.setCategory(resourceCategoryEnum.getCategoryUniqeId()); + vendorSoftwareProductObject.setSubCategory(resourceCategoryEnum.getSubCategoryUniqeId()); + vendorSoftwareProductObject.setOnboardingMethod("NetworkPackage"); + vendorSoftwareProductObject.setVendorName(amdocsLicenseMembers.getVendorLicenseName()); + vendorSoftwareProductObject.setVendorId(amdocsLicenseMembers.getVendorId()); + vendorSoftwareProductObject.setIcon("icon"); + vendorSoftwareProductObject.setLicensingData(licensingData); + vendorSoftwareProductObject.setLicensingVersion(amdocsLicenseMembers.getVersion()); + + Map<String, String> headersMap = OnboardingUtils.prepareHeadersMap(userId); + HttpRequest http = new HttpRequest(); + Gson gson = new Gson(); + String body = gson.toJson(vendorSoftwareProductObject); + + RestResponse response = http.httpSendPost(url, body, headersMap); + + vendorSoftwareProductObject.setVspId(ResponseParser.getValueFromJsonResponse(response.getResponse(), "itemId")); + vendorSoftwareProductObject.setComponentId(ResponseParser.getValueFromJsonResponse(response.getResponse(), "version:id")); +// vendorSoftwareProductObject.setVersion(ResponseParser.getValueFromJsonResponse(response.getResponse(), "version:name")); + vendorSoftwareProductObject.setAttContact(user.getUserId()); + + return new Pair<>(response, vendorSoftwareProductObject); + } + + public static RestResponse validateUpload(VendorSoftwareProductObject vendorSoftwareProductObject, User user) throws Exception { + Config config = Utils.getConfig(); + String url = String.format(Urls.VALIDATE_UPLOAD, config.getCatalogBeHost(), config.getCatalogBePort(), vendorSoftwareProductObject.getVspId(), vendorSoftwareProductObject.getComponentId()); + String userId = user.getUserId(); + + Map<String, String> headersMap = OnboardingUtils.prepareHeadersMap(userId); + HttpRequest http = new HttpRequest(); + RestResponse response = http.httpSendPut(url, null, headersMap); + + return response; + } + + public static RestResponse uploadHeatPackage(String filepath, String filename, VendorSoftwareProductObject vendorSoftwareProductObject, User user) throws Exception { + Config config = Utils.getConfig(); + String url = String.format(Urls.UPLOAD_HEAT_PACKAGE, config.getCatalogBeHost(), config.getCatalogBePort(), vendorSoftwareProductObject.getVspId(), vendorSoftwareProductObject.getComponentId()); + return uploadFile(filepath, filename, url, user); + } + + private static RestResponse uploadFile(String filepath, String filename, String url, User user) throws IOException{ + CloseableHttpResponse response = null; + + MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create(); + mpBuilder.addPart("upload", new FileBody(getTestZipFile(filepath, filename))); + + Map<String, String> headersMap = OnboardingUtils.prepareHeadersMap(user.getUserId()); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "multipart/form-data"); + + CloseableHttpClient client = HttpClients.createDefault(); + try { + HttpPost httpPost = new HttpPost(url); + RestResponse restResponse = new RestResponse(); + + Iterator<String> iterator = headersMap.keySet().iterator(); + while (iterator.hasNext()) { + String key = iterator.next(); + String value = headersMap.get(key); + httpPost.addHeader(key, value); + } + httpPost.setEntity(mpBuilder.build()); + response = client.execute(httpPost); + HttpEntity entity = response.getEntity(); + String responseBody = null; + if (entity != null) { + InputStream instream = entity.getContent(); + try { + StringWriter writer = new StringWriter(); + IOUtils.copy(instream, writer); + responseBody = writer.toString(); + } finally { + instream.close(); + } + } + + restResponse.setErrorCode(response.getStatusLine().getStatusCode()); + restResponse.setResponse(responseBody); + + return restResponse; + + } finally { + closeResponse(response); + closeHttpClient(client); + + } + } + + private static void closeResponse(CloseableHttpResponse response) { + try { + if (response != null) { + response.close(); + } + } catch (IOException e) { + System.out.println(String.format("failed to close client or response: %s", e.getMessage())); + } + } + + private static void closeHttpClient(CloseableHttpClient client) { + try { + if (client != null) { + client.close(); + } + } catch (IOException e) { + System.out.println(String.format("failed to close client or response: %s", e.getMessage())); + } + } + + private static File getTestZipFile(String filepath, String filename) throws IOException { + Config config = Utils.getConfig(); + String sourceDir = config.getImportResourceTestsConfigDir(); + java.nio.file.Path filePath; + if(filename == null){ + filePath = FileSystems.getDefault().getPath(filepath); + }else{ + filePath = FileSystems.getDefault().getPath(filepath + File.separator + filename); + } + return filePath.toFile(); + } + + public static RestResponse checkinVendorSoftwareProduct(User user, VendorSoftwareProductObject vendorSoftwareProductObject) throws Exception { + Config config = Utils.getConfig(); + String url = String.format(Urls.UPDATE_VSP, config.getCatalogBeHost(), config.getCatalogBePort(), vendorSoftwareProductObject.getVspId(), vendorSoftwareProductObject.getComponentId()); + + String userId = user.getUserId(); + Map<String, String> headersMap = OnboardingUtils.prepareHeadersMap(userId); +// unset vspId, componentId, attContact, onboardingMethod + String vspId = vendorSoftwareProductObject.getVspId(); + String componentId = vendorSoftwareProductObject.getComponentId(); + String attContact = vendorSoftwareProductObject.getAttContact(); + String onboardingMethod = vendorSoftwareProductObject.getOnboardingMethod(); + vendorSoftwareProductObject.setVspId(null); + vendorSoftwareProductObject.setComponentId(null); + vendorSoftwareProductObject.setAttContact(null); + vendorSoftwareProductObject.setOnboardingMethod(null); + Gson gson = new Gson(); + String body = gson.toJson(vendorSoftwareProductObject); + HttpRequest http = new HttpRequest(); + RestResponse response = http.httpSendPut(url, body, headersMap); +// set back vspId, componentId, attContact, onboardingMethod + vendorSoftwareProductObject.setVspId(vspId); + vendorSoftwareProductObject.setComponentId(componentId); + vendorSoftwareProductObject.setAttContact(attContact); + vendorSoftwareProductObject.setOnboardingMethod(onboardingMethod); + + return response; + } + + public static RestResponse commitVendorSoftwareProduct(VendorSoftwareProductObject vendorSoftwareProductObject, User user) throws Exception { + String messageBody = "{\"action\":\"Commit\",\"commitRequest\":{\"message\":\"commit\"}}"; + return actionOnComponent(vendorSoftwareProductObject.getVspId(), messageBody, "items", user, vendorSoftwareProductObject.getComponentId()); + } + + public static RestResponse submitVendorSoftwareProduct(String vspid, User user, String componentId) throws Exception { + return actionOnComponent(vspid, "{\"action\":\"Submit\"}", "vendor-software-products", user, componentId); + } + + public static RestResponse createPackageOfVendorSoftwareProduct(String vspid, User user, String componentId) throws Exception { + return actionOnComponent(vspid, "{\"action\":\"Create_Package\"}", "vendor-software-products", user, componentId); + } + + public static RestResponse creationMethodVendorSoftwareProduct(VendorSoftwareProductObject vendorSoftwareProductObject, User user) throws Exception { + String messageBody = "{\"description\":\"2.0\",\"creationMethod\":\"major\"}"; + return createMethodVendorSoftwareProduct(vendorSoftwareProductObject, messageBody, "items", user); + } + + private static RestResponse createMethodVendorSoftwareProduct(VendorSoftwareProductObject vendorSoftwareProductObject, String body, String onboardComponent, User user) throws Exception { + Config config = Utils.getConfig(); + String url = String.format(Urls.CREATE_METHOD, config.getCatalogBeHost(), config.getCatalogBePort(), onboardComponent, vendorSoftwareProductObject.getVspId(), vendorSoftwareProductObject.getComponentId()); + String userId = user.getUserId(); + Map<String, String> headersMap = OnboardingUtils.prepareHeadersMap(userId); + + HttpRequest http = new HttpRequest(); + RestResponse response = http.httpSendPost(url, body, headersMap); + if(response.getErrorCode().intValue() == 200) { + vendorSoftwareProductObject.setComponentId(ResponseParser.getValueFromJsonResponse(response.getResponse(), "id")); + } + return response; + } + + public static VendorSoftwareProductObject updateVSPWithNewVLMParameters(VendorSoftwareProductObject vendorSoftwareProductObject, AmdocsLicenseMembers amdocsLicenseMembers, User user) throws Exception { + + RestResponse createMethod = creationMethodVendorSoftwareProduct(vendorSoftwareProductObject, user); + assertEquals("did not succeed to checkout new VSP", 200, createMethod.getErrorCode().intValue()); +// vendorSoftwareProductObject.setComponentId(ResponseParser.getValueFromJsonResponse(createMethod.getResponse(), "id")); + + String licensingVersion = amdocsLicenseMembers.getVersion(); + LicensingData licensingData = new LicensingData(amdocsLicenseMembers.getVendorLicenseAgreementId(), Arrays.asList(amdocsLicenseMembers.getFeatureGroupId())); + vendorSoftwareProductObject.setVendorId(amdocsLicenseMembers.getVendorId()); + vendorSoftwareProductObject.setVendorName(amdocsLicenseMembers.getVendorLicenseName()); + vendorSoftwareProductObject.setLicensingVersion(licensingVersion); + vendorSoftwareProductObject.setLicensingData(licensingData); + + VendorSoftwareProductObjectReqDetails vendorSoftwareProductObjectReqDetails = new VendorSoftwareProductObjectReqDetails( + vendorSoftwareProductObject.getName(), vendorSoftwareProductObject.getDescription(), vendorSoftwareProductObject.getCategory(), + vendorSoftwareProductObject.getSubCategory(), vendorSoftwareProductObject.getVendorId(), vendorSoftwareProductObject.getVendorName(), + vendorSoftwareProductObject.getLicensingVersion(), vendorSoftwareProductObject.getLicensingData(), + null, null, null, vendorSoftwareProductObject.getIcon() ); + + Gson gson = new Gson(); + String body = gson.toJson(vendorSoftwareProductObjectReqDetails); + RestResponse updateResponse = updateVendorSoftwareProduct(vendorSoftwareProductObject, body, user); + assertEquals("did not succeed to update VSP", 200, updateResponse.getErrorCode().intValue()); + + prepareVspForUse(user, vendorSoftwareProductObject, true); + + return vendorSoftwareProductObject; + } + + public static RestResponse updateVendorSoftwareProduct(VendorSoftwareProductObject vendorSoftwareProductObject, String body, User user) throws Exception { + + Config config = Utils.getConfig(); + String url = String.format(Urls.UPDATE_VSP, config.getCatalogBeHost(), config.getCatalogBePort(), vendorSoftwareProductObject.getVspId(), vendorSoftwareProductObject.getComponentId()); + String userId = user.getUserId(); + + Map<String, String> headersMap = OnboardingUtils.prepareHeadersMap(userId); + HttpRequest http = new HttpRequest(); + + RestResponse response = http.httpSendPut(url, body, headersMap); + return response; + } + +// private static void importUpdateVSP(Pair<String, Map<String, String>> vsp, boolean isUpdate) throws Exception{ +// String vspName = vsp.left; +// Map<String, String> vspMetadata = vsp.right; +// boolean vspFound = HomePage.searchForVSP(vspName); +// +// if (vspFound){ +// +// List<WebElement> elemenetsFromTable = HomePage.getElemenetsFromTable(); +//// WebDriverWait wait = new WebDriverWait(GeneralUIUtils.getDriver(), 30); +//// WebElement findElement = wait.until(ExpectedConditions.visibilityOf(elemenetsFromTable.get(1))); +//// findElement.click(); +// elemenetsFromTable.get(1).click(); +// GeneralUIUtils.waitForLoader(); +// +// if (isUpdate){ +// GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ImportVfRepository.UPDATE_VSP.getValue()); +// +// } +// else{ +// GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ImportVfRepository.IMPORT_VSP.getValue()); +// } +// +// String lifeCycleState = ResourceGeneralPage.getLifeCycleState(); +// boolean needCheckout = lifeCycleState.equals(LifeCycleStateEnum.CHECKIN.getValue()) || lifeCycleState.equals(LifeCycleStateEnum.CERTIFIED.getValue()); +// if (needCheckout) +// { +// try { +// ResourceGeneralPage.clickCheckoutButton(); +// Assert.assertTrue(ResourceGeneralPage.getLifeCycleState().equals(LifeCycleStateEnum.CHECKOUT.getValue()), "Did not succeed to checkout"); +// +// } catch (Exception e) { +// ExtentTestActions.log(Status.ERROR, "Did not succeed to checkout"); +// e.printStackTrace(); +// } +// GeneralUIUtils.waitForLoader(); +// } +// +// //Metadata verification +// VfVerificator.verifyOnboardedVnfMetadata(vspName, vspMetadata); +// +// ExtentTestActions.log(Status.INFO, "Clicking create/update VNF"); +// String duration = GeneralUIUtils.getActionDuration(() -> waitUntilVnfCreated()); +// ExtentTestActions.log(Status.INFO, "Succeeded in importing/updating " + vspName, duration); +// } +// else{ +// Assert.fail("Did not find VSP named " + vspName); +// } +// } + +// private static void waitUntilVnfCreated() { +// GeneralUIUtils.clickOnElementByTestIdWithoutWait(DataTestIdEnum.GeneralElementsEnum.CREATE_BUTTON.getValue()); +// GeneralUIUtils.waitForLoader(60*10); +// GeneralUIUtils.waitForAngular(); +// GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.GeneralElementsEnum.CHECKIN_BUTTON.getValue()); +// } +// +// public static void updateVSP(Pair<String, Map<String, String>> vsp) throws Exception{ +// ExtentTestActions.log(Status.INFO, "Updating VSP " + vsp.left); +// importUpdateVSP(vsp, true); +// } +// +// public static void importVSP(Pair<String, Map<String, String>> vsp) throws Exception{ +// ExtentTestActions.log(Status.INFO, "Importing VSP " + vsp.left); +// importUpdateVSP(vsp, false); +// } +// +// public static void updateVnfAndValidate(String filepath, Pair<String, Map<String, String>> vsp, String updatedVnfFile, User user) throws Exception, Throwable { +// ExtentTestActions.log(Status.INFO, String.format("Going to update the VNF with %s......", updatedVnfFile)); +// System.out.println(String.format("Going to update the VNF with %s......", updatedVnfFile)); +// +// Map<String, String> vspMap = vsp.right; +// String vspId = vspMap.get("vspId"); +// +// updateVendorSoftwareProduct(vspId, updatedVnfFile, filepath, user); +// HomePage.showVspRepository(); +// updateVSP(vsp); +// ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); +// DeploymentArtifactPage.verifyArtifactsExistInTable(filepath, updatedVnfFile); +// } +// +// public static Pair<String, Map<String, String>> onboardAndValidate(String filepath, String vnfFile, User user) throws Exception { +// ExtentTestActions.log(Status.INFO, String.format("Going to onboard the VNF %s", vnfFile)); +// System.out.println(String.format("Going to onboard the VNF %s", vnfFile)); +// +// AmdocsLicenseMembers amdocsLicenseMembers = createVendorLicense(user); +// Pair<String, Map<String, String>> createVendorSoftwareProduct = createVendorSoftwareProduct(vnfFile, filepath, user, amdocsLicenseMembers); +// String vspName = createVendorSoftwareProduct.left; +// +// DownloadManager.downloadCsarByNameFromVSPRepository(vspName, createVendorSoftwareProduct.right.get("vspId")); +// File latestFilefromDir = FileHandling.getLastModifiedFileNameFromDir(); +// +// ExtentTestActions.log(Status.INFO, String.format("Searching for onboarded %s", vnfFile)); +// HomePage.showVspRepository(); +// ExtentTestActions.log(Status.INFO,String.format("Going to import %s", vnfFile.substring(0, vnfFile.indexOf(".")))); +// importVSP(createVendorSoftwareProduct); +// +// ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); +// +// // Verify deployment artifacts +// Map<String, Object> combinedMap = ArtifactFromCsar.combineHeatArtifacstWithFolderArtifacsToMap(latestFilefromDir.getAbsolutePath()); +// +// LinkedList<HeatMetaFirstLevelDefinition> deploymentArtifacts = ((LinkedList<HeatMetaFirstLevelDefinition>) combinedMap.get("Deployment")); +// ArtifactsCorrelationManager.addVNFartifactDetails(vspName, deploymentArtifacts); +// +// List<String> heatEnvFilesFromCSAR = deploymentArtifacts.stream().filter(e -> e.getType().equals("HEAT_ENV")). +// map(e -> e.getFileName()). +// collect(Collectors.toList()); +// +// validateDeploymentArtifactsVersion(deploymentArtifacts, heatEnvFilesFromCSAR); +// +// DeploymentArtifactPage.verifyArtifactsExistInTable(filepath, vnfFile); +// return createVendorSoftwareProduct; +// } +// +// public static void validateDeploymentArtifactsVersion(LinkedList<HeatMetaFirstLevelDefinition> deploymentArtifacts, +// List<String> heatEnvFilesFromCSAR) { +// String artifactVersion; +// String artifactName; +// +// for(HeatMetaFirstLevelDefinition deploymentArtifact: deploymentArtifacts) { +// artifactVersion = "1"; +// +// if(deploymentArtifact.getType().equals("HEAT_ENV")) { +// continue; +// } else if(deploymentArtifact.getFileName().contains(".")) { +// artifactName = deploymentArtifact.getFileName().trim().substring(0, deploymentArtifact.getFileName().lastIndexOf(".")); +// } else { +// artifactName = deploymentArtifact.getFileName().trim(); +// } +// +// if (heatEnvFilesFromCSAR.contains(artifactName + ".env")){ +// artifactVersion = "2"; +// } +// ArtifactUIUtils.validateArtifactNameVersionType(artifactName, artifactVersion, deploymentArtifact.getType()); +// } +// } + + + public static VendorSoftwareProductObject fillVendorSoftwareProductObjectWithMetaData(String vnfFile, Pair<String, VendorSoftwareProductObject> createVendorSoftwareProduct) { + VendorSoftwareProductObject vendorSoftwareProductObject = new VendorSoftwareProductObject(); + VendorSoftwareProductObject map = createVendorSoftwareProduct.right; + vendorSoftwareProductObject.setAttContact(map.getAttContact()); + vendorSoftwareProductObject.setCategory(map.getCategory()); + vendorSoftwareProductObject.setComponentId(map.getComponentId()); + vendorSoftwareProductObject.setDescription(map.getDescription()); + vendorSoftwareProductObject.setSubCategory(map.getSubCategory()); + vendorSoftwareProductObject.setVendorName(map.getVendorName()); + vendorSoftwareProductObject.setVspId(map.getVspId()); + vendorSoftwareProductObject.setName(createVendorSoftwareProduct.left); + String[] arrFileNameAndExtension = vnfFile.split("\\."); + vendorSoftwareProductObject.setOnboardingMethod("NetworkPackage"); + vendorSoftwareProductObject.setNetworkPackageName(arrFileNameAndExtension[0]); + vendorSoftwareProductObject.setOnboardingOrigin(arrFileNameAndExtension[1]); + + return vendorSoftwareProductObject; + } + + public static void updateVendorSoftwareProductToNextVersion(VendorSoftwareProductObject vendorSoftwareProductObject, User user, String filepath, String heatFileName) throws Throwable { + + RestResponse createMethod = creationMethodVendorSoftwareProduct(vendorSoftwareProductObject, user); + assertEquals("did not succeed to createMethod for new VSP", 200, createMethod.getErrorCode().intValue()); + + RestResponse uploadHeatPackage = uploadHeatPackage(filepath, heatFileName, vendorSoftwareProductObject, user); + assertEquals("did not succeed to upload HEAT package", 200, uploadHeatPackage.getErrorCode().intValue()); + + RestResponse validateUpload = validateUpload(vendorSoftwareProductObject, user); + assertEquals("did not succeed to validate upload process, reason: " + validateUpload.getResponse(), 200, validateUpload.getErrorCode().intValue()); + + prepareVspForUse(user,vendorSoftwareProductObject, true); + } + + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ArtifactRestUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ArtifactRestUtils.java index a7ab544725..448442e112 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ArtifactRestUtils.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ArtifactRestUtils.java @@ -50,15 +50,12 @@ 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.api.Constants; import org.openecomp.sdc.common.util.ValidationUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.AssertJUnit; import com.google.gson.Gson; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; public class ArtifactRestUtils extends BaseRestUtils { private static Logger logger = LoggerFactory.getLogger(ArtifactRestUtils.class.getName()); @@ -68,7 +65,7 @@ public class ArtifactRestUtils extends BaseRestUtils { // 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 resourceType; String resourceUUID = component.getUUID(); String resourceInstanceName = resourceInstance.getNormalizedName(); @@ -88,7 +85,7 @@ public class ArtifactRestUtils extends BaseRestUtils { // 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 resourceType; String resourceUUID = component.getUUID(); System.out.println(component.getComponentType()); @@ -110,7 +107,7 @@ public class ArtifactRestUtils extends BaseRestUtils { // 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 resourceType; String resourceUUID = component.getUUID(); String resourceInstanceName = resourceInstance.getNormalizedName(); @@ -130,7 +127,7 @@ public class ArtifactRestUtils extends BaseRestUtils { // 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 resourceType; String resourceUUID = component.getUUID(); System.out.println(component.getComponentType()); @@ -150,7 +147,7 @@ public class ArtifactRestUtils extends BaseRestUtils { // 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 resourceType; String resourceUUID = component.getUUID(); String resourceInstanceName = resourceInstance.getNormalizedName(); @@ -170,7 +167,7 @@ public class ArtifactRestUtils extends BaseRestUtils { // 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 resourceType; String resourceUUID = component.getUUID(); System.out.println(component.getComponentType()); @@ -190,7 +187,7 @@ public class ArtifactRestUtils extends BaseRestUtils { // 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 resourceType; String resourceUUID = component.getUUID(); String resourceInstanceName = resourceInstance.getNormalizedName(); @@ -210,7 +207,7 @@ public class ArtifactRestUtils extends BaseRestUtils { // 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 resourceType; String resourceUUID = component.getUUID(); System.out.println(component.getComponentType()); @@ -232,7 +229,7 @@ public class ArtifactRestUtils extends BaseRestUtils { // public static RestResponse getResourceDeploymentArtifactExternalAPI(String resourceUUID, String artifactUUID,User sdncModifierDetails, String resourceType) throws IOException { Config config = Utils.getConfig(); - String url = null; + String url; if (resourceType.toUpperCase().equals("SERVICE")) { url = String.format(Urls.GET_DOWNLOAD_SERVICE_ARTIFACT_OF_ASSET, config.getCatalogBeHost(), config.getCatalogBePort(), resourceUUID, artifactUUID); @@ -241,11 +238,12 @@ public class ArtifactRestUtils extends BaseRestUtils { url = String.format(Urls.GET_DOWNLOAD_RESOURCE_ARTIFACT_OF_ASSET, config.getCatalogBeHost(), config.getCatalogBePort(), resourceUUID, artifactUUID); } - Map<String, String> headersMap = new HashMap<String,String>(); + Map<String, String> headersMap = new HashMap<>(); 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"); + headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), BaseRestUtils.xEcompInstanceId); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(),acceptMultipartHeader); HttpRequest http = new HttpRequest(); @@ -265,7 +263,7 @@ public class ArtifactRestUtils extends BaseRestUtils { public static RestResponse getComponentInstanceDeploymentArtifactExternalAPI(String resourceUUID, String componentNormalizedName, String artifactUUID,User sdncModifierDetails, String resourceType) throws IOException { Config config = Utils.getConfig(); - String url = null; + String url; if (resourceType.toLowerCase().equals("service")) { url = String.format(Urls.GET_DOWNLOAD_SERVICE_ARTIFACT_OF_COMPONENT_INSTANCE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceUUID, componentNormalizedName, artifactUUID); @@ -274,11 +272,12 @@ public class ArtifactRestUtils extends BaseRestUtils { 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>(); + Map<String, String> headersMap = new HashMap<>(); 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"); + headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), BaseRestUtils.xEcompInstanceId); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(),acceptMultipartHeader); HttpRequest http = new HttpRequest(); @@ -443,7 +442,7 @@ public class ArtifactRestUtils extends BaseRestUtils { public static Map<String, String> getHeadersMap(User sdncModifierDetails) { - Map<String, String> headersMap = new HashMap<String,String>(); + Map<String, String> headersMap = new HashMap<>(); headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptJsonHeader); @@ -602,9 +601,9 @@ public class ArtifactRestUtils extends BaseRestUtils { public static RestResponse uploadDeploymentArtifact(ArtifactReqDetails artifactDetails, Component component, User sdncModifierDetails) throws IOException { Config config = Utils.getConfig(); - Map<String, String> additionalHeaders = null; + Map<String, String> additionalHeaders; String checksum = ResponseParser.calculateMD5Header(artifactDetails); - additionalHeaders = new HashMap<String, String>(); + additionalHeaders = new HashMap<>(); additionalHeaders.put(HttpHeaderEnum.Content_MD5.getValue(), checksum); ComponentTypeEnum componentType = component.getComponentType(); @@ -614,26 +613,26 @@ public class ArtifactRestUtils extends BaseRestUtils { 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; - } + { + 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; + } } @@ -654,9 +653,9 @@ public class ArtifactRestUtils extends BaseRestUtils { 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; + Map<String, String> additionalHeaders; + String checksum; + String url; // // // if (artifactDetails.getArtifactGroupType() != null @@ -676,7 +675,7 @@ public class ArtifactRestUtils extends BaseRestUtils { // // else { checksum = ResponseParser.calculateMD5Header(artifactDetails); - additionalHeaders = new HashMap<String, String>(); + additionalHeaders = new HashMap<>(); additionalHeaders.put(HttpHeaderEnum.Content_MD5.getValue(), checksum); url = String.format(Urls.UPLOAD_DELETE_ARTIFACT_OF_COMPONENT, config.getCatalogBeHost(), config.getCatalogBePort(), ComponentTypeEnum.findParamByType(component.getComponentType()), @@ -700,13 +699,13 @@ public class ArtifactRestUtils extends BaseRestUtils { //*************** PRIVATE ************** private static RestResponse deleteInformationalArtifact(User sdncModifierDetails, String url) throws IOException { - Map<String, String> additionalHeaders = null; + Map<String, String> additionalHeaders; - additionalHeaders = new HashMap<String, String>(); + additionalHeaders = new HashMap<>(); additionalHeaders.put(HttpHeaderEnum.AUTHORIZATION.getValue(), authorizationHeader); - additionalHeaders.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci"); + additionalHeaders.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), BaseRestUtils.xEcompInstanceId); return sendDelete(url, sdncModifierDetails.getUserId(), additionalHeaders); @@ -729,12 +728,12 @@ public class ArtifactRestUtils extends BaseRestUtils { 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 = new HashMap<>(); additionalHeaders.put(HttpHeaderEnum.Content_MD5.getValue(), checksum); } additionalHeaders.put(HttpHeaderEnum.AUTHORIZATION.getValue(), authorizationHeader); - additionalHeaders.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci"); + additionalHeaders.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), BaseRestUtils.xEcompInstanceId); Gson gson = new Gson(); // System.out.println("ArtifactDetails: "+ jsonBody); @@ -749,10 +748,10 @@ public class ArtifactRestUtils extends BaseRestUtils { } private static RestResponse addArtifactToInstance(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String checksum, String url) throws IOException { - Map<String, String> additionalHeaders = null; - additionalHeaders = new HashMap<String, String>(); + Map<String, String> additionalHeaders; + additionalHeaders = new HashMap<>(); if (checksum != null && !checksum.isEmpty()) { - additionalHeaders = new HashMap<String, String>(); + additionalHeaders = new HashMap<>(); additionalHeaders.put(HttpHeaderEnum.Content_MD5.getValue(), checksum); } additionalHeaders.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json, text/plain, */*"); @@ -769,8 +768,8 @@ public class ArtifactRestUtils extends BaseRestUtils { } private static RestResponse updateDeploymentArtifact(ArtifactDefinition artifactDefinition, User sdncModifierDetails, String url) throws IOException { - Map<String, String> additionalHeaders = null; - additionalHeaders = new HashMap<String, String>(); + Map<String, String> additionalHeaders; + additionalHeaders = new HashMap<>(); additionalHeaders.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json, text/plain, */*"); additionalHeaders.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json;charset=UTF-8"); @@ -782,9 +781,9 @@ public class ArtifactRestUtils extends BaseRestUtils { } private static RestResponse updateDeploymentArtifact(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String url) throws IOException { - Map<String, String> additionalHeaders = null; + Map<String, String> additionalHeaders; - additionalHeaders = new HashMap<String, String>(); + additionalHeaders = new HashMap<>(); 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"); @@ -805,7 +804,7 @@ public class ArtifactRestUtils extends BaseRestUtils { 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); + addionalHeaders.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), BaseRestUtils.xEcompInstanceId); } return downloadArtifact(url, user, addionalHeaders, acceptOctetStream); } @@ -906,29 +905,5 @@ public class ArtifactRestUtils extends BaseRestUtils { } - - public static ArtifactDefinition getArtifactDataFromJson(String json) { - Gson gson = new Gson(); - JsonObject jsonElement = new JsonObject(); - jsonElement = gson.fromJson(json, jsonElement.getClass()); - ArtifactDefinition artifact = new ArtifactDefinition(); - String payload = null; - JsonElement artifactPayload = jsonElement.get(Constants.ARTIFACT_PAYLOAD_DATA); - if (artifactPayload != null && !artifactPayload.isJsonNull()) { - payload = artifactPayload.getAsString(); - } - jsonElement.remove(Constants.ARTIFACT_PAYLOAD_DATA); - artifact = gson.fromJson(jsonElement, ArtifactDefinition.class); - artifact.setPayloadData(payload); - - /*atifact.setArtifactName(UPLOAD_ARTIFACT_NAME); -artifact.setArtifactDisplayName("configure"); -artifact.setArtifactType("SHELL"); -artifact.setMandatory(false); -artifact.setDescription("ff"); -artifact.setPayloadData(UPLOAD_ARTIFACT_PAYLOAD); -artifact.setArtifactLabel("configure");*/ - return artifact; - } } diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/AssetRestUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/AssetRestUtils.java index 4ade9eb16c..13cfb8fb63 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/AssetRestUtils.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/AssetRestUtils.java @@ -31,7 +31,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; -import java.util.UUID; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; @@ -39,7 +38,7 @@ import org.apache.http.client.methods.CloseableHttpResponse; 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 com.fasterxml.jackson.databind.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; @@ -78,8 +77,6 @@ public class AssetRestUtils extends BaseRestUtils { static ObjectMapper objectMapper = new ObjectMapper(); static Logger logger = LoggerFactory.getLogger(AssetRestUtils.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"; @@ -93,7 +90,7 @@ public class AssetRestUtils extends BaseRestUtils { assetType.getValue(), uuid); HttpGet httpGet = new HttpGet(url); - httpGet.addHeader(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci"); + httpGet.addHeader(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), BaseRestUtils.xEcompInstanceId); httpGet.addHeader(HttpHeaderEnum.AUTHORIZATION.getValue(), basicAuthentication); logger.debug("Send GET request to get Tosca model: {}", url); @@ -101,18 +98,27 @@ public class AssetRestUtils extends BaseRestUtils { return httpclient.execute(httpGet); } + public static File getToscaModelCsarFile(AssetTypeEnum assetType, String uuid) throws IOException { + return getToscaModelCsarFile(assetType, uuid, ""); + } + public static File getToscaModelCsarFile(AssetTypeEnum assetType, String uuid, String fileName) throws IOException { + File myFile; 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); - - String csarDir = FileHandling.getCreateDirByName("outputCsar"); - File myFile = new File(csarDir+ File.separator + "tmpCSAR_" + fileName + ".csar"); + + if(fileName.isEmpty()) { + myFile = new File("tmpCSAR"); + } else { + String csarDir = FileHandling.getCreateDirByName("outputCsar"); + myFile = new File(csarDir+ File.separator + "tmpCSAR_" + fileName + ".csar"); + } - httpGet.addHeader(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci"); + httpGet.addHeader(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), BaseRestUtils.xEcompInstanceId); httpGet.addHeader(HttpHeaderEnum.AUTHORIZATION.getValue(), basicAuthentication); logger.debug("Send GET request to get Tosca model: {}", url); @@ -127,19 +133,17 @@ public class AssetRestUtils extends BaseRestUtils { } return myFile; } - - - + 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>(); + Map<String, String> headersMap = new HashMap<>(); headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), authorizationHeader); - headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci"); + headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), BaseRestUtils.xEcompInstanceId); HttpRequest http = new HttpRequest(); @@ -158,16 +162,16 @@ public class AssetRestUtils extends BaseRestUtils { 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); + Map<String, String> headersMap = new HashMap<>(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), BaseRestUtils.contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), BaseRestUtils.acceptHeaderData); if (isBasicAuthentication) { headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), basicAuthentication); } - headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci"); + headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), BaseRestUtils.xEcompInstanceId); HttpRequest http = new HttpRequest(); - String url = String.format(Urls.GET_ASSET_LIST, config.getCatalogBeHost(), config.getCatalogBePort(), + String url = String.format(Urls.GET_ASSET_LIST, config.getCatalogBeHost(), config.getCatalogBePort(), assetType.getValue()); if (filterArrayString != null && filterArrayString.length > 0) { url = buildUrlWithFilter(url, filterArrayString); @@ -180,11 +184,11 @@ public class AssetRestUtils extends BaseRestUtils { 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); + Map<String, String> headersMap = new HashMap<>(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), BaseRestUtils.contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), BaseRestUtils.acceptHeaderData); headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), basicAuthentication); - headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci"); + headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), BaseRestUtils.xEcompInstanceId); HttpRequest http = new HttpRequest(); @@ -217,13 +221,13 @@ public class AssetRestUtils extends BaseRestUtils { 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); + Map<String, String> headersMap = new HashMap<>(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), BaseRestUtils.contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), BaseRestUtils.acceptHeaderData); if (isBasicAuthentication) { headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), basicAuthentication); } - headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci"); + headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), BaseRestUtils.xEcompInstanceId); HttpRequest http = new HttpRequest(); String url = String.format(Urls.GET_ASSET_METADATA, config.getCatalogBeHost(), config.getCatalogBePort(), @@ -628,8 +632,5 @@ public class AssetRestUtils extends BaseRestUtils { } return null; } - private static String getShortUUID() { - return UUID.randomUUID().toString().split("-")[0]; - } } diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/AutomationUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/AutomationUtils.java index 2e27907fb5..65ab6c920a 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/AutomationUtils.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/AutomationUtils.java @@ -61,11 +61,19 @@ public class AutomationUtils extends BaseRestUtils { - public static void createVersionsInfoFile(String filepath, String onboardVersion, String osVersion, String envData, String suiteName) - throws FileNotFoundException, IOException { + public static void createVersionsInfoFile(String filepath, String onboardVersion, String osVersion, String envData, String suiteName) throws IOException { + File myFoo = new File(filepath); + FileOutputStream fooStream = new FileOutputStream(myFoo, false); // true to append + String versions = ("onboardVersion=\""+ onboardVersion+ "\"\n" + "osVersion=\"" + osVersion + "\"\n" + "env=\""+ envData + "\"\n" + "suiteName=\""+ suiteName+ "\"\n"); + byte[] myBytes = versions.getBytes(); + fooStream.write(myBytes); + fooStream.close(); + } + + public static void createVersionsInfoFile(String filepath, String onboardVersion, String osVersion, String envData, String suiteName, String reportStartTime) throws IOException { File myFoo = new File(filepath); FileOutputStream fooStream = new FileOutputStream(myFoo, false); // true to append - String versions = ("onboardVesrion=\""+ onboardVersion+ "\"\n" + "osVersion=\"" + osVersion + "\"\n" + "env=\""+ envData + "\"\n" + "suiteName=\""+ suiteName+ "\"\n"); + String versions = ("onboardVersion=\""+ onboardVersion+ "\"\n" + "osVersion=\"" + osVersion + "\"\n" + "env=\""+ envData + "\"\n" + "suiteName=\""+ suiteName+ "\"\n" + "reportStartTime=\""+ reportStartTime+ "\"\n"); byte[] myBytes = versions.getBytes(); fooStream.write(myBytes); fooStream.close(); diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/BaseRestUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/BaseRestUtils.java index 4ea404784a..4ec0353abd 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/BaseRestUtils.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/BaseRestUtils.java @@ -45,10 +45,13 @@ public class BaseRestUtils extends BaseValidationUtils { 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 acceptMultipartHeader = "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 xEcompInstanceId = "a1bd39f6-d55e-45b2-9207-156216af5cb5"; + public static final String cacheControlHeader = "no-cache"; public static final String RESOURCE_COMPONENT_TYPE = "resources"; public static final String PRODUCT_COMPONENT_TYPE = "products"; @@ -86,7 +89,7 @@ public class BaseRestUtils extends BaseValidationUtils { } protected static Map<String, String> prepareHeadersMap(String userId, String accept) { - Map<String, String> headersMap = new HashMap<String, String>(); + Map<String, String> headersMap = new HashMap<>(); if (contentTypeHeaderData != null) { headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); } @@ -257,7 +260,7 @@ public class BaseRestUtils extends BaseValidationUtils { String userCredentials = userName + ":" + password; encodeBase64 = Base64.encodeBase64(userCredentials.getBytes()); String encodedUserCredentials = authorizationPrefixString + new String(encodeBase64); - Map<String, String> authorizationHeader = new HashMap<String, String>(); + Map<String, String> authorizationHeader = new HashMap<>(); authorizationHeader.put(HttpHeaderEnum.AUTHORIZATION.getValue(), encodedUserCredentials); return authorizationHeader; } diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CatalogRestUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CatalogRestUtils.java index 449b6beca5..b09ba10df1 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CatalogRestUtils.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CatalogRestUtils.java @@ -67,7 +67,7 @@ public class CatalogRestUtils extends BaseRestUtils { 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>(); + Map<String, String> additionalHeaders = new HashMap<>(); additionalHeaders.put(HttpHeaderEnum.X_ECOMP_REQUEST_ID_HEADER.getValue(), uuid); return sendGet(url, UserRoleEnum.DESIGNER.getUserId(), additionalHeaders); diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ComponentInstanceRestUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ComponentInstanceRestUtils.java index 1b550e4fff..64b576e3e2 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ComponentInstanceRestUtils.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ComponentInstanceRestUtils.java @@ -43,7 +43,7 @@ import org.openecomp.sdc.ci.tests.utils.Utils; import com.google.gson.Gson; public class ComponentInstanceRestUtils extends BaseRestUtils { - public static String acceptHeaderDate = "application/json"; +// public static String acceptHeaderDate = "application/json"; static Config config = Config.instance(); public static Gson gson = new Gson(); @@ -87,7 +87,7 @@ public class ComponentInstanceRestUtils extends BaseRestUtils { Config config = Utils.getConfig(); - Map<String, String> headersMap = new HashMap<String, String>(); + Map<String, String> headersMap = new HashMap<>(); headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderData); headersMap.put(HttpHeaderEnum.USER_ID.getValue(), user.getUserId()); @@ -207,7 +207,7 @@ public class ComponentInstanceRestUtils extends BaseRestUtils { Config config = Utils.getConfig(); - Map<String, String> headersMap = new HashMap<String, String>(); + Map<String, String> headersMap = new HashMap<>(); headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderData); headersMap.put(HttpHeaderEnum.USER_ID.getValue(), user.getUserId()); diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ConsumerRestUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ConsumerRestUtils.java index 0aadfdbaeb..5e35327305 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ConsumerRestUtils.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ConsumerRestUtils.java @@ -20,12 +20,9 @@ package org.openecomp.sdc.ci.tests.utils.rest; -import static org.testng.AssertJUnit.assertEquals; - -import java.util.Map; - -import org.codehaus.jackson.map.DeserializationConfig; -import org.codehaus.jackson.map.ObjectMapper; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.gson.Gson; import org.openecomp.sdc.be.datatypes.elements.ConsumerDataDefinition; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.ci.tests.api.Urls; @@ -34,7 +31,9 @@ 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 java.util.Map; + +import static org.testng.AssertJUnit.assertEquals; public class ConsumerRestUtils extends BaseRestUtils { @@ -123,9 +122,8 @@ public class ConsumerRestUtils extends BaseRestUtils { String bodyToParse = restResponse.getResponse(); ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); try { - mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); ConsumerDataDefinition component = mapper.readValue(bodyToParse, ConsumerDataDefinition.class); return component; } catch (Exception e) { diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/EcompUserRestUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/EcompUserRestUtils.java index 458aa4a91c..9fdab02bb1 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/EcompUserRestUtils.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/EcompUserRestUtils.java @@ -44,8 +44,6 @@ public class EcompUserRestUtils extends BaseRestUtils { static Gson gson = new Gson(); static Logger logger = LoggerFactory.getLogger(EcompUserRestUtils.class.getName()); - static String contentTypeHeaderData = "application/json"; - static String acceptHeaderDate = "application/json"; static String ecompUsername = "12345"; static String ecompPassword = "12345"; @@ -58,9 +56,9 @@ public class EcompUserRestUtils extends BaseRestUtils { 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); + Map<String, String> headersMap = new HashMap<>(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), BaseRestUtils.contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), BaseRestUtils.acceptHeaderData); headersMap.put(HttpHeaderEnum.ECOMP_USERNAME.getValue(), ecompUsername); headersMap.put(HttpHeaderEnum.ECOMP_PASSWORD.getValue(), ecompPassword); @@ -84,9 +82,9 @@ public class EcompUserRestUtils extends BaseRestUtils { 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); + Map<String, String> headersMap = new HashMap<>(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), BaseRestUtils.contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), BaseRestUtils.acceptHeaderData); headersMap.put(HttpHeaderEnum.ECOMP_USERNAME.getValue(), ecompUsername); headersMap.put(HttpHeaderEnum.ECOMP_PASSWORD.getValue(), ecompPassword); @@ -110,9 +108,9 @@ public class EcompUserRestUtils extends BaseRestUtils { 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); + Map<String, String> headersMap = new HashMap<>(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), BaseRestUtils.contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), BaseRestUtils.acceptHeaderData); headersMap.put(HttpHeaderEnum.ECOMP_USERNAME.getValue(), ecompUsername); headersMap.put(HttpHeaderEnum.ECOMP_PASSWORD.getValue(), ecompPassword); @@ -130,9 +128,9 @@ public class EcompUserRestUtils extends BaseRestUtils { 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); + Map<String, String> headersMap = new HashMap<>(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), BaseRestUtils.contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), BaseRestUtils.acceptHeaderData); headersMap.put(HttpHeaderEnum.ECOMP_USERNAME.getValue(), ecompUsername); headersMap.put(HttpHeaderEnum.ECOMP_PASSWORD.getValue(), ecompPassword); @@ -150,9 +148,9 @@ public class EcompUserRestUtils extends BaseRestUtils { 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); + Map<String, String> headersMap = new HashMap<>(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), BaseRestUtils.contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), BaseRestUtils.acceptHeaderData); headersMap.put(HttpHeaderEnum.ECOMP_USERNAME.getValue(), ecompUsername); headersMap.put(HttpHeaderEnum.ECOMP_PASSWORD.getValue(), ecompPassword); @@ -174,9 +172,9 @@ public class EcompUserRestUtils extends BaseRestUtils { 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); + Map<String, String> headersMap = new HashMap<>(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), BaseRestUtils.contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), BaseRestUtils.acceptHeaderData); headersMap.put(HttpHeaderEnum.ECOMP_USERNAME.getValue(), ecompUsername); headersMap.put(HttpHeaderEnum.ECOMP_PASSWORD.getValue(), ecompPassword); @@ -204,9 +202,9 @@ public class EcompUserRestUtils extends BaseRestUtils { 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); + Map<String, String> headersMap = new HashMap<>(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), BaseRestUtils.contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), BaseRestUtils.acceptHeaderData); headersMap.put(HttpHeaderEnum.ECOMP_USERNAME.getValue(), ecompUsername); headersMap.put(HttpHeaderEnum.ECOMP_PASSWORD.getValue(), ecompPassword); diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/GroupRestUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/GroupRestUtils.java index d79c8e002c..f55cdbd035 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/GroupRestUtils.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/GroupRestUtils.java @@ -36,7 +36,6 @@ 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(); @@ -44,7 +43,7 @@ public class GroupRestUtils extends BaseRestUtils { Config config = Utils.getConfig(); - Map<String, String> headersMap = new HashMap<String, String>(); + Map<String, String> headersMap = new HashMap<>(); headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderData); headersMap.put(HttpHeaderEnum.USER_ID.getValue(), user.getUserId()); diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ImportRestUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ImportRestUtils.java index 0be438470d..40dc060993 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ImportRestUtils.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ImportRestUtils.java @@ -48,7 +48,6 @@ 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; @@ -61,7 +60,7 @@ 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.openecomp.sdc.common.http.client.api.HttpResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -351,7 +350,7 @@ public class ImportRestUtils extends BaseRestUtils { } } - public static RestResponseAsByteArray getCsar(String csarUid, User sdncModifierDetails) throws Exception { + public static HttpResponse<byte []> getCsar(String csarUid, User sdncModifierDetails) throws Exception { Config config = Utils.getConfig(); String url = String.format(Urls.GET_CSAR_USING_SIMULATOR, config.getCatalogBeHost(), config.getCatalogBePort(), @@ -367,17 +366,11 @@ public class ImportRestUtils extends BaseRestUtils { // System.out.println(url); // System.out.println(userBodyJson); - HttpRestClient httpRestClient = new HttpRestClient(); - for (Map.Entry<String, String> mapEntry : headersMap.entrySet()) { downloadCsarHeaders.put(mapEntry.getKey(), mapEntry.getValue()); } - RestResponseAsByteArray doGetAsByteArray = httpRestClient.doGetAsByteArray(url, downloadCsarHeaders); - // RestResponse getCsar = http.httpSendGet(url, headersMap); - - return doGetAsByteArray; - + return org.openecomp.sdc.common.http.client.api.HttpRequest.getAsByteArray(url, downloadCsarHeaders); } private static File getGroupTypeZipFile(String elementName) throws IOException { diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/LifecycleRestUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/LifecycleRestUtils.java index 39afff9022..9c0b7a89e0 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/LifecycleRestUtils.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/LifecycleRestUtils.java @@ -111,10 +111,10 @@ public class LifecycleRestUtils extends BaseRestUtils { Config config = Utils.getConfig(); String url = String.format(Urls.POST_EXTERNAL_API_CHANGE_LIFE_CYCLE_OF_ASSET, config.getCatalogBeHost(), config.getCatalogBePort(), assetTypeEnum.getValue(), assetUUID, lifeCycleStatesEnum.getState()); - Map<String, String> additionalHeaders = new HashMap<String, String>(); + Map<String, String> additionalHeaders = new HashMap<>(); additionalHeaders.put(HttpHeaderEnum.AUTHORIZATION.getValue(), authorizationHeader); - additionalHeaders.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci"); + additionalHeaders.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), BaseRestUtils.xEcompInstanceId); String jsonBody = "{\"userRemarks\": \"" + comment + "\"}"; @@ -361,7 +361,7 @@ public class LifecycleRestUtils extends BaseRestUtils { } private static Map<String, String> prepareHeadersMap(User sdncModifierDetails) { - Map<String, String> headersMap = new HashMap<String, String>(); + Map<String, String> headersMap = new HashMap<>(); headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderData); headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId()); diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/PropertyRestUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/PropertyRestUtils.java index 33704a5128..d507c2cb23 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/PropertyRestUtils.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/PropertyRestUtils.java @@ -20,32 +20,28 @@ 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.HashMap; -import java.util.List; -import java.util.Map; - +import com.google.gson.Gson; 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.ComponentInstanceInput; -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.be.model.*; import org.openecomp.sdc.ci.tests.api.Urls; import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.PropertyObject; +import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum; 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.HttpRequest; import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; import org.openecomp.sdc.common.util.GeneralUtility; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.openecomp.sdc.ci.tests.datatypes.PropertyObject; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.testng.AssertJUnit.*; import com.google.gson.Gson; @@ -69,6 +65,14 @@ public class PropertyRestUtils extends BaseRestUtils { return sendPut(url, body, user.getUserId(), acceptHeaderData); } + public static RestResponse updateGroupProperty(Component component, String groupId, String body, User user) + throws Exception { + Config config = Config.instance(); + + String url = String.format(Urls.RESOURCE_GROUP_PROPERTY, config.getCatalogBeHost(), config.getCatalogBePort(), component.getUniqueId(), groupId); + 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, @@ -337,4 +341,24 @@ public class PropertyRestUtils extends BaseRestUtils { } return declareProportiesResponse; } + + public static RestResponse updateInput(Component componentObject, PropertyObject componentInput, User sdncModifierDetails) + throws Exception { + Config config = Config.instance(); + String url = String.format(Urls.UPDATE_INPUT, config.getCatalogBeHost(), config.getCatalogBePort(), componentObject.getUniqueId()); + String userId = sdncModifierDetails.getUserId(); + Map<String, String> headersMap = prepareHeadersMap(userId); + Gson gson = new Gson(); + String userBodyJson = gson.toJson(componentInput); + 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 declareProportiesResponse = http.httpSendPost(url, userBodyJson, headersMap); + if (declareProportiesResponse.getErrorCode() == STATUS_CODE_GET_SUCCESS) { + + } + return declareProportiesResponse; + } } diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtils.java index 2f33273319..5f8eeca911 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtils.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtils.java @@ -113,15 +113,12 @@ public class ResourceRestUtils extends BaseRestUtils { 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)); + headersMap.put(HttpHeaderEnum.Content_MD5.getValue(), ArtifactRestUtils.calculateMD5(resourceImportBodyJson)); } RestResponse createResourceResponse = http.httpSendPost(url, resourceImportBodyJson, headersMap); @@ -272,7 +269,7 @@ public class ResourceRestUtils extends BaseRestUtils { Map<String, String> headersMap = prepareHeadersMap(sdncModifierDetails.getUserId()); headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), authorizationHeader); - headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci"); + headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), BaseRestUtils.xEcompInstanceId); return sendGet(url, sdncModifierDetails.getUserId(), headersMap); @@ -285,7 +282,7 @@ public class ResourceRestUtils extends BaseRestUtils { Map<String, String> headersMap = prepareHeadersMap(sdncModifierDetails.getUserId()); headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), authorizationHeader); - headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci"); + headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), BaseRestUtils.xEcompInstanceId); return sendGet(url, sdncModifierDetails.getUserId(), headersMap); @@ -298,7 +295,7 @@ public class ResourceRestUtils extends BaseRestUtils { Map<String, String> headersMap = prepareHeadersMap(sdncModifierDetails.getUserId()); headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), authorizationHeader); - headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci"); + headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), BaseRestUtils.xEcompInstanceId); return sendGet(url, sdncModifierDetails.getUserId(), headersMap); @@ -359,9 +356,9 @@ public class ResourceRestUtils extends BaseRestUtils { 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"); + Map<String, String> headersMap = new HashMap<>(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), BaseRestUtils.contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), BaseRestUtils.acceptHeaderData); headersMap.put(HttpHeaderEnum.USER_ID.getValue(), "cs0008"); return http.httpSendGet(url, headersMap); @@ -374,10 +371,10 @@ public class ResourceRestUtils extends BaseRestUtils { HttpRequest http = new HttpRequest(); String url = String.format(Urls.GET_ALL_ARTIFACTS, config.getCatalogBeHost(), config.getCatalogBePort()); - Map<String, String> headersMap = new HashMap<String, String>(); + Map<String, String> headersMap = new HashMap<>(); - headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json"); - headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json"); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), acceptJsonHeader); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptJsonHeader); headersMap.put(HttpHeaderEnum.USER_ID.getValue(), "cs0008"); return http.httpSendGet(url, headersMap); @@ -390,9 +387,9 @@ public class ResourceRestUtils extends BaseRestUtils { 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"); + Map<String, String> headersMap = new HashMap<>(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), acceptJsonHeader); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptJsonHeader); headersMap.put(HttpHeaderEnum.USER_ID.getValue(), "cs0008"); return http.httpSendGet(url, headersMap); diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtilsExternalAPI.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtilsExternalAPI.java index d9b8ec3d4b..76d2ededfc 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtilsExternalAPI.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtilsExternalAPI.java @@ -50,7 +50,7 @@ public class ResourceRestUtilsExternalAPI extends BaseRestUtils { 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.X_ECOMP_INSTANCE_ID.getValue(), BaseRestUtils.xEcompInstanceId); headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId()); HttpRequest http = new HttpRequest(); diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResponseParser.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResponseParser.java index 6f83ec9d52..d78a6c9026 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResponseParser.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResponseParser.java @@ -20,22 +20,16 @@ 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 com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.module.SimpleModule; +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 org.apache.commons.codec.binary.Base64; import org.apache.log4j.Logger; -import org.codehaus.jackson.Version; -import org.codehaus.jackson.map.DeserializationConfig; -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; @@ -44,12 +38,13 @@ 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.GroupDefinition; 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.be.model.operations.impl.PropertyOperation.PropertyConstraintJacksonDeserializer; import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails; import org.openecomp.sdc.ci.tests.datatypes.ResourceAssetStructure; import org.openecomp.sdc.ci.tests.datatypes.ResourceRespJavaObject; @@ -57,11 +52,16 @@ 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; +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 java.util.List; +import java.util.Map; public class ResponseParser { @@ -104,16 +104,25 @@ public class ResponseParser { public static String getValueFromJsonResponse(String response, String fieldName) { try { - JSONObject jsonResp = (JSONObject) JSONValue.parse(response); - Object fieldValue = jsonResp.get(fieldName); - return fieldValue.toString(); +// JSONObject jsonResp = (JSONObject) JSONValue.parse(response); + String[] split = fieldName.split(":"); + String fieldValue = response; + for(int i=0; i<split.length; i++) { + fieldValue = parser(fieldValue, split[i]); + } + return fieldValue; } catch (Exception e) { return null; } } + private static String parser(String response, String field){ + JSONObject fieldValue = (JSONObject) JSONValue.parse(response); + return fieldValue.get(field).toString(); + } + public static String getUniqueIdFromResponse(RestResponse response) { return getValueFromJsonResponse(response.getResponse(), UNIQUE_ID); } @@ -152,7 +161,7 @@ public class ResponseParser { JsonObject jObject = jElement.getAsJsonObject(); JsonArray arrayOfObjects = (JsonArray) jObject.get(resourceType); Gson gson = new Gson(); - Map<String, Object> map = new HashMap<String, Object>(); + Map<String, Object> map = new HashMap<>(); ResourceRespJavaObject jsonToJavaObject = new ResourceRespJavaObject(); for (int counter = 0; counter < arrayOfObjects.size(); counter++) { @@ -169,19 +178,19 @@ public class ResponseParser { } - 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> deserializer = new PropertyConstraintJacksonDeserialiser(); - addDeserializer(module, PropertyConstraint.class, deserializer); + private static ObjectMapper newObjectMapper() { + SimpleModule module = new SimpleModule("customDeserializationModule"); + module.addDeserializer(PropertyConstraint.class, new PropertyConstraintJacksonDeserializer()); + return new ObjectMapper() + .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .registerModule(module); + } - mapper.registerModule(module); + public static Resource convertResourceResponseToJavaObject(String response) { + ObjectMapper mapper = newObjectMapper(); Resource resource = null; try { -// TODO Andrey L. uncomment line below in case to ignore on unknown properties, not recommended - mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); resource = mapper.readValue(response, Resource.class); logger.debug(resource.toString()); @@ -199,15 +208,9 @@ public class ResponseParser { 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); + ObjectMapper mapper = newObjectMapper(); ComponentInstanceProperty propertyDefinition = null; try { - mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); propertyDefinition = mapper.readValue(response, ComponentInstanceProperty.class); logger.debug(propertyDefinition.toString()); } catch (IOException e) { @@ -216,6 +219,19 @@ public class ResponseParser { return propertyDefinition; } + public static GroupDefinition convertPropertyResponseToObject(String response) { + + ObjectMapper mapper = newObjectMapper(); + GroupDefinition groupDefinition = null; + try { + groupDefinition = mapper.readValue(response, GroupDefinition.class); + logger.debug(groupDefinition.toString()); + } catch (IOException e) { + e.printStackTrace(); + } + return groupDefinition; + } + public static String toJson(Object object) { Gson gson = new Gson(); return gson.toJson(object); @@ -225,7 +241,7 @@ public class ResponseParser { ObjectMapper mapper = new ObjectMapper(); ArtifactDefinition artifactDefinition = null; try { - mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); artifactDefinition = mapper.readValue(response, ArtifactDefinition.class); logger.debug(artifactDefinition.toString()); } catch (IOException e) { @@ -257,18 +273,10 @@ public class ResponseParser { public static <T> T parseToObjectUsingMapper(String json, Class<T> clazz) { // Generic convert - ObjectMapper mapper = new ObjectMapper(); + ObjectMapper mapper = newObjectMapper(); 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); - mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); try { object = mapper.readValue(json, clazz); - // System.out.println("Class: "+clazz.getSimpleName()+", json: - // "+json); } catch (IOException e) { e.printStackTrace(); } @@ -286,25 +294,11 @@ public class ResponseParser { 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> deserializer = new PropertyConstraintJacksonDeserialiser(); - addDeserializer(module, PropertyConstraint.class, deserializer); - - mapper.registerModule(module); + ObjectMapper mapper = newObjectMapper(); Service service = null; try { -// TODO Andrey L. uncomment line below in case to ignore on unknown properties, not recommended, added by Matvey - mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); - service = mapper.readValue(response, Service.class); logger.debug(service.toString()); } catch (IOException e) { @@ -316,18 +310,9 @@ public class ResponseParser { public static Product convertProductResponseToJavaObject(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); - + ObjectMapper mapper = newObjectMapper(); Product product = null; try { - mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); product = mapper.readValue(response, Product.class); logger.debug(product.toString()); } catch (IOException e) { @@ -339,16 +324,9 @@ public class ResponseParser { 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); + ObjectMapper mapper = newObjectMapper(); ComponentInstance componentInstance = null; try { - mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); componentInstance = mapper.readValue(response, ComponentInstance.class); logger.debug(componentInstance.toString()); } catch (IOException e) { @@ -360,7 +338,7 @@ public class ResponseParser { } public static List<String> getValuesFromJsonArray(RestResponse message) throws Exception { - List<String> artifactTypesArrayFromApi = new ArrayList<String>(); + List<String> artifactTypesArrayFromApi = new ArrayList<>(); org.json.JSONObject responseObject = new org.json.JSONObject(message.getResponse()); JSONArray jArr = responseObject.getJSONArray("artifactTypes"); @@ -392,7 +370,7 @@ public class ResponseParser { } public static List<Map<String, Object>> getAuditFromMessage(Map<String, Object> auditingMessage) { - List<Map<String, Object>> auditList = new ArrayList<Map<String, Object>>(); + List<Map<String, Object>> auditList = new ArrayList<>(); auditList.add(auditingMessage); return auditList; } @@ -425,8 +403,8 @@ public class ResponseParser { } public static List<String> getDerivedListFromJson(RestResponse res) throws JSONException { - JSONArray listFromJson = getListFromJson(res, "derivedList"); - List<String> lst = new ArrayList<String>(); + JSONArray listFromJson = getListFromJson(res, "derivedFrom"); + List<String> lst = new ArrayList<>(); for (int i = 0; i < listFromJson.length(); i++) { lst.add(listFromJson.getString(i)); } @@ -440,7 +418,7 @@ public class ResponseParser { } public static List<Map<String, Object>> getListOfMapsFromJson(RestResponse res, String field) throws Exception { - List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); + List<Map<String, Object>> list = new ArrayList<>(); JSONArray listFromJson = getListFromJson(res, field); for (int i = 0; i < listFromJson.length(); i++) { Map<String, Object> convertStringToMap = convertStringToMap(listFromJson.getString(i)); @@ -472,7 +450,7 @@ public class ResponseParser { // Map<String, ArrayList<Component>> map = new HashMap<String, // ArrayList<Component>>(); - Map<String, List<Component>> map = new HashMap<String, List<Component>>(); + Map<String, List<Component>> map = new HashMap<>(); JsonElement jElement = new JsonParser().parse(response); JsonObject jObject = jElement.getAsJsonObject(); @@ -531,7 +509,7 @@ public class ResponseParser { public static Map<Long, ServiceDistributionStatus> convertServiceDistributionStatusToObject(String response) throws ParseException { - Map<Long, ServiceDistributionStatus> serviceDistributionStatusMap = new HashMap<Long, ServiceDistributionStatus>(); + Map<Long, ServiceDistributionStatus> serviceDistributionStatusMap = new HashMap<>(); ServiceDistributionStatus serviceDistributionStatusObject = null; JsonElement jElement = new JsonParser().parse(response); @@ -551,7 +529,7 @@ public class ResponseParser { public static Map<String, String> getPropertiesNameType(RestResponse restResponse) throws JSONException { - Map<String, String> propertiesMap = new HashMap<String, String>(); + Map<String, String> propertiesMap = new HashMap<>(); JSONArray propertiesList = getListFromJson(restResponse, "properties"); for (int i = 0; i < propertiesList.length() ; i ++){ JSONObject prop = (JSONObject) JSONValue.parse(propertiesList.get(i).toString()); diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ServiceRestUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ServiceRestUtils.java index 9ba4a906c6..1d8aef6f04 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ServiceRestUtils.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ServiceRestUtils.java @@ -45,9 +45,6 @@ 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(); @@ -68,8 +65,7 @@ public class ServiceRestUtils extends BaseRestUtils { public static RestResponse markServiceToDelete(String resourceId, String userId) throws IOException { Config config = Utils.getConfig(); - String url = String.format(Urls.DELETE_SERVICE, config.getCatalogBeHost(), config.getCatalogBePort(), - resourceId); + String url = String.format(Urls.DELETE_SERVICE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceId); RestResponse sendDelete = sendDelete(url, userId); return sendDelete; @@ -79,8 +75,7 @@ public class ServiceRestUtils extends BaseRestUtils { 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); + String url = String.format(Urls.DELETE_SERVICE, config.getCatalogBeHost(), config.getCatalogBePort(), serviceId); RestResponse sendDelete = sendDelete(url, userId); deleteMarkedServices(userId); return sendDelete; @@ -177,12 +172,12 @@ public class ServiceRestUtils extends BaseRestUtils { } public static Map<String, String> prepareHeadersMap(User sdncModifierDetails, boolean isCached) { - Map<String, String> headersMap = new HashMap<String, String>(); + Map<String, String> headersMap = new HashMap<>(); if (isCached) - headersMap.put(HttpHeaderEnum.CACHE_CONTROL.getValue(), cacheControl); + headersMap.put(HttpHeaderEnum.CACHE_CONTROL.getValue(), BaseRestUtils.cacheControlHeader); - headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); - headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), BaseRestUtils.contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), BaseRestUtils.acceptHeaderData); headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId()); return headersMap; } @@ -202,7 +197,7 @@ public class ServiceRestUtils extends BaseRestUtils { String url = String.format(Urls.REJECT_DISTRIBUTION, config.getCatalogBeHost(), config.getCatalogBePort(), serviceId); String userBodyJson = gson.toJson(comment); - return sendPost(url, userBodyJson, userId, acceptHeaderData); + return sendPost(url, userBodyJson, userId, BaseRestUtils.acceptHeaderData); } @@ -268,9 +263,9 @@ public class ServiceRestUtils extends BaseRestUtils { 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"); + Map<String, String> headersMap = new HashMap<>(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), BaseRestUtils.contentTypeHeaderData); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), BaseRestUtils.acceptHeaderData); headersMap.put(HttpHeaderEnum.USER_ID.getValue(), user.getUserId()); RestResponse getResourceNotAbstarctResponse = httpRequest.httpSendGet(url, headersMap); diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/UserRestUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/UserRestUtils.java index 881e9469dd..5031391fe4 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/UserRestUtils.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/UserRestUtils.java @@ -171,7 +171,7 @@ public class UserRestUtils extends BaseRestUtils { Config config = Utils.getConfig(); - Map<String, String> headersMap = new HashMap<String, String>(); + Map<String, String> headersMap = new HashMap<>(); headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId()); @@ -189,7 +189,7 @@ public class UserRestUtils extends BaseRestUtils { Config config = Utils.getConfig(); - Map<String, String> headersMap = new HashMap<String, String>(); + Map<String, String> headersMap = new HashMap<>(); headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId()); diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ArtifactValidationUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ArtifactValidationUtils.java index a07300671f..61d340094d 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ArtifactValidationUtils.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ArtifactValidationUtils.java @@ -20,17 +20,9 @@ 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 com.fasterxml.jackson.databind.ObjectMapper; +import com.google.gson.JsonElement; +import com.google.gson.JsonParser; import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstance; @@ -44,8 +36,14 @@ 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; +import java.io.File; +import java.io.IOException; +import java.util.List; +import java.util.Map; + +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertTrue; +import static org.testng.AssertJUnit.assertTrue; public class ArtifactValidationUtils { @@ -109,16 +107,14 @@ public class ArtifactValidationUtils { counter); } - public static ESArtifactData parseArtifactRespFromES(RestResponse resResponse) - throws JsonParseException, JsonProcessingException, Exception { + public static ESArtifactData parseArtifactRespFromES(RestResponse resResponse) throws 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; + return mapper.readValue(jsourceElement.toString(), ESArtifactData.class); } diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/AuditValidationUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/AuditValidationUtils.java index 4cf712f2fc..5f5afb2126 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/AuditValidationUtils.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/AuditValidationUtils.java @@ -48,7 +48,6 @@ 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; @@ -66,7 +65,6 @@ 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; @@ -129,41 +127,18 @@ public class AuditValidationUtils { 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); + Map<String, Object> actualAuditRecords = parseAuditResourceByAction(action, null); 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()); + 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()); } - 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); + public static void validateAudit(ExpectedResourceAuditJavaObject resourceAuditJavaObject, String action, String body, boolean checkAllFields) throws Exception { + Map<String, Object> actualAuditRecords = parseAuditResourceByAction(action, null); if ((resourceAuditJavaObject.getModifierName() != null) && (resourceAuditJavaObject.getModifierUid() != null)) { resourceAuditJavaObject.setModifierUid(getModifierString(resourceAuditJavaObject.getModifierName(), @@ -171,77 +146,45 @@ public class AuditValidationUtils { } 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); + 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(actualAuditRecords, AuditJsonKeysEnum.DESCRIPTION.getAuditJsonKeyName(), resourceAuditJavaObject.getDesc()); + validateField(actualAuditRecords, AuditJsonKeysEnum.COMMENT.getAuditJsonKeyName(), resourceAuditJavaObject.getComment()); + 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 { + 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); + Map<String, Object> actualAuditRecord = parseAuditResourceByAction(action, body); validateField(actualAuditRecord, AuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action); - validateField(actualAuditRecord, AuditJsonKeysEnum.CONSUMER_ID.getAuditJsonKeyName(), - externalAuditObject.getCONSUMER_ID()); + validateField(actualAuditRecord, AuditJsonKeysEnum.CONSUMER_ID.getAuditJsonKeyName(), externalAuditObject.getCONSUMER_ID()); // TODO - validateField(actualAuditRecord, AuditJsonKeysEnum.RESOURCE_URL.getAuditJsonKeyName(), - externalAuditObject.getRESOURCE_URL()); + 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()); + 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()); + 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()); +// 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()); + validateField(actualAuditRecord, AuditJsonKeysEnum.ARTIFACT_DATA.getAuditJsonKeyName(), externalAuditObject.getARTIFACT_DATA()); } @@ -288,26 +231,19 @@ public class AuditValidationUtils { } // //Benny - public static void validateEcompConsumerAudit(ExpectedEcomConsumerAudit ecompConsumerAuditJavaObject, String action) - throws Exception { + 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()); + Map<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 { + public static void ecompConsumerAuditSuccess(String action, ConsumerDataDefinition consumerDataDefinition, User user, int status) throws Exception { ExpectedEcomConsumerAudit expectedEcomConsumerAuditJavaObject = new ExpectedEcomConsumerAudit(); expectedEcomConsumerAuditJavaObject.setAction(action); expectedEcomConsumerAuditJavaObject.setEcomUser( @@ -384,34 +320,24 @@ public class AuditValidationUtils { public static void validateAuditGetListOfUsersByRoles(ExpectedGetUserListAudit GetListOfUsersAuditJavaObject, String action) throws Exception { - Map<String, Object> map2 = new HashMap<String, Object>(); - map2 = parseAuditResourceByAction(action, null); + Map<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()); + 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 { + public static void validateAuditImport(ExpectedResourceAuditJavaObject resourceAuditJavaObject, String action) throws Exception { - Map<String, Object> map2 = new HashMap<String, Object>(); - map2 = parseAuditResourceByAction(action, null); + Map<String, Object> map2 = parseAuditResourceByAction(action, null); - resourceAuditJavaObject.setModifierUid( - getModifierString(resourceAuditJavaObject.getModifierName(), resourceAuditJavaObject.getModifierUid())); + 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.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()); @@ -420,28 +346,20 @@ public class AuditValidationUtils { } - public static void validateAuditDistribution(ExpectedResourceAuditJavaObject resourceAuditJavaObject, String action) - throws Exception { + public static void validateAuditDistribution(ExpectedResourceAuditJavaObject resourceAuditJavaObject, String action) throws Exception { - Map<String, Object> map2 = new HashMap<String, Object>(); - map2 = parseAuditResourceByAction(action, null); + Map<String, Object> map2 = parseAuditResourceByAction(action, null); - resourceAuditJavaObject.setModifierUid( - getModifierString(resourceAuditJavaObject.getModifierName(), resourceAuditJavaObject.getModifierUid())); + 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.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.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()); @@ -450,46 +368,34 @@ public class AuditValidationUtils { } // Benny - public static void validateAudit_Distribution(ExpectedResourceAuditJavaObject resourceAuditJavaObject, - String action) throws Exception { + 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.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.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 { + public void validateAuditNotification(ExpectedResourceAuditJavaObject resourceAuditJavaObject, String action) throws Exception { - Map<String, Object> map2 = new HashMap<String, Object>(); - map2 = parseAuditResourceByAction(action, null); + Map<String, Object> map2 = parseAuditResourceByAction(action, null); - resourceAuditJavaObject.setModifierUid( - getModifierString(resourceAuditJavaObject.getModifierName(), resourceAuditJavaObject.getModifierUid())); + 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.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()); @@ -498,39 +404,31 @@ public class AuditValidationUtils { } - public static void validateAudit(ExpectedDistDownloadAudit expectedDistDownloadAudit, String action) - throws Exception { + public static void validateAudit(ExpectedDistDownloadAudit expectedDistDownloadAudit, String action) throws Exception { - Map<String, Object> map2 = new HashMap<String, Object>(); - map2 = parseAuditResourceByAction(action, null); + Map<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()); + 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); + Map<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()); + 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); + Map<String, Object> map2 = parseAuditResourceByAction(action, body); validateField(map2, AuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action); validateField(map2, AuditJsonKeysEnum.RESOURCE_NAME.getAuditJsonKeyName(), expectedExternalAudit.getResourceName()); @@ -549,8 +447,7 @@ public class AuditValidationUtils { } public static void validateAuditExternalChangeAssetLifeCycle(ExpectedResourceAuditJavaObject expectedExternalAudit, String action, Map<AuditingFieldsKeysEnum, String> body) throws Exception { - Map<String, Object> map2 = new HashMap<String, Object>(); - map2 = parseAuditResourceByAction(action, body); + Map<String, Object> map2 = parseAuditResourceByAction(action, body); validateField(map2, AuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action); validateField(map2, AuditJsonKeysEnum.DESCRIPTION.getAuditJsonKeyName(), expectedExternalAudit.getDesc()); @@ -566,28 +463,20 @@ public class AuditValidationUtils { validateField(map2, AuditJsonKeysEnum.CURR_VERSION.getAuditJsonKeyName(), expectedExternalAudit.getCurrVersion()); validateField(map2, AuditJsonKeysEnum.PREV_STATE.getAuditJsonKeyName(), expectedExternalAudit.getPrevState()); validateField(map2, AuditJsonKeysEnum.CURR_STATE.getAuditJsonKeyName(), expectedExternalAudit.getCurrState()); - - - // TODO: Remove comment -// validateField(map2, AuditJsonKeysEnum.INVARIANT_UUID.getAuditJsonKeyName(), expectedExternalAudit.getINVARIANT_UUID()); + } public void validateAuditDeploy(ExpectedResourceAuditJavaObject resourceAuditJavaObject, String action) throws Exception { - Map<String, Object> map2 = new HashMap<String, Object>(); - map2 = parseAuditResourceByAction(action, null); + Map<String, Object> map2 = parseAuditResourceByAction(action, null); - resourceAuditJavaObject.setModifierUid( - getModifierString(resourceAuditJavaObject.getModifierName(), resourceAuditJavaObject.getModifierUid())); + 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.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()); @@ -598,25 +487,19 @@ public class AuditValidationUtils { public static void validateAuditProduct(ExpectedProductAudit productExpectedAudit, String action, AuditJsonKeysEnum... additionalFields) throws Exception { - Map<String, Object> map2 = new HashMap<String, Object>(); - map2 = parseAuditResourceByAction(action, null); + Map<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.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()); + 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)) { @@ -837,76 +720,6 @@ public class AuditValidationUtils { 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); @@ -955,8 +768,7 @@ public class AuditValidationUtils { expectedCatrgoryAuditJavaObject.setAction(action); expectedCatrgoryAuditJavaObject.setModifier(user.getFullName() + "(" + user.getUserId() + ")"); expectedCatrgoryAuditJavaObject.setCategoryName(categoryDataDefinition.getName()); - String subCategoryName = (subCategoryDefinition != null ? subCategoryDefinition.getName() - : Constants.EMPTY_STRING); + String subCategoryName = (subCategoryDefinition != null ? subCategoryDefinition.getName() : Constants.EMPTY_STRING); expectedCatrgoryAuditJavaObject.setSubCategoryName(subCategoryName); String groupingName = (groupingDefinition != null ? groupingDefinition.getName() : Constants.EMPTY_STRING); expectedCatrgoryAuditJavaObject.setGroupingName(groupingName); @@ -989,8 +801,7 @@ public class AuditValidationUtils { /////////////////////////// ///// BENNNNNNNNY public enum UserAuditJsonKeysEnum { - ACTION("ACTION"), MODIFIER("MODIFIER"), STATUS("STATUS"), DESC("DESCRIPTION"), USER_AFTER( - "USER_AFTER"), USER_BEFORE("USER_BEFORE"); + ACTION("ACTION"), MODIFIER("MODIFIER"), STATUS("STATUS"), DESC("DESCRIPTION"), USER_AFTER("USER_AFTER"), USER_BEFORE("USER_BEFORE"); private String auditJsonKeyName; private UserAuditJsonKeysEnum(String auditJsonKeyName) { @@ -1002,20 +813,15 @@ public class AuditValidationUtils { } } - public static void validateAddUserAudit(ExpectedUserCRUDAudit expectedAddUserAuditJavaObject, String action) - throws Exception { + 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.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()); } @@ -1029,8 +835,7 @@ public class AuditValidationUtils { expectedCatrgoryAuditJavaObject.setAction(action); expectedCatrgoryAuditJavaObject.setModifier(user.getFullName() + "(" + user.getUserId() + ")"); expectedCatrgoryAuditJavaObject.setCategoryName(categoryDataDefinition.getName()); - String subCategoryName = (subCategoryDefinition != null ? subCategoryDefinition.getName() - : Constants.EMPTY_STRING); + String subCategoryName = (subCategoryDefinition != null ? subCategoryDefinition.getName() : Constants.EMPTY_STRING); expectedCatrgoryAuditJavaObject.setSubCategoryName(subCategoryName); String groupingName = (groupingDefinition != null ? groupingDefinition.getName() : Constants.EMPTY_STRING); expectedCatrgoryAuditJavaObject.setGroupingName(groupingName); @@ -1049,14 +854,10 @@ public class AuditValidationUtils { 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()); + 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()); } @@ -1066,20 +867,13 @@ public class AuditValidationUtils { 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()); + 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) @@ -1122,60 +916,6 @@ public class AuditValidationUtils { 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) @@ -1205,144 +945,27 @@ public class AuditValidationUtils { 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>(); + Map<String, String> actionMap = new HashMap<>(); actionMap.put("ACTION", action); JSONObject actionJsonObject = new JSONObject(actionMap); - Map<String, String> uuidMap = new HashMap<String, String>(); + Map<String, String> uuidMap = new HashMap<>(); uuidMap.put("SERVICE_INSTANCE_ID", uuid); JSONObject uuidJsonObject = new JSONObject(uuidMap); - List<JSONObject> filters = new ArrayList<JSONObject>(Arrays.asList(actionJsonObject, uuidJsonObject)); + List<JSONObject> filters = new ArrayList<>(Arrays.asList(actionJsonObject, uuidJsonObject)); JSONObject body = buildElasticQueryBody(filters); return body; } - public static void validateAudit(ExpectedResourceAuditJavaObject resourceAuditJavaObject, String action) - throws Exception { + 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.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()); |