diff options
author | Idan Amit <ia096e@intl.att.com> | 2018-06-11 18:37:17 +0300 |
---|---|---|
committer | Michael Lando <ml636r@att.com> | 2018-06-13 09:40:26 +0000 |
commit | 87a2123d5ba98391499a36645122e78be9737a59 (patch) | |
tree | 9477fe204e2a53300f790683175d914a7a4ad017 | |
parent | af561a8c58022cd211fa5ff020b72307bdde1ac6 (diff) |
Raised JUnit coverage for tosca package
Raised JUnit coverage for package: sdc.be.tosca
Change-Id: Ib372b546b7ab19f1b1642d93ff58d7773d7a2d14
Issue-ID: SDC-1333
Signed-off-by: Idan Amit <ia096e@intl.att.com>
11 files changed, 4900 insertions, 1836 deletions
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CsarUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CsarUtils.java index 2cf7319633..19565ed020 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CsarUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CsarUtils.java @@ -101,7 +101,6 @@ import com.google.gson.Gson; import fj.data.Either; - /** * @author tg851x * @@ -109,1531 +108,1668 @@ import fj.data.Either; @org.springframework.stereotype.Component("csar-utils") public class CsarUtils { - private static final Logger log = LoggerFactory.getLogger(CsarUtils.class); - - @Autowired - private SdcSchemaFilesCassandraDao sdcSchemaFilesCassandraDao; - @Autowired - private ArtifactCassandraDao artifactCassandraDao; - @Autowired - private ComponentsUtils componentsUtils; - @Autowired - private ToscaExportHandler toscaExportUtils; - @Autowired - private ArtifactsBusinessLogic artifactsBusinessLogic; - @Autowired - protected ToscaOperationFacade toscaOperationFacade; - - - @javax.annotation.Resource - private ServiceBusinessLogic serviceBusinessLogic; - - private Gson gson = new Gson(); - - public static final String CONFORMANCE_LEVEL = ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel(); - public static final String SDC_VERSION = ExternalConfiguration.getAppVersion(); - - public static final Pattern UUID_NORMATIVE_NEW_VERSION = Pattern.compile("^\\d{1,}.0"); - public static final String ARTIFACTS_PATH = "Artifacts/"; - public static final String RESOURCES_PATH = "Resources/"; - public static final String INFORMATIONAL_ARTIFACTS = "Informational/"; - public static final String DEPLOYMENT_ARTIFACTS = "Deployment/"; - public static final String WORKFLOW_ARTIFACT_DIR = "Workflows"+File.separator+"BPMN"+File.separator; - public static final String DEPLOYMENT_ARTIFACTS_DIR = "Deployment"+File.separator; - - public static final String DEFINITIONS_PATH = "Definitions/"; - private static final String CSAR_META_VERSION = "1.0"; - private static final String CSAR_META_PATH_FILE_NAME = "csar.meta"; - private static final String TOSCA_META_PATH_FILE_NAME = "TOSCA-Metadata/TOSCA.meta"; - private static final String TOSCA_META_VERSION = "1.0"; - private static final String CSAR_VERSION = "1.1"; - public static final String ARTIFACTS = "Artifacts"; - public static final String DEFINITION = "Definitions"; - public static final String DEL_PATTERN = "([/\\\\]+)"; - private static String versionFirstThreeOctates; - - public static final String VFC_NODE_TYPE_ARTIFACTS_PATH_PATTERN = ARTIFACTS + DEL_PATTERN + - ImportUtils.Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + - "([\\d\\w\\_\\-\\.\\s]+)" + DEL_PATTERN + - "([\\d\\w\\_\\-\\.\\s]+)" + DEL_PATTERN + - "([\\d\\w\\_\\-\\.\\s]+)" + DEL_PATTERN + - "([\\d\\w\\_\\-\\.\\s]+)"; - - public static final String VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN = ARTIFACTS + DEL_PATTERN+ - // Artifact Group (i.e Deployment/Informational) - "([\\w\\_\\-\\.\\s]+)" + DEL_PATTERN + - // Artifact Type - "([\\w\\_\\-\\.\\s]+)" + DEL_PATTERN + - // Artifact Any File Name - ".+"; - public static final String VALID_ENGLISH_ARTIFACT_NAME = "([\\w\\_\\-\\.\\s]+)"; - public static final String SERVICE_TEMPLATE_PATH_PATTERN = DEFINITION + DEL_PATTERN+ - // Service Template File Name - "([\\w\\_\\-\\.\\s]+)"; - - public static final String ARTIFACT_CREATED_FROM_CSAR = "Artifact created from csar"; - - public CsarUtils() { - if(SDC_VERSION != null && !SDC_VERSION.isEmpty()){ - Matcher matcher = Pattern.compile("(?!\\.)(\\d+(\\.\\d+)+)(?![\\d\\.])").matcher(SDC_VERSION); - matcher.find(); - versionFirstThreeOctates = matcher.group(0); - } else { - versionFirstThreeOctates = ""; - } - } - - /** - * - * @param component - * @param getFromCS - * @param isInCertificationRequest - * @return - */ - public Either<byte[], ResponseFormat> createCsar(Component component, boolean getFromCS, boolean isInCertificationRequest) { - return createCsar(component, getFromCS, isInCertificationRequest, false); - } - - private Either<byte[], ResponseFormat> createCsar(Component component, boolean getFromCS, boolean isInCertificationRequest, boolean mockGenerator) { - final String createdBy = component.getCreatorFullName(); - - String fileName; - Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts(); - ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); - fileName = artifactDefinition.getArtifactName(); - - String toscaConformanceLevel = ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel(); - String csarBlock0 = createCsarBlock0(CSAR_META_VERSION, toscaConformanceLevel); - byte[] csarBlock0Byte = csarBlock0.getBytes(); - - final String toscaBlock0 = createToscaBlock0(TOSCA_META_VERSION, CSAR_VERSION, createdBy, fileName); - byte[] toscaBlock0Byte = toscaBlock0.getBytes(); - - Either<byte[], ResponseFormat> generateCsarZipResponse = generateCsarZip(csarBlock0Byte, toscaBlock0Byte, component, getFromCS, isInCertificationRequest, mockGenerator); - - if (generateCsarZipResponse.isRight()) { - return Either.right(generateCsarZipResponse.right().value()); - } - - return Either.left(generateCsarZipResponse.left().value()); - } - - private Either<byte[], ResponseFormat> generateCsarZip(byte[] csarBlock0Byte, byte[] toscaBlock0Byte, Component component, boolean getFromCS, boolean isInCertificationRequest, boolean mockGenerator) { - try ( - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ZipOutputStream zip = new ZipOutputStream(out); - ){ - zip.putNextEntry(new ZipEntry(CSAR_META_PATH_FILE_NAME)); - zip.write(csarBlock0Byte); - zip.putNextEntry(new ZipEntry(TOSCA_META_PATH_FILE_NAME)); - zip.write(toscaBlock0Byte); - Either<ZipOutputStream, ResponseFormat> populateZip = populateZip(component, getFromCS, zip, isInCertificationRequest, mockGenerator); - if (populateZip.isRight()) { - log.debug("Failed to populate CSAR zip file {}", populateZip.right().value()); - return Either.right(populateZip.right().value()); - } - - zip.finish(); - byte[] byteArray = out.toByteArray(); - - return Either.left(byteArray); - } catch (IOException e) { - log.debug("Failed with IOexception to create CSAR zip for component {}", component.getUniqueId(), e); - - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - return Either.right(responseFormat); - } - } - - private Either<ZipOutputStream, ResponseFormat> populateZip(Component component, boolean getFromCS, ZipOutputStream zip, boolean isInCertificationRequest, boolean mockGenerator) throws IOException { - - LifecycleStateEnum lifecycleState = component.getLifecycleState(); - String componentYaml; - Either<ToscaRepresentation, ToscaError> exportComponent; - byte[] mainYaml; - // <file name, cassandraId, component> - List<Triple<String, String, Component>> dependencies = null; - List<ImmutablePair<Component, byte[]>> generatorInputs = new LinkedList<>(); - - Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts(); - ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); - String fileName = artifactDefinition.getArtifactName(); - - if (getFromCS || !(lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) { - String cassandraId = artifactDefinition.getEsId(); - Either<byte[], ActionStatus> fromCassandra = getFromCassandra(cassandraId); - if (fromCassandra.isRight()) { - log.debug("ArtifactName {}, unique ID {}", artifactDefinition.getArtifactName(), artifactDefinition.getUniqueId()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(fromCassandra.right().value()); - return Either.right(responseFormat); - } - mainYaml = fromCassandra.left().value(); - - } else { - exportComponent = toscaExportUtils.exportComponent(component); - if (exportComponent.isRight()) { - log.debug("exportComponent failed", exportComponent.right().value()); - ActionStatus convertedFromToscaError = componentsUtils.convertFromToscaError(exportComponent.right().value()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(convertedFromToscaError); - return Either.right(responseFormat); - } - ToscaRepresentation exportResult = exportComponent.left().value(); - componentYaml = exportResult.getMainYaml(); - mainYaml = componentYaml.getBytes(); - dependencies = exportResult.getDependencies(); - } - - zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + fileName)); - zip.write(mainYaml); - //US798487 - Abstraction of complex types - if (!ModelConverter.isAtomicComponent(component)){ - log.debug("Component {} is complex - generating abstract type for it..", component.getName()); - writeComponentInterface(component, zip, fileName); - } - - generatorInputs.add(new ImmutablePair<Component, byte[]>(component, mainYaml)); - - if (dependencies == null) { - Either<ToscaTemplate, ToscaError> dependenciesRes = toscaExportUtils.getDependencies(component); - if (dependenciesRes.isRight()) { - log.debug("Failed to retrieve dependencies for component {}, error {}", component.getUniqueId(), - dependenciesRes.right().value()); - ActionStatus convertFromToscaError = componentsUtils.convertFromToscaError(dependenciesRes.right().value()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(convertFromToscaError); - return Either.right(responseFormat); - } - dependencies = dependenciesRes.left().value().getDependencies(); - } - - //UID <cassandraId,filename,component> - Map<String, ImmutableTriple<String,String, Component>> innerComponentsCache = new HashMap<>(); - - if (dependencies != null && !dependencies.isEmpty()) { - for (Triple<String, String, Component> d : dependencies) { - String cassandraId = d.getMiddle(); - Component childComponent = d.getRight(); - Either<byte[], ActionStatus> entryData = getEntryData(cassandraId, childComponent); - - if (entryData.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(entryData.right().value()); - return Either.right(responseFormat); - } - - //fill innerComponentsCache - fileName = d.getLeft(); - addComponentToCache(innerComponentsCache, cassandraId, fileName, childComponent); - addInnerComponentsToCache(innerComponentsCache, childComponent); - - byte[] content = entryData.left().value(); - generatorInputs.add(new ImmutablePair<Component, byte[]>(childComponent, content)); - } - - //add inner components to CSAR - for (Entry<String, ImmutableTriple<String, String, Component>> innerComponentTripleEntry : innerComponentsCache.entrySet()) { - - ImmutableTriple<String, String, Component> innerComponentTriple = innerComponentTripleEntry.getValue(); - - Component innerComponent = innerComponentTriple.getRight(); - String icFileName = innerComponentTriple.getMiddle(); - - // add component to zip - Either<byte[], ActionStatus> entryData = getEntryData(innerComponentTriple.getLeft(), innerComponent); - if (entryData.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(entryData.right().value()); - log.debug("Failed adding to zip component {}, error {}", innerComponentTriple.getLeft(), - entryData.right().value()); - return Either.right(responseFormat); - } - byte[] content = entryData.left().value(); - zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + icFileName)); - zip.write(content); - - // add component interface to zip - if (!ModelConverter.isAtomicComponent(innerComponent)) { - writeComponentInterface(innerComponent, zip, icFileName); - } - } - } - - //retrieve SDC.zip from Cassandra - Either<byte[], ResponseFormat> latestSchemaFilesFromCassandra = getLatestSchemaFilesFromCassandra(); - - if(latestSchemaFilesFromCassandra.isRight()){ - log.error("Error retrieving SDC Schema files from cassandra" ); - return Either.right(latestSchemaFilesFromCassandra.right().value()); - } - - //add files from retireved SDC.zip to Definitions folder in CSAR - Either<ZipOutputStream, ResponseFormat> addSchemaFilesFromCassandra = addSchemaFilesFromCassandra(zip, latestSchemaFilesFromCassandra.left().value()); - - if(addSchemaFilesFromCassandra.isRight()){ - return addSchemaFilesFromCassandra; - } - - // Artifact Generation - if (component.getComponentType() == ComponentTypeEnum.SERVICE - && isInCertificationRequest) { - - List<ArtifactDefinition> aiiArtifactList; - - Either<List<ArtifactDefinition>, ResponseFormat> handleAAIArtifacts = handleAAIArtifacts(component, mockGenerator, generatorInputs); - - if (handleAAIArtifacts.isLeft()) { - aiiArtifactList = handleAAIArtifacts.left().value(); - } else { - log.debug("AAI Artifacts handling failed"); - return Either.right(handleAAIArtifacts.right().value()); - } - - if (isInCertificationRequest) { - Either<ActionStatus, ResponseFormat> handleAllAAIArtifactsInDataModel = handleAllAAIArtifactsInDataModel( - component, aiiArtifactList, false, true); - - if (handleAllAAIArtifactsInDataModel.isRight()) { - log.debug("AAI Artifacts handling (create, update, delete) failed"); - return Either.right(handleAllAAIArtifactsInDataModel.right().value()); - } - } - - } - - Either<CsarDefinition, ResponseFormat> collectedComponentCsarDefinition = collectComponentCsarDefinition(component); - - if (collectedComponentCsarDefinition.isRight()) { - return Either.right(collectedComponentCsarDefinition.right().value()); - } - - return writeAllFilesToCsar(component, collectedComponentCsarDefinition.left().value(), zip, isInCertificationRequest); - } - - private Either<ZipOutputStream, ResponseFormat> addSchemaFilesFromCassandra(ZipOutputStream zip, byte[] schemaFileZip){ - - final int initSize = 2048; - - log.debug("Starting copy from Schema file zip to CSAR zip"); - - try (ZipInputStream zipStream = new ZipInputStream(new ByteArrayInputStream(schemaFileZip)); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - BufferedOutputStream bos = new BufferedOutputStream(out, initSize);) { - - ZipEntry entry = null; - - while ((entry = zipStream.getNextEntry()) != null) { - - String entryName = entry.getName(); - int readSize = initSize; - byte[] entryData = new byte[initSize]; - - while ((readSize = zipStream.read(entryData, 0, readSize)) != -1) { - bos.write(entryData, 0, readSize); - } - - bos.flush(); - out.flush(); - zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + entryName)); - zip.write(out.toByteArray()); - zip.flush(); - out.reset(); - } - } catch (IOException e) { - log.error("Error while writing the SDC schema file to the CSAR {}", e); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - - log.debug("Finished coppy from Schema file zip to CSAR zip"); - - return Either.left(zip); - } - - - private void addInnerComponentsToCache(Map<String, ImmutableTriple<String, String, Component>> componentCache, - Component childComponent) { - - List<ComponentInstance> instances = childComponent.getComponentInstances(); - - if(instances != null) { - instances.forEach(ci -> { - ImmutableTriple<String, String, Component> componentRecord = componentCache.get(ci.getComponentUid()); - if (componentRecord == null) { - // all resource must be only once! - Either<Resource, StorageOperationStatus> resource = toscaOperationFacade.getToscaElement(ci.getComponentUid()); - if (resource.isRight()) { - log.debug("Failed to fetch resource with id {} for instance {}"); - } - Component componentRI = resource.left().value(); - - Map<String, ArtifactDefinition> childToscaArtifacts = componentRI.getToscaArtifacts(); - ArtifactDefinition childArtifactDefinition = childToscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); - if (childArtifactDefinition != null) { - //add to cache - addComponentToCache(componentCache, childArtifactDefinition.getEsId(), childArtifactDefinition.getArtifactName(), componentRI); - } - - //if not atomic - insert inner components as well - if(!ModelConverter.isAtomicComponent(componentRI)) { - addInnerComponentsToCache(componentCache, componentRI); - } - } - }); - } - } - - private void addComponentToCache(Map<String, ImmutableTriple<String, String, Component>> componentCache, - String id, String fileName, Component component) { - - ImmutableTriple<String, String, Component> cachedComponent = componentCache.get(component.getInvariantUUID()); - if (cachedComponent == null || CommonBeUtils.compareAsdcComponentVersions(component.getVersion(), cachedComponent.getRight().getVersion())) { - componentCache.put(component.getInvariantUUID(), - new ImmutableTriple<String, String, Component>(id, fileName, component)); - - if(cachedComponent != null) { - //overwriting component with newer version - log.warn("Overwriting component invariantID {} of version {} with a newer version {}", id, cachedComponent.getRight().getVersion(), component.getVersion()); - } - } - } - - private Either<ZipOutputStream, ResponseFormat> writeComponentInterface(Component component, ZipOutputStream zip, String fileName) { - try { - Either<ToscaRepresentation, ToscaError> componentInterface = toscaExportUtils.exportComponentInterface(component); - ToscaRepresentation componentInterfaceYaml = componentInterface.left().value(); - String mainYaml = componentInterfaceYaml.getMainYaml(); - String interfaceFileName = DEFINITIONS_PATH + ToscaExportHandler.getInterfaceFilename(fileName); - - zip.putNextEntry(new ZipEntry(interfaceFileName)); - zip.write(mainYaml.getBytes()); - - } catch (Exception e) { - log.error("#writeComponentInterface - zip writing failed with error: ", e); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - - return Either.left(zip); - } - - private Either<List<ArtifactDefinition>, ResponseFormat> handleAAIArtifacts(Component component, boolean mockGenerator, List<ImmutablePair<Component, byte[]>> generatorInputs) { - - ComponentTypeEnum componentType = component.getComponentType(); - List<Artifact> generatedArtifacts; - List<ArtifactDefinition> aaiArtifacts = new LinkedList<>(); - - if (componentType == ComponentTypeEnum.SERVICE && !generatorInputs.isEmpty()) { - List<Artifact> convertedGeneratorInputs = convertToGeneratorArtifactsInput(generatorInputs); - - Either<List<Artifact>, String> generatorResponse; - - if (mockGenerator) { - generatorResponse = artifactGenerator(convertedGeneratorInputs, ArtifactType.OTHER, component); - } else { - generatorResponse = artifactGenerator(convertedGeneratorInputs, ArtifactType.AAI, component); - } - - if (generatorResponse.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.AAI_ARTIFACT_GENERATION_FAILED, component.getComponentType().getValue(), component.getName(), generatorResponse.right().value()); - return Either.right(responseFormat); - } - - generatedArtifacts = generatorResponse.left().value(); - - aaiArtifacts = convertToArtifactDefinitionFromArtifactGeneratedData(generatedArtifacts); - - } - - return Either.left(aaiArtifacts); - } - - private Either<ActionStatus, ResponseFormat> handleAllAAIArtifactsInDataModel(Component component, List<ArtifactDefinition> artifactsFromAAI, boolean shouldLock, boolean inTransaction) { - - Either<ActionStatus, ResponseFormat> handleAAIArtifactsResponse; - User lastComponentUpdater; - - List<ArtifactDefinition> aaiArtifatcsToCreate = getAAIArtifatcsForCreate(artifactsFromAAI, component); - List<ArtifactDefinition> aaiArtifatcsToDelete = getAAIArtifatcsForDelete(artifactsFromAAI, component); - List<ArtifactDefinition> aaiArtifatcsToUpdate = getAAIArtifatcsForUpdate(artifactsFromAAI, component); - - String lastUpdaterUserId = component.getLastUpdaterUserId(); - Either<User, ResponseFormat> validateUserExists = artifactsBusinessLogic.validateUserExists(lastUpdaterUserId, "CSAR creation util", true); - - if (validateUserExists.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.AAI_ARTIFACT_GENERATION_FAILED, component.getComponentType().getValue(), component.getName(), "User not found"); - return Either.right(responseFormat); - } - - lastComponentUpdater = validateUserExists.left().value(); - - handleAAIArtifactsResponse = handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToDelete, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.DELETE), lastComponentUpdater, shouldLock, - inTransaction); - - if (handleAAIArtifactsResponse.isRight()) { - return handleAAIArtifactsResponse; - } - - handleAAIArtifactsResponse = handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToCreate, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.CREATE), lastComponentUpdater, shouldLock, - inTransaction); - - if (handleAAIArtifactsResponse.isRight()) { - return handleAAIArtifactsResponse; - } - - return handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToUpdate, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.UPDATE), lastComponentUpdater, shouldLock, inTransaction); - } - - private List<ArtifactDefinition> getAAIArtifatcsForUpdate(List<ArtifactDefinition> artifactsFromAAI, Component component) { - - Set<String> componetDeploymentArtifactLables = component.getDeploymentArtifacts().keySet(); - Set<String> componetInformationalArtifactLables = component.getArtifacts().keySet(); - - return artifactsFromAAI.stream() - .filter(e -> componetDeploymentArtifactLables.contains(e.getArtifactLabel()) || componetInformationalArtifactLables.contains(e.getArtifactLabel())) - .filter(e -> checkAaiForUpdate(component, e)) - .collect(Collectors.toList()); - } - - private boolean checkAaiForUpdate(Component component, ArtifactDefinition artifactDefinition) { - ArtifactDefinition artifactDefinitionComp = component.getDeploymentArtifacts().get(artifactDefinition.getArtifactLabel()); - - if (artifactDefinitionComp == null) { - log.warn("Failed to get {} artifact", artifactDefinition.getArtifactLabel()); - return false; - } - - // Old Artifacts before the generated flag introduction if contains "aai" ignore case prefix updated - if (artifactDefinitionComp.getGenerated() == null) { - if (artifactDefinitionComp.getArtifactLabel().toLowerCase().startsWith("aai")) { - return true; - } else { - log.warn("The artifact {} flag is null but AAI prefix is abssent Not updated", artifactDefinition.getArtifactLabel()); - } - } else { - if (artifactDefinition.getGenerated()) { - return true; - } else { - log.warn("Generated artifact {} was already uploaded manually", artifactDefinition.getArtifactLabel()); - } - } - return false; - } - - private List<ArtifactDefinition> getAAIArtifatcsForDelete(List<ArtifactDefinition> artifactsFromAAI, Component component) { - - Set<String> aaiLabels = artifactsFromAAI.stream() - .map(ArtifactDefinition::getArtifactLabel) - .collect(Collectors.toSet()); - - List<ArtifactDefinition> artifactsForDeleteDeployment = component.getDeploymentArtifacts().values().stream() - // Filter Out Artifacts that are not contained in artifacts returned - // from AAI API - .filter(e -> !aaiLabels.contains(e.getArtifactLabel())) - .collect(Collectors.toList()); - - List<ArtifactDefinition> artifactsForDeleteInformational = component.getArtifacts().values().stream() - // Filter Out Artifacts that are not contained in artifacts returned - // from AAI API - .filter(e -> !aaiLabels.contains(e.getArtifactLabel())) - .collect(Collectors.toList()); - - artifactsForDeleteDeployment.addAll(artifactsForDeleteInformational); - - return artifactsForDeleteDeployment.stream() - .filter(e -> (e.getGenerated() != null && e.getGenerated().equals(Boolean.TRUE)) || (e.getGenerated() == null && e.getArtifactLabel().toLowerCase().startsWith("aai"))) - .collect(Collectors.toList()); - } - - private List<ArtifactDefinition> getAAIArtifatcsForCreate(List<ArtifactDefinition> artifactsFromAAI, Component component) { - - Set<String> componentDeploymentLabels = component.getDeploymentArtifacts().keySet(); - Set<String> componentInfoLabels = component.getArtifacts().keySet(); - - // If the artifact label does not exist in the service - - // store the artifact (generate uuid and version, "generated" flag is TRUE) - return artifactsFromAAI.stream() - .filter(e -> !componentDeploymentLabels.contains(e.getArtifactLabel()) && !componentInfoLabels.contains(e.getArtifactLabel())) - .collect(Collectors.toList()); - } - - private Either<ActionStatus, ResponseFormat> handleAAIArtifactsInDataModelByOperationType(Component component, List<ArtifactDefinition> generatedArtifactsDefinitions, ArtifactOperationInfo operationType, User user, boolean shouldLock, - boolean inTransaction) { - - String componentUniqueId = component.getUniqueId(); - ComponentTypeEnum componentType = component.getComponentType(); - - for (ArtifactDefinition artDef : generatedArtifactsDefinitions) { - String data = gson.toJson(artDef); - String dataMD5 = GeneralUtility.calculateMD5Base64EncodedByString(data); - String artifactUniqueId = null; - - if ((operationType.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE) || (operationType.getArtifactOperationEnum() == ArtifactOperationEnum.DELETE)) { - String artifactLabel = artDef.getArtifactLabel(); - ArtifactDefinition artifactDefinition = component.getDeploymentArtifacts().get(artifactLabel); - if (artifactDefinition != null) { - artifactUniqueId = artifactDefinition.getUniqueId(); - } - } - - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> validateAndHandleArtifact = artifactsBusinessLogic.validateAndHandleArtifact(componentUniqueId, componentType, operationType, artifactUniqueId, artDef, dataMD5, data, null, - null, user, component, shouldLock, inTransaction, false); - - if (validateAndHandleArtifact.isRight()) { - if (ArtifactOperationEnum.isCreateOrLink(operationType.getArtifactOperationEnum()) || ArtifactOperationEnum.UPDATE == operationType.getArtifactOperationEnum()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.AAI_ARTIFACT_GENERATION_FAILED, componentType.getValue(), component.getName(), validateAndHandleArtifact.right().value().toString()); - - Either.right(responseFormat); - } else { - log.warn("Generated artifact {} could not be deleted", artDef.getArtifactLabel()); - } - } - } - - return Either.left(ActionStatus.OK); - } - - private List<ArtifactDefinition> convertToArtifactDefinitionFromArtifactGeneratedData(List<Artifact> generatorOutput) { - List<ArtifactDefinition> artifactDefList = new LinkedList<>(); - - for (Artifact artifact : generatorOutput) { - ArtifactDefinition newEntry = new ArtifactDefinition(); - newEntry.setArtifactName(artifact.getName()); - newEntry.setArtifactType(artifact.getType()); - newEntry.setArtifactGroupType(ArtifactGroupTypeEnum.findType(artifact.getGroupType())); - newEntry.setDescription(artifact.getDescription()); - - // Normalizing the artifact label to match those stored in DB - String normalizeArtifactLabel = ValidationUtils.normalizeArtifactLabel(artifact.getLabel()); - newEntry.setArtifactLabel(normalizeArtifactLabel); - newEntry.setPayload(Base64.decodeBase64(artifact.getPayload())); - newEntry.setArtifactChecksum(artifact.getChecksum()); - // Flag that set to true in case that the artifact is generated by AI&I generator - newEntry.setGenerated(Boolean.TRUE); - - artifactDefList.add(newEntry); - } - - return artifactDefList; - } - - // List<ImmutablePair<Component, byte[] artifactBytes>> - // artifact stored by label - private List<Artifact> convertToGeneratorArtifactsInput(List<ImmutablePair<Component, byte[]>> inputs) { - List<Artifact> listOfArtifactsInput = new LinkedList<>(); - for (ImmutablePair<Component, byte[]> triple : inputs) { - Component component = triple.getLeft(); - - Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts(); - ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); - - String artifactName = artifactDefinition.getArtifactName(); - String artifactType = artifactDefinition.getArtifactType(); - String artifactGroupType = artifactDefinition.getArtifactGroupType().getType(); - String artifactDescription = artifactDefinition.getDescription(); - String artifactLabel = artifactDefinition.getArtifactLabel(); - byte[] right = triple.getRight(); - // The md5 calculated on the uncoded data - String md5Hex = DigestUtils.md5Hex(right); - byte[] payload = Base64.encodeBase64(right); - String artifactVersion = artifactDefinition.getArtifactVersion(); - - Artifact convertedArtifact = new Artifact(artifactType, artifactGroupType, md5Hex, payload); - convertedArtifact.setName(artifactName); - convertedArtifact.setDescription(artifactDescription); - convertedArtifact.setLabel(artifactLabel); - convertedArtifact.setVersion(artifactVersion); - - listOfArtifactsInput.add(convertedArtifact); - } - - return listOfArtifactsInput; - } - - private Either<byte[], ActionStatus> getEntryData(String cassandraId, Component childComponent) { - byte[] content; - if (cassandraId == null || cassandraId.isEmpty()) { - Either<ToscaRepresentation, ToscaError> exportRes = toscaExportUtils.exportComponent(childComponent); - if (exportRes.isRight()) { - log.debug("Failed to export tosca template for child component {} error {}", childComponent.getUniqueId(), exportRes.right().value()); - return Either.right(componentsUtils.convertFromToscaError(exportRes.right().value())); - } - content = exportRes.left().value().getMainYaml().getBytes(); - } else { - Either<byte[], ActionStatus> fromCassandra = getFromCassandra(cassandraId); - if (fromCassandra.isRight()) { - return Either.right(fromCassandra.right().value()); - } else { - content = fromCassandra.left().value(); - } - } - return Either.left(content); - } - - private Either<byte[], ResponseFormat> getLatestSchemaFilesFromCassandra() { - Either<List<SdcSchemaFilesData>, CassandraOperationStatus> specificSchemaFiles = sdcSchemaFilesCassandraDao.getSpecificSchemaFiles(versionFirstThreeOctates, CONFORMANCE_LEVEL); - - if(specificSchemaFiles.isRight()){ - log.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}", versionFirstThreeOctates, CONFORMANCE_LEVEL); - StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(specificSchemaFiles.right().value()); - ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(storageStatus); - return Either.right(componentsUtils.getResponseFormat(convertedFromStorageResponse)); - } - - List<SdcSchemaFilesData> listOfSchemas = specificSchemaFiles.left().value(); - - if(listOfSchemas.isEmpty()){ - log.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}", versionFirstThreeOctates, CONFORMANCE_LEVEL); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.TOSCA_SCHEMA_FILES_NOT_FOUND, versionFirstThreeOctates, CONFORMANCE_LEVEL)); - } - - SdcSchemaFilesData schemaFile = listOfSchemas.iterator().next(); - - return Either.left(schemaFile.getPayloadAsArray()); - } - - private Either<byte[], ActionStatus> getFromCassandra(String cassandraId) { - Either<ESArtifactData, CassandraOperationStatus> artifactResponse = artifactCassandraDao.getArtifact(cassandraId); - - if (artifactResponse.isRight()) { - log.debug("Failed to fetch artifact from Cassandra by id {} error {} ", cassandraId, artifactResponse.right().value()); - - StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactResponse.right().value()); - ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(storageStatus); - return Either.right(convertedFromStorageResponse); - } - ESArtifactData artifactData = artifactResponse.left().value(); - return Either.left(artifactData.getDataAsArray()); - } - - private String createCsarBlock0(String metaFileVersion, String toscaConformanceLevel) { - final String BLOCK_0_TEMPLATE = - "SDC-TOSCA-Meta-File-Version: %s\nSDC-TOSCA-Definitions-Version: %s\n"; - String readyBlock = String.format(BLOCK_0_TEMPLATE, metaFileVersion, toscaConformanceLevel); - return readyBlock; - } - - private String createToscaBlock0(String metaFileVersion, String csarVersion, String createdBy, String entryDef) { - final String block0template = "TOSCA-Meta-File-Version: %s\nCSAR-Version: %s\nCreated-By: %s\nEntry-Definitions: Definitions/%s\n\nName: csar.meta\nContent-Type: text/plain\n"; - return String.format(block0template, metaFileVersion, csarVersion, createdBy, entryDef); - } - - private Either<List<Artifact>, String> artifactGenerator(List<Artifact> artifactList, ArtifactType type, Component component) { - - ArtifactGenerationServiceImpl artifactGenerationServiceImpl = new ArtifactGenerationServiceImpl(); - ArtifactTypes artifactTypes = new ArtifactTypes(); - List<ArtifactType> artifactTypesList = new LinkedList<>(); - ArtifactType otherType; - - if (type == null) { - otherType = ArtifactType.OTHER; - } else { - otherType = type; - } - - artifactTypesList.add(otherType); - artifactTypes.setArtifactTypes(artifactTypesList); - - String configJson = gson.toJson(artifactTypes); - Map<String, String> additionalParams = new HashMap<>(); - String version; - - if (UUID_NORMATIVE_NEW_VERSION.matcher(component.getVersion()).matches() ) { - version = component.getVersion(); - } else { - String[] versionParts = component.getVersion().split(ToscaElementLifecycleOperation.VERSION_DELIMETER_REGEXP); - Integer majorVersion = Integer.parseInt(versionParts[0]); - - version = (majorVersion + 1) + ToscaElementLifecycleOperation.VERSION_DELIMETER + "0"; - } - - additionalParams.put(AdditionalParams.ServiceVersion.getName(), version); - GenerationData generatedArtifacts = artifactGenerationServiceImpl.generateArtifact(artifactList, configJson, additionalParams); - - Map<String, List<String>> errorData = generatedArtifacts.getErrorData(); - - if (!errorData.isEmpty()) { - Set<String> keySet = errorData.keySet(); - StringBuilder error = new StringBuilder(); - - for (String key : keySet) { - List<String> errorList = errorData.get(key); - log.debug("The Artifact Generator Failed - {} with following: {}", key, errorList); - error.append(key + errorList); - } - - return Either.right(error.toString()); - } - - return Either.left(generatedArtifacts.getResultData()); - } - - /** - * Extracts artifacts of VFCs from CSAR - * - * @param csar - * @return Map of <String, List<ArtifactDefinition>> the contains Lists of artifacts according vfcToscaNamespace - */ - public static Map<String, List<ArtifactDefinition>> extractVfcsArtifactsFromCsar(Map<String, byte[]> csar) { - - Map<String, List<ArtifactDefinition>> artifacts = new HashMap<>(); - if (csar != null) { - log.debug("************* Going to extract VFCs artifacts from Csar. "); - Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>(); - csar.entrySet().stream() - // filter CSAR entry by node type artifact path - .filter(e -> Pattern.compile(VFC_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey()).matches()) - // extract ArtifactDefinition from CSAR entry for each entry with matching artifact path - .forEach(e -> addExtractedVfcArtifact(extractVfcArtifact(e, collectedWarningMessages), artifacts)); - // add counter suffix to artifact labels - handleWarningMessages(collectedWarningMessages); - - } - return artifacts; - } - - /** - * Print warnings to log - * - * @param collectedWarningMessages - */ - public static void handleWarningMessages(Map<String, Set<List<String>>> collectedWarningMessages) { - collectedWarningMessages.entrySet().stream() - // for each vfc - .forEach(e -> e.getValue().stream() - // add each warning message to log - .forEach(args -> log.warn(e.getKey(), args.toArray()))); - - } - - private static void addExtractedVfcArtifact(ImmutablePair<String, ArtifactDefinition> extractedVfcArtifact, Map<String, List<ArtifactDefinition>> artifacts) { - if (extractedVfcArtifact != null) { - List<ArtifactDefinition> currArtifactsList; - String vfcToscaNamespace = extractedVfcArtifact.getKey(); - if (artifacts.containsKey(vfcToscaNamespace)) { - currArtifactsList = artifacts.get(vfcToscaNamespace); - } else { - currArtifactsList = new ArrayList<>(); - artifacts.put(vfcToscaNamespace, currArtifactsList); - } - currArtifactsList.add(extractedVfcArtifact.getValue()); - } - } - - private static ImmutablePair<String, ArtifactDefinition> extractVfcArtifact(Entry<String, byte[]> entry, Map<String, Set<List<String>>> collectedWarningMessages) { - ArtifactDefinition artifact; - String[] parsedCsarArtifactPath = entry.getKey().split("/"); - Either<ArtifactGroupTypeEnum, Boolean> eitherArtifactGroupType = detectArtifactGroupType(parsedCsarArtifactPath[2].toUpperCase(), collectedWarningMessages); - if (eitherArtifactGroupType.isLeft()) { - artifact = buildArtifactDefinitionFromCsarArtifactPath(entry, collectedWarningMessages, parsedCsarArtifactPath, eitherArtifactGroupType.left().value()); - } else { - return null; - } - return new ImmutablePair<>(parsedCsarArtifactPath[1], artifact); - } - - private static Either<ArtifactGroupTypeEnum, Boolean> detectArtifactGroupType(String groupType, Map<String, Set<List<String>>> collectedWarningMessages) { - Either<ArtifactGroupTypeEnum, Boolean> result; - try { - ArtifactGroupTypeEnum artifactGroupType = ArtifactGroupTypeEnum.findType(groupType.toUpperCase()); - if (artifactGroupType == null || (artifactGroupType != ArtifactGroupTypeEnum.INFORMATIONAL && artifactGroupType != ArtifactGroupTypeEnum.DEPLOYMENT)) { - String warningMessage = "Warning - unrecognized artifact group type {} was received."; - List<String> messageArguments = new ArrayList<>(); - messageArguments.add(groupType); - if (!collectedWarningMessages.containsKey(warningMessage)) { - Set<List<String>> messageArgumentLists = new HashSet<>(); - messageArgumentLists.add(messageArguments); - collectedWarningMessages.put(warningMessage, messageArgumentLists); - } else { - collectedWarningMessages.get(warningMessage).add(messageArguments); - } - - result = Either.right(false); - } else { - - result = Either.left(artifactGroupType); - } - } catch (Exception e) { - log.debug("detectArtifactGroupType failed with exception", e); - result = Either.right(false); - } - return result; - } - - private static ArtifactDefinition buildArtifactDefinitionFromCsarArtifactPath(Entry<String, byte[]> entry, Map<String, Set<List<String>>> collectedWarningMessages, String[] parsedCsarArtifactPath, ArtifactGroupTypeEnum artifactGroupType) { - ArtifactDefinition artifact; - artifact = new ArtifactDefinition(); - artifact.setArtifactGroupType(artifactGroupType); - artifact.setArtifactType(detectArtifactTypeVFC(artifactGroupType, parsedCsarArtifactPath[3], parsedCsarArtifactPath[1], collectedWarningMessages)); - artifact.setArtifactName(ValidationUtils.normalizeFileName(parsedCsarArtifactPath[parsedCsarArtifactPath.length - 1])); - artifact.setPayloadData(Base64.encodeBase64String(entry.getValue())); - artifact.setArtifactDisplayName(artifact.getArtifactName().lastIndexOf('.') > 0 ? artifact.getArtifactName().substring(0, artifact.getArtifactName().lastIndexOf('.')) : artifact.getArtifactName()); - artifact.setArtifactLabel(ValidationUtils.normalizeArtifactLabel(artifact.getArtifactName())); - artifact.setDescription(ARTIFACT_CREATED_FROM_CSAR); - artifact.setIsFromCsar(true); - artifact.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(entry.getValue())); - return artifact; - } - - public static final class NonMetaArtifactInfo { - private final String path; - private final String artifactName; - private final String displayName; - private final String artifactLabel; - private final ArtifactTypeEnum artifactType; - private final ArtifactGroupTypeEnum artifactGroupType; - private String payloadData; - private String artifactChecksum; - private String artifactUniqueId; - private final boolean isFromCsar; - - public NonMetaArtifactInfo(String artifactName, String path, ArtifactTypeEnum artifactType, ArtifactGroupTypeEnum artifactGroupType, byte[] payloadData, String artifactUniqueId, boolean isFromCsar) { - super(); - this.path = path; - this.isFromCsar = isFromCsar; - this.artifactName = ValidationUtils.normalizeFileName(artifactName); - this.artifactType = artifactType; - this.artifactGroupType = artifactGroupType; - final int pointIndex = artifactName.lastIndexOf('.'); - if (pointIndex > 0) { - displayName = artifactName.substring(0, pointIndex); - } else { - displayName = artifactName; - } - this.artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactName); - if (payloadData != null) { - this.payloadData = Base64.encodeBase64String(payloadData); - this.artifactChecksum = GeneralUtility.calculateMD5Base64EncodedByByteArray(payloadData); - } - this.artifactUniqueId = artifactUniqueId; - } - - public String getPath() { - return path; - } - - public String getArtifactName() { - return artifactName; - } - - public ArtifactTypeEnum getArtifactType() { - return artifactType; - } - - public String getDisplayName() { - return displayName; - } - - public ArtifactGroupTypeEnum getArtifactGroupType() { - return artifactGroupType; - } - - public String getArtifactLabel() { - return artifactLabel; - } - - public boolean isFromCsar(){ - return isFromCsar; - } - - public String getPayloadData() { - return payloadData; - } - - public String getArtifactChecksum() { - return artifactChecksum; - } - - public String getArtifactUniqueId() { - return artifactUniqueId; - } - - public void setArtifactUniqueId(String artifactUniqueId) { - this.artifactUniqueId = artifactUniqueId; - } - - } - - /** - * This method checks the artifact GroupType & Artifact Type. <br> - * if there is any problem warning messages are added to collectedWarningMessages - * - * @param artifactPath - * @param collectedWarningMessages - * @return - */ - public static Either<NonMetaArtifactInfo, Boolean> validateNonMetaArtifact(String artifactPath, byte[] payloadData, Map<String, Set<List<String>>> collectedWarningMessages) { - Either<NonMetaArtifactInfo, Boolean> ret; - try { - String[] parsedArtifactPath = artifactPath.split("/"); - // Validate Artifact Group Type - Either<ArtifactGroupTypeEnum, Boolean> eitherGroupType = detectArtifactGroupType(parsedArtifactPath[1], collectedWarningMessages); - if (eitherGroupType.isLeft()) { - final ArtifactGroupTypeEnum groupTypeEnum = eitherGroupType.left().value(); - - // Validate Artifact Type - String artifactType = parsedArtifactPath[2]; - artifactType = detectArtifactTypeVF(groupTypeEnum, artifactType, collectedWarningMessages); - - String artifactFileNameType = parsedArtifactPath[3]; - ret = Either.left(new NonMetaArtifactInfo(artifactFileNameType, artifactPath, ArtifactTypeEnum.findType(artifactType), groupTypeEnum, payloadData, null, true)); - - } else { - ret = Either.right(eitherGroupType.right().value()); - } - } catch (Exception e) { - log.debug("detectArtifactGroupType failed with exception", e); - ret = Either.right(false); - } - return ret; - - } - - private static String detectArtifactTypeVFC(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, String parentVfName, Map<String, Set<List<String>>> collectedWarningMessages) { - String warningMessage = "Warning - artifact type {} that was provided for VFC {} is not recognized."; - return detectArtifactType(artifactGroupType, receivedTypeName, warningMessage, collectedWarningMessages, parentVfName); - } - - private static String detectArtifactTypeVF(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, Map<String, Set<List<String>>> collectedWarningMessages) { - String warningMessage = "Warning - artifact type {} that was provided for VF is not recognized."; - return detectArtifactType(artifactGroupType, receivedTypeName, warningMessage, collectedWarningMessages); - } - - private static String detectArtifactType(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, String warningMessage, Map<String, Set<List<String>>> collectedWarningMessages, String... arguments) { - - ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(receivedTypeName); - Map<String, ArtifactTypeConfig> resourceValidTypeArtifacts = null; - - if(artifactGroupType != null){ - switch (artifactGroupType) { - case INFORMATIONAL: - resourceValidTypeArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration() - .getResourceInformationalArtifacts(); - break; - case DEPLOYMENT: - resourceValidTypeArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration() - .getResourceDeploymentArtifacts(); - break; - default: - break; - } - } - - Set<String> validArtifactTypes = null; - if(resourceValidTypeArtifacts != null){ - validArtifactTypes = resourceValidTypeArtifacts.keySet(); - } - - if (validArtifactTypes == null || artifactType == null || !validArtifactTypes.contains(artifactType.getType())) { - List<String> messageArguments = new ArrayList<>(); - messageArguments.add(receivedTypeName); - messageArguments.addAll(Arrays.asList(arguments)); - if (!collectedWarningMessages.containsKey(warningMessage)) { - Set<List<String>> messageArgumentLists = new HashSet<>(); - messageArgumentLists.add(messageArguments); - collectedWarningMessages.put(warningMessage, messageArgumentLists); - } else { - collectedWarningMessages.get(warningMessage).add(messageArguments); - } - } - - return artifactType == null ? ArtifactTypeEnum.OTHER.getType() : artifactType.getType(); - } - - private Either<ZipOutputStream, ResponseFormat> writeAllFilesToCsar(Component mainComponent, CsarDefinition csarDefinition, ZipOutputStream zipstream, boolean isInCertificationRequest) throws IOException{ - ComponentArtifacts componentArtifacts = csarDefinition.getComponentArtifacts(); - - Either<ZipOutputStream, ResponseFormat> writeComponentArtifactsToSpecifiedPath = writeComponentArtifactsToSpecifiedPath(mainComponent, componentArtifacts, zipstream, ARTIFACTS_PATH, isInCertificationRequest); - - if(writeComponentArtifactsToSpecifiedPath.isRight()){ - return Either.right(writeComponentArtifactsToSpecifiedPath.right().value()); - } - - ComponentTypeArtifacts mainTypeAndCIArtifacts = componentArtifacts.getMainTypeAndCIArtifacts(); - writeComponentArtifactsToSpecifiedPath = writeArtifactsInfoToSpecifiedtPath(mainComponent, mainTypeAndCIArtifacts.getComponentArtifacts(), zipstream, ARTIFACTS_PATH, isInCertificationRequest); - - if(writeComponentArtifactsToSpecifiedPath.isRight()){ - return Either.right(writeComponentArtifactsToSpecifiedPath.right().value()); - } - - Map<String, ArtifactsInfo> componentInstancesArtifacts = mainTypeAndCIArtifacts.getComponentInstancesArtifacts(); - Set<String> keySet = componentInstancesArtifacts.keySet(); - - String currentPath = ARTIFACTS_PATH + RESOURCES_PATH; - for (String keyAssetName : keySet) { - ArtifactsInfo artifactsInfo = componentInstancesArtifacts.get(keyAssetName); - String pathWithAssetName = currentPath + keyAssetName + "/"; - writeComponentArtifactsToSpecifiedPath = writeArtifactsInfoToSpecifiedtPath(mainComponent, artifactsInfo, zipstream, pathWithAssetName, isInCertificationRequest); - - if(writeComponentArtifactsToSpecifiedPath.isRight()){ - return Either.right(writeComponentArtifactsToSpecifiedPath.right().value()); - } - } - writeComponentArtifactsToSpecifiedPath = writeOperationsArtifactsToCsar(mainComponent, zipstream); - - if (writeComponentArtifactsToSpecifiedPath.isRight()) { - return Either.right(writeComponentArtifactsToSpecifiedPath.right().value()); - } - return Either.left(zipstream); - } - - private Either<ZipOutputStream, ResponseFormat> writeOperationsArtifactsToCsar(Component component, - ZipOutputStream zipstream) { - if (component instanceof Service ) { - return Either.left(zipstream); - } - if (Objects.isNull(((Resource) component).getInterfaces())) { - log.debug("Component Name {}- no interfaces found", component.getNormalizedName()); - return Either.left(zipstream); - } - final Map<String, InterfaceDefinition> interfaces = ((Resource) component).getInterfaces(); - - for (Map.Entry<String, InterfaceDefinition> interfaceEntry : interfaces.entrySet()) { - for (OperationDataDefinition operation : interfaceEntry.getValue().getOperations().values()) { - try { - if (Objects.isNull(operation.getImplementation())) { - log.debug("Component Name {}, Interface Id {}, Operation Name {} - no Operation Implementation found", - component.getNormalizedName(), interfaceEntry.getValue().getUniqueId(), - operation.getName()); - continue; - } - if (Objects.isNull(operation.getImplementation().getArtifactName())) { - log.debug("Component Name {}, Interface Id {}, Operation Name {} - no artifact found", - component.getNormalizedName(), interfaceEntry.getValue().getUniqueId(), - operation.getName()); - continue; - } - - final String artifactUUID = operation.getImplementation().getArtifactUUID(); - - final Either<byte[], ActionStatus> artifactFromCassandra = getFromCassandra(artifactUUID); - final String artifactName = operation.getImplementation().getArtifactName(); - if (artifactFromCassandra.isRight()) { - log.error("ArtifactName {}, unique ID {}", artifactName, artifactUUID); - log.error("Failed to get {} payload from DB reason: {}", artifactName, - artifactFromCassandra.right().value()); - return Either.right(componentsUtils.getResponseFormat( - ActionStatus.ARTIFACT_PAYLOAD_NOT_FOUND_DURING_CSAR_CREATION, "Resource", - component.getUniqueId(), artifactName, artifactUUID)); - } - - final byte[] payloadData = artifactFromCassandra.left().value(); - zipstream.putNextEntry(new ZipEntry(OperationArtifactUtil.createOperationArtifactPath( - component.getNormalizedName(), interfaceEntry.getValue().getToscaResourceName(), operation))); - zipstream.write(payloadData); - - } catch (IOException e) { - log.error("Component Name {}, Interface Name {}, Operation Name {}", component.getNormalizedName(), - interfaceEntry.getKey(), operation.getName()); - log.error("Error while writing the operation's artifacts to the CSAR " + "{}", e); - return Either.right(componentsUtils - .getResponseFormat(ActionStatus.ERROR_DURING_CSAR_CREATION, "Resource", - component.getUniqueId())); - } - } - } - return Either.left(zipstream); - - } - - private Either<ZipOutputStream, ResponseFormat> writeComponentArtifactsToSpecifiedPath(Component mainComponent, ComponentArtifacts componentArtifacts, ZipOutputStream zipstream, - String currentPath, boolean isInCertificationRequest) throws IOException { - Map<String, ComponentTypeArtifacts> componentTypeArtifacts = componentArtifacts.getComponentTypeArtifacts(); - //Keys are defined: - //<Inner Asset TOSCA name (e.g. VFC name)> folder name: <Inner Asset TOSCA name (e.g. VFC name)>_v<version>. - //E.g. "org.openecomp.resource.vf.vipr_atm_v1.0" - Set<String> componentTypeArtifactsKeys = componentTypeArtifacts.keySet(); - for (String keyAssetName : componentTypeArtifactsKeys) { - ComponentTypeArtifacts componentInstanceArtifacts = componentTypeArtifacts.get(keyAssetName); - ArtifactsInfo componentArtifacts2 = componentInstanceArtifacts.getComponentArtifacts(); - String pathWithAssetName = currentPath + keyAssetName + "/"; - Either<ZipOutputStream, ResponseFormat> writeArtifactsInfoToSpecifiedtPath = writeArtifactsInfoToSpecifiedtPath(mainComponent, componentArtifacts2, zipstream, pathWithAssetName, isInCertificationRequest); - - if(writeArtifactsInfoToSpecifiedtPath.isRight()){ - return writeArtifactsInfoToSpecifiedtPath; - } - } - - return Either.left(zipstream); - } - - private Either<ZipOutputStream, ResponseFormat> writeArtifactsInfoToSpecifiedtPath(Component mainComponent, ArtifactsInfo currArtifactsInfo, ZipOutputStream zip, String path, boolean isInCertificationRequest) throws IOException { - Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> artifactsInfo = currArtifactsInfo - .getArtifactsInfo(); - Set<ArtifactGroupTypeEnum> groupTypeEnumKeySet = artifactsInfo.keySet(); - - for (ArtifactGroupTypeEnum artifactGroupTypeEnum : groupTypeEnumKeySet) { - String groupTypeFolder = path + WordUtils.capitalizeFully(artifactGroupTypeEnum.getType()) + "/"; - - Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactTypesMap = artifactsInfo.get(artifactGroupTypeEnum); - Set<ArtifactTypeEnum> artifactTypeEnumKeySet = artifactTypesMap.keySet(); - - for (ArtifactTypeEnum artifactTypeEnum : artifactTypeEnumKeySet) { - List<ArtifactDefinition> artifactDefinitionList = artifactTypesMap.get(artifactTypeEnum); - String artifactTypeFolder = groupTypeFolder + artifactTypeEnum.toString() + "/"; - - Either<ZipOutputStream, ResponseFormat> writeArtifactDefinition = writeArtifactDefinition(mainComponent, zip, artifactDefinitionList, artifactTypeFolder, isInCertificationRequest); - - if(writeArtifactDefinition.isRight()){ - return writeArtifactDefinition; - } - } - } - - return Either.left(zip); - } - - private Either<ZipOutputStream, ResponseFormat> writeArtifactDefinition(Component mainComponent, ZipOutputStream zip, List<ArtifactDefinition> artifactDefinitionList, - String artifactPathAndFolder, boolean isInCertificationRequest) throws IOException { - - ComponentTypeEnum componentType = mainComponent.getComponentType(); - String heatEnvType = ArtifactTypeEnum.HEAT_ENV.getType(); - - for (ArtifactDefinition artifactDefinition : artifactDefinitionList) { - if (!isInCertificationRequest && componentType == ComponentTypeEnum.SERVICE - && artifactDefinition.getArtifactType().equals(heatEnvType) || - //this is placeholder - (artifactDefinition.getEsId() == null && artifactDefinition.getMandatory())){ - continue; - } - - byte[] payloadData = artifactDefinition.getPayloadData(); - String artifactFileName = artifactDefinition.getArtifactName(); - - if (payloadData == null) { - Either<byte[], ActionStatus> fromCassandra = getFromCassandra(artifactDefinition.getEsId()); - - if (fromCassandra.isRight()) { - log.debug("ArtifactName {}, unique ID {}", artifactDefinition.getArtifactName(), artifactDefinition.getUniqueId()); - log.debug("Failed to get {} payload from DB reason: {}", artifactFileName, fromCassandra.right().value()); - continue; - } - payloadData = fromCassandra.left().value(); - } - zip.putNextEntry(new ZipEntry(artifactPathAndFolder + artifactFileName)); - zip.write(payloadData); - } - - return Either.left(zip); - } - - /************************************ Artifacts Structure ******************************************************************/ - /** - * The artifacts Definition saved by their structure - */ - private class ArtifactsInfo { - //Key is the type of artifacts(Informational/Deployment) - //Value is a map between an artifact type and a list of all artifacts of this type - private Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> artifactsInfoField; - - public ArtifactsInfo() { - this.artifactsInfoField = new EnumMap<>(ArtifactGroupTypeEnum.class); - } - - public Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> getArtifactsInfo() { - return artifactsInfoField; - } - - public List<ArtifactDefinition> getFlatArtifactsListByType(ArtifactTypeEnum artifactType){ - List<ArtifactDefinition> artifacts = new ArrayList<>(); - for (List<ArtifactDefinition> artifactsByType:artifactsInfoField.get(artifactType).values()){ - artifacts.addAll(artifactsByType); - } - return artifacts; - } - - public void addArtifactsToGroup(ArtifactGroupTypeEnum artifactGroup,Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactsDefinition){ - artifactsInfoField.put(artifactGroup, artifactsDefinition); - } - - public boolean isEmpty() { - return artifactsInfoField.isEmpty(); - } - - } - - /** - * The artifacts of the component and of all its composed instances - * - */ - private class ComponentTypeArtifacts { - private ArtifactsInfo componentArtifacts; //component artifacts (describes the Informational Deployment folders) - private Map<String, ArtifactsInfo> componentInstancesArtifacts; //artifacts of the composed instances mapped by the resourceInstance normalized name (describes the Resources folder) - - public ComponentTypeArtifacts() { - componentArtifacts = new ArtifactsInfo(); - componentInstancesArtifacts = new HashMap<>(); - } - - public ArtifactsInfo getComponentArtifacts() { - return componentArtifacts; - } - public void setComponentArtifacts(ArtifactsInfo artifactsInfo) { - this.componentArtifacts = artifactsInfo; - } - public Map<String, ArtifactsInfo> getComponentInstancesArtifacts() { - return componentInstancesArtifacts; - } - public void setComponentInstancesArtifacts(Map<String, ArtifactsInfo> componentInstancesArtifacts) { - this.componentInstancesArtifacts = componentInstancesArtifacts; - } - - public void addComponentInstancesArtifacts(String normalizedName, ArtifactsInfo artifactsInfo) { - componentInstancesArtifacts.put(normalizedName, artifactsInfo); - } - - } - - private class ComponentArtifacts { - //artifacts of the component and CI's artifacts contained in it's composition (represents Informational, Deployment & Resource folders of main component) - private ComponentTypeArtifacts mainTypeAndCIArtifacts; - //artifacts of all component types mapped by their tosca name - private Map<String, ComponentTypeArtifacts> componentTypeArtifacts; - - public ComponentArtifacts(){ - mainTypeAndCIArtifacts = new ComponentTypeArtifacts(); - componentTypeArtifacts = new HashMap<>(); - } - - public ComponentTypeArtifacts getMainTypeAndCIArtifacts() { - return mainTypeAndCIArtifacts; - } - - public void setMainTypeAndCIArtifacts(ComponentTypeArtifacts componentInstanceArtifacts) { - this.mainTypeAndCIArtifacts = componentInstanceArtifacts; - } - - public Map<String, ComponentTypeArtifacts> getComponentTypeArtifacts() { - return componentTypeArtifacts; - } - - public void setComponentTypeArtifacts(Map<String, ComponentTypeArtifacts> componentTypeArtifacts) { - this.componentTypeArtifacts = componentTypeArtifacts; - } - } - - private class CsarDefinition { - private ComponentArtifacts componentArtifacts; - - // add list of tosca artifacts and meta describes CSAR zip root - - public CsarDefinition(ComponentArtifacts componentArtifacts) { - this.componentArtifacts = componentArtifacts; - } - - public ComponentArtifacts getComponentArtifacts() { - return componentArtifacts; - } - } - - /************************************ Artifacts Structure END******************************************************************/ - - private Either<CsarDefinition,ResponseFormat> collectComponentCsarDefinition(Component component){ - ComponentArtifacts componentArtifacts = new ComponentArtifacts(); - Component updatedComponent = component; - - //get service to receive the AII artifacts uploaded to the service - if (updatedComponent.getComponentType() == ComponentTypeEnum.SERVICE) { - Either<Service, StorageOperationStatus> getServiceResponse = toscaOperationFacade.getToscaElement(updatedComponent.getUniqueId()); - - if(getServiceResponse.isRight()){ - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getServiceResponse.right().value()); - return Either.right(componentsUtils.getResponseFormat(actionStatus)); - } - - updatedComponent = getServiceResponse.left().value(); - } - - //find the artifacts of the main component, it would have its composed instances artifacts in a separate folder - ComponentTypeArtifacts componentInstanceArtifacts = new ComponentTypeArtifacts(); - ArtifactsInfo artifactsInfo = collectComponentArtifacts(updatedComponent); - componentInstanceArtifacts.setComponentArtifacts(artifactsInfo); - componentArtifacts.setMainTypeAndCIArtifacts(componentInstanceArtifacts); - - Map<String,ComponentTypeArtifacts> resourceTypeArtifacts = componentArtifacts.getComponentTypeArtifacts(); //artifacts mapped by the component type(tosca name+version) - //get the component instances - List<ComponentInstance> componentInstances = updatedComponent.getComponentInstances(); - if (componentInstances!=null){ - for (ComponentInstance componentInstance:componentInstances){ - //call recursive to find artifacts for all the path - Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts = collectComponentInstanceArtifacts( - updatedComponent, componentInstance, resourceTypeArtifacts, componentInstanceArtifacts); - if (collectComponentInstanceArtifacts.isRight()){ - return Either.right(collectComponentInstanceArtifacts.right().value()); - } - } - } - - if(log.isDebugEnabled()){ - printResult(componentArtifacts,updatedComponent.getName()); - } - - return Either.left(new CsarDefinition(componentArtifacts)); - } - - private void printResult(ComponentArtifacts componentArtifacts, String name) { - StringBuilder result = new StringBuilder(); - result.append("Artifacts of main component " + name + "\n"); - ComponentTypeArtifacts componentInstanceArtifacts = componentArtifacts.getMainTypeAndCIArtifacts(); - printArtifacts(componentInstanceArtifacts); - result.append("Type Artifacts\n"); - for (Map.Entry<String, ComponentTypeArtifacts> typeArtifacts:componentArtifacts.getComponentTypeArtifacts().entrySet()){ - result.append("Folder " + typeArtifacts.getKey() + "\n"); - result.append(printArtifacts(typeArtifacts.getValue())); - } - - if(log.isDebugEnabled()){ - log.debug(result.toString()); - } - } - - private String printArtifacts(ComponentTypeArtifacts componentInstanceArtifacts) { - StringBuilder result = new StringBuilder(); - ArtifactsInfo artifactsInfo = componentInstanceArtifacts.getComponentArtifacts(); - Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> componetArtifacts = artifactsInfo.getArtifactsInfo(); - printArtifacts(componetArtifacts); - result = result.append("Resources\n"); - for (Map.Entry<String, ArtifactsInfo> resourceInstance:componentInstanceArtifacts.getComponentInstancesArtifacts().entrySet()){ - result.append("Folder" + resourceInstance.getKey() + "\n"); - result.append(printArtifacts(resourceInstance.getValue().getArtifactsInfo())); - } - - return result.toString(); - } - - private String printArtifacts(Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> componetArtifacts) { - StringBuilder result = new StringBuilder(); - for (Map.Entry<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> artifactGroup:componetArtifacts.entrySet()){ - result.append(" " + artifactGroup.getKey().getType()); - for (Map.Entry<ArtifactTypeEnum, List<ArtifactDefinition>> groupArtifacts:artifactGroup.getValue().entrySet()){ - result.append(" " + groupArtifacts.getKey().getType()); - for (ArtifactDefinition artifact:groupArtifacts.getValue()){ - result.append(" " + artifact.getArtifactDisplayName()); - } - } - } - - return result.toString(); - } - - private ComponentTypeArtifacts collectComponentTypeArtifacts(Map<String, ComponentTypeArtifacts> resourcesArtifacts, ComponentInstance componentInstance, - Resource fetchedComponent) { - String toscaComponentName = componentInstance.getToscaComponentName() + "_v" + componentInstance.getComponentVersion(); - - ComponentTypeArtifacts componentArtifactsInfo = resourcesArtifacts.get(toscaComponentName); - //if there are no artifacts for this component type we need to fetch and build them - if (componentArtifactsInfo==null){ - ArtifactsInfo componentArtifacts = collectComponentArtifacts(fetchedComponent); - componentArtifactsInfo = new ComponentTypeArtifacts(); - if (!componentArtifacts.isEmpty()){ - componentArtifactsInfo.setComponentArtifacts(componentArtifacts); - resourcesArtifacts.put(toscaComponentName, componentArtifactsInfo); - } - } - return componentArtifactsInfo; - } - - private Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts(Component parentComponent,ComponentInstance componentInstance, - Map<String, ComponentTypeArtifacts> resourcesTypeArtifacts,ComponentTypeArtifacts instanceArtifactsLocation) { - //1. get the component instance component - String componentUid = componentInstance.getComponentUid(); - Either<Resource, StorageOperationStatus> resource = toscaOperationFacade.getToscaElement(componentUid); - if (resource.isRight()) { - log.error("Failed to fetch resource with id {} for instance {}",componentUid, parentComponent.getUUID()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ASSET_NOT_FOUND_DURING_CSAR_CREATION, - parentComponent.getComponentType().getValue(), parentComponent.getUUID(), - componentInstance.getOriginType().getComponentType().getValue(), componentUid)); - } - Resource fetchedComponent = resource.left().value(); - - //2. fill the artifacts for the current component parent type - ComponentTypeArtifacts componentParentArtifacts = collectComponentTypeArtifacts(resourcesTypeArtifacts, componentInstance, fetchedComponent); - - //3. find the artifacts specific to the instance - Map<ArtifactTypeEnum, List<ArtifactDefinition>> componentInstanceSpecificInformationalArtifacts = - getComponentInstanceSpecificArtifacts(componentInstance.getArtifacts(), - componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), ArtifactGroupTypeEnum.INFORMATIONAL); - Map<ArtifactTypeEnum, List<ArtifactDefinition>> componentInstanceSpecificDeploymentArtifacts = - getComponentInstanceSpecificArtifacts(componentInstance.getDeploymentArtifacts(), - componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), ArtifactGroupTypeEnum.DEPLOYMENT); - - //4. add the instances artifacts to the component type - ArtifactsInfo artifactsInfo = new ArtifactsInfo(); - if (!componentInstanceSpecificInformationalArtifacts.isEmpty()){ - artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.INFORMATIONAL, componentInstanceSpecificInformationalArtifacts); - } - if (!componentInstanceSpecificDeploymentArtifacts.isEmpty()){ - artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, componentInstanceSpecificDeploymentArtifacts); - } - if (!artifactsInfo.isEmpty()){ - instanceArtifactsLocation.addComponentInstancesArtifacts(componentInstance.getNormalizedName(), artifactsInfo); - } - - //5. do the same for all the component instances - List<ComponentInstance> componentInstances = fetchedComponent.getComponentInstances(); - if (componentInstances!=null){ - for (ComponentInstance childComponentInstance:componentInstances){ - Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts = collectComponentInstanceArtifacts( - fetchedComponent, childComponentInstance, resourcesTypeArtifacts, componentParentArtifacts); - if (collectComponentInstanceArtifacts.isRight()){ - return collectComponentInstanceArtifacts; - } - } - } - - return Either.left(true); - } - - private Map<ArtifactTypeEnum, List<ArtifactDefinition>> getComponentInstanceSpecificArtifacts(Map<String, ArtifactDefinition> componentArtifacts, - Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> componentTypeArtifacts, ArtifactGroupTypeEnum artifactGroupTypeEnum) { - Map<ArtifactTypeEnum, List<ArtifactDefinition>> parentArtifacts = componentTypeArtifacts.get(artifactGroupTypeEnum); //the artfiacts of the component itself and not the instance - - Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactsByTypeOfComponentInstance = new EnumMap<>(ArtifactTypeEnum.class); - if (componentArtifacts!=null){ - for (ArtifactDefinition artifact:componentArtifacts.values()){ - ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifact.getArtifactType()); - List<ArtifactDefinition> parentArtifactsByType = null; - if (parentArtifacts!=null){ - parentArtifactsByType = parentArtifacts.get(artifactType); - } - //the artifact is of instance - if (parentArtifactsByType == null || !parentArtifactsByType.contains(artifact)){ - List<ArtifactDefinition> typeArtifacts = artifactsByTypeOfComponentInstance.get(artifactType); - if (typeArtifacts == null){ - typeArtifacts = new ArrayList<>(); - artifactsByTypeOfComponentInstance.put(artifactType, typeArtifacts); - } - typeArtifacts.add(artifact); - } - } - } - - return artifactsByTypeOfComponentInstance; - } - - private ArtifactsInfo collectComponentArtifacts(Component component) { - Map<String, ArtifactDefinition> informationalArtifacts = component.getArtifacts(); - Map<ArtifactTypeEnum, List<ArtifactDefinition>> informationalArtifactsByType = collectGroupArtifacts(informationalArtifacts); - Map<String, ArtifactDefinition> deploymentArtifacts = component.getDeploymentArtifacts(); - Map<ArtifactTypeEnum, List<ArtifactDefinition>> deploymentArtifactsByType = collectGroupArtifacts(deploymentArtifacts); - ArtifactsInfo artifactsInfo = new ArtifactsInfo(); - if (!informationalArtifactsByType.isEmpty()){ - artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.INFORMATIONAL, informationalArtifactsByType); - } - if (!deploymentArtifactsByType.isEmpty() ){ - artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, deploymentArtifactsByType); - } - - return artifactsInfo; - } - - private Map<ArtifactTypeEnum, List<ArtifactDefinition>> collectGroupArtifacts(Map<String, ArtifactDefinition> componentArtifacts) { - Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactsByType = new EnumMap<>(ArtifactTypeEnum.class); - for (ArtifactDefinition artifact:componentArtifacts.values()){ - if (artifact.getArtifactUUID()!=null){ - ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifact.getArtifactType()); - List<ArtifactDefinition> typeArtifacts = artifactsByType.get(artifactType); - if (typeArtifacts==null){ - typeArtifacts = new ArrayList<>(); - artifactsByType.put(artifactType, typeArtifacts); - } - typeArtifacts.add(artifact); - } - } - return artifactsByType; - } + private static final Logger log = LoggerFactory.getLogger(CsarUtils.class); + + @Autowired + private SdcSchemaFilesCassandraDao sdcSchemaFilesCassandraDao; + @Autowired + private ArtifactCassandraDao artifactCassandraDao; + @Autowired + private ComponentsUtils componentsUtils; + @Autowired + private ToscaExportHandler toscaExportUtils; + @Autowired + private ArtifactsBusinessLogic artifactsBusinessLogic; + @Autowired + protected ToscaOperationFacade toscaOperationFacade; + + @javax.annotation.Resource + private ServiceBusinessLogic serviceBusinessLogic; + + private Gson gson = new Gson(); + + private String CONFORMANCE_LEVEL; + private String SDC_VERSION; + + public static final Pattern UUID_NORMATIVE_NEW_VERSION = Pattern.compile("^\\d{1,}.0"); + public static final String ARTIFACTS_PATH = "Artifacts/"; + public static final String RESOURCES_PATH = "Resources/"; + public static final String INFORMATIONAL_ARTIFACTS = "Informational/"; + public static final String DEPLOYMENT_ARTIFACTS = "Deployment/"; + public static final String WORKFLOW_ARTIFACT_DIR = "Workflows" + File.separator + "BPMN" + File.separator; + public static final String DEPLOYMENT_ARTIFACTS_DIR = "Deployment" + File.separator; + + public static final String DEFINITIONS_PATH = "Definitions/"; + private static final String CSAR_META_VERSION = "1.0"; + private static final String CSAR_META_PATH_FILE_NAME = "csar.meta"; + private static final String TOSCA_META_PATH_FILE_NAME = "TOSCA-Metadata/TOSCA.meta"; + private static final String TOSCA_META_VERSION = "1.0"; + private static final String CSAR_VERSION = "1.1"; + public static final String ARTIFACTS = "Artifacts"; + public static final String DEFINITION = "Definitions"; + public static final String DEL_PATTERN = "([/\\\\]+)"; + private static String versionFirstThreeOctates; + + public static final String VFC_NODE_TYPE_ARTIFACTS_PATH_PATTERN = ARTIFACTS + DEL_PATTERN + + ImportUtils.Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + "([\\d\\w\\_\\-\\.\\s]+)" + DEL_PATTERN + + "([\\d\\w\\_\\-\\.\\s]+)" + DEL_PATTERN + "([\\d\\w\\_\\-\\.\\s]+)" + DEL_PATTERN + + "([\\d\\w\\_\\-\\.\\s]+)"; + + public static final String VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN = ARTIFACTS + DEL_PATTERN + + // Artifact Group (i.e Deployment/Informational) + "([\\w\\_\\-\\.\\s]+)" + DEL_PATTERN + + // Artifact Type + "([\\w\\_\\-\\.\\s]+)" + DEL_PATTERN + + // Artifact Any File Name + ".+"; + public static final String VALID_ENGLISH_ARTIFACT_NAME = "([\\w\\_\\-\\.\\s]+)"; + public static final String SERVICE_TEMPLATE_PATH_PATTERN = DEFINITION + DEL_PATTERN + + // Service Template File Name + "([\\w\\_\\-\\.\\s]+)"; + + public static final String ARTIFACT_CREATED_FROM_CSAR = "Artifact created from csar"; + + public CsarUtils() { + this.CONFORMANCE_LEVEL = ConfigurationManager.getConfigurationManager().getConfiguration() + .getToscaConformanceLevel(); + this.SDC_VERSION = ExternalConfiguration.getAppVersion(); + if (SDC_VERSION != null && !SDC_VERSION.isEmpty()) { + Matcher matcher = Pattern.compile("(?!\\.)(\\d+(\\.\\d+)+)(?![\\d\\.])").matcher(SDC_VERSION); + matcher.find(); + versionFirstThreeOctates = matcher.group(0); + } else { + versionFirstThreeOctates = ""; + } + } + + /** + * + * @param component + * @param getFromCS + * @param isInCertificationRequest + * @return + */ + public Either<byte[], ResponseFormat> createCsar(Component component, boolean getFromCS, + boolean isInCertificationRequest) { + return createCsar(component, getFromCS, isInCertificationRequest, false); + } + + private Either<byte[], ResponseFormat> createCsar(Component component, boolean getFromCS, + boolean isInCertificationRequest, boolean mockGenerator) { + final String createdBy = component.getCreatorFullName(); + + String fileName; + Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts(); + ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); + fileName = artifactDefinition.getArtifactName(); + + String toscaConformanceLevel = ConfigurationManager.getConfigurationManager().getConfiguration() + .getToscaConformanceLevel(); + String csarBlock0 = createCsarBlock0(CSAR_META_VERSION, toscaConformanceLevel); + byte[] csarBlock0Byte = csarBlock0.getBytes(); + + final String toscaBlock0 = createToscaBlock0(TOSCA_META_VERSION, CSAR_VERSION, createdBy, fileName); + byte[] toscaBlock0Byte = toscaBlock0.getBytes(); + + Either<byte[], ResponseFormat> generateCsarZipResponse = generateCsarZip(csarBlock0Byte, toscaBlock0Byte, + component, getFromCS, isInCertificationRequest, mockGenerator); + + if (generateCsarZipResponse.isRight()) { + return Either.right(generateCsarZipResponse.right().value()); + } + + return Either.left(generateCsarZipResponse.left().value()); + } + + private Either<byte[], ResponseFormat> generateCsarZip(byte[] csarBlock0Byte, byte[] toscaBlock0Byte, + Component component, boolean getFromCS, boolean isInCertificationRequest, boolean mockGenerator) { + try (ByteArrayOutputStream out = new ByteArrayOutputStream(); ZipOutputStream zip = new ZipOutputStream(out);) { + zip.putNextEntry(new ZipEntry(CSAR_META_PATH_FILE_NAME)); + zip.write(csarBlock0Byte); + zip.putNextEntry(new ZipEntry(TOSCA_META_PATH_FILE_NAME)); + zip.write(toscaBlock0Byte); + Either<ZipOutputStream, ResponseFormat> populateZip = populateZip(component, getFromCS, zip, + isInCertificationRequest, mockGenerator); + if (populateZip.isRight()) { + log.debug("Failed to populate CSAR zip file {}", populateZip.right().value()); + return Either.right(populateZip.right().value()); + } + + zip.finish(); + byte[] byteArray = out.toByteArray(); + + return Either.left(byteArray); + } catch (IOException | NullPointerException e) { + log.debug("Failed with IOexception to create CSAR zip for component {}", component.getUniqueId(), e); + + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + return Either.right(responseFormat); + } + } + + private Either<ZipOutputStream, ResponseFormat> populateZip(Component component, boolean getFromCS, + ZipOutputStream zip, boolean isInCertificationRequest, boolean mockGenerator) throws IOException { + + LifecycleStateEnum lifecycleState = component.getLifecycleState(); + String componentYaml; + Either<ToscaRepresentation, ToscaError> exportComponent; + byte[] mainYaml; + // <file name, cassandraId, component> + List<Triple<String, String, Component>> dependencies = null; + List<ImmutablePair<Component, byte[]>> generatorInputs = new LinkedList<>(); + + Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts(); + ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); + String fileName = artifactDefinition.getArtifactName(); + + if (getFromCS || !(lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN + || lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) { + String cassandraId = artifactDefinition.getEsId(); + Either<byte[], ActionStatus> fromCassandra = getFromCassandra(cassandraId); + if (fromCassandra.isRight()) { + log.debug("ArtifactName {}, unique ID {}", artifactDefinition.getArtifactName(), + artifactDefinition.getUniqueId()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(fromCassandra.right().value()); + return Either.right(responseFormat); + } + mainYaml = fromCassandra.left().value(); + + } else { + exportComponent = toscaExportUtils.exportComponent(component); + if (exportComponent.isRight()) { + log.debug("exportComponent failed", exportComponent.right().value()); + ActionStatus convertedFromToscaError = componentsUtils + .convertFromToscaError(exportComponent.right().value()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(convertedFromToscaError); + return Either.right(responseFormat); + } + ToscaRepresentation exportResult = exportComponent.left().value(); + componentYaml = exportResult.getMainYaml(); + mainYaml = componentYaml.getBytes(); + dependencies = exportResult.getDependencies(); + } + + zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + fileName)); + zip.write(mainYaml); + // US798487 - Abstraction of complex types + if (!ModelConverter.isAtomicComponent(component)) { + log.debug("Component {} is complex - generating abstract type for it..", component.getName()); + writeComponentInterface(component, zip, fileName); + } + + generatorInputs.add(new ImmutablePair<Component, byte[]>(component, mainYaml)); + + if (dependencies == null) { + Either<ToscaTemplate, ToscaError> dependenciesRes = toscaExportUtils.getDependencies(component); + if (dependenciesRes.isRight()) { + log.debug("Failed to retrieve dependencies for component {}, error {}", component.getUniqueId(), + dependenciesRes.right().value()); + ActionStatus convertFromToscaError = componentsUtils + .convertFromToscaError(dependenciesRes.right().value()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(convertFromToscaError); + return Either.right(responseFormat); + } + dependencies = dependenciesRes.left().value().getDependencies(); + } + + // UID <cassandraId,filename,component> + Map<String, ImmutableTriple<String, String, Component>> innerComponentsCache = new HashMap<>(); + + if (dependencies != null && !dependencies.isEmpty()) { + for (Triple<String, String, Component> d : dependencies) { + String cassandraId = d.getMiddle(); + Component childComponent = d.getRight(); + Either<byte[], ActionStatus> entryData = getEntryData(cassandraId, childComponent); + + if (entryData.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(entryData.right().value()); + return Either.right(responseFormat); + } + + // fill innerComponentsCache + fileName = d.getLeft(); + addComponentToCache(innerComponentsCache, cassandraId, fileName, childComponent); + addInnerComponentsToCache(innerComponentsCache, childComponent); + + byte[] content = entryData.left().value(); + generatorInputs.add(new ImmutablePair<Component, byte[]>(childComponent, content)); + } + + // add inner components to CSAR + for (Entry<String, ImmutableTriple<String, String, Component>> innerComponentTripleEntry : innerComponentsCache + .entrySet()) { + + ImmutableTriple<String, String, Component> innerComponentTriple = innerComponentTripleEntry.getValue(); + + Component innerComponent = innerComponentTriple.getRight(); + String icFileName = innerComponentTriple.getMiddle(); + + // add component to zip + Either<byte[], ActionStatus> entryData = getEntryData(innerComponentTriple.getLeft(), innerComponent); + if (entryData.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(entryData.right().value()); + log.debug("Failed adding to zip component {}, error {}", innerComponentTriple.getLeft(), + entryData.right().value()); + return Either.right(responseFormat); + } + byte[] content = entryData.left().value(); + zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + icFileName)); + zip.write(content); + + // add component interface to zip + if (!ModelConverter.isAtomicComponent(innerComponent)) { + writeComponentInterface(innerComponent, zip, icFileName); + } + } + } + + // retrieve SDC.zip from Cassandra + Either<byte[], ResponseFormat> latestSchemaFilesFromCassandra = getLatestSchemaFilesFromCassandra(); + + if (latestSchemaFilesFromCassandra.isRight()) { + log.error("Error retrieving SDC Schema files from cassandra"); + return Either.right(latestSchemaFilesFromCassandra.right().value()); + } + + // add files from retireved SDC.zip to Definitions folder in CSAR + Either<ZipOutputStream, ResponseFormat> addSchemaFilesFromCassandra = addSchemaFilesFromCassandra(zip, + latestSchemaFilesFromCassandra.left().value()); + + if (addSchemaFilesFromCassandra.isRight()) { + return addSchemaFilesFromCassandra; + } + + // Artifact Generation + if (component.getComponentType() == ComponentTypeEnum.SERVICE && isInCertificationRequest) { + + List<ArtifactDefinition> aiiArtifactList; + + Either<List<ArtifactDefinition>, ResponseFormat> handleAAIArtifacts = handleAAIArtifacts(component, + mockGenerator, generatorInputs); + + if (handleAAIArtifacts.isLeft()) { + aiiArtifactList = handleAAIArtifacts.left().value(); + } else { + log.debug("AAI Artifacts handling failed"); + return Either.right(handleAAIArtifacts.right().value()); + } + + if (isInCertificationRequest) { + Either<ActionStatus, ResponseFormat> handleAllAAIArtifactsInDataModel = handleAllAAIArtifactsInDataModel( + component, aiiArtifactList, false, true); + + if (handleAllAAIArtifactsInDataModel.isRight()) { + log.debug("AAI Artifacts handling (create, update, delete) failed"); + return Either.right(handleAllAAIArtifactsInDataModel.right().value()); + } + } + + } + + Either<CsarDefinition, ResponseFormat> collectedComponentCsarDefinition = collectComponentCsarDefinition( + component); + + if (collectedComponentCsarDefinition.isRight()) { + return Either.right(collectedComponentCsarDefinition.right().value()); + } + + return writeAllFilesToCsar(component, collectedComponentCsarDefinition.left().value(), zip, + isInCertificationRequest); + } + + private Either<ZipOutputStream, ResponseFormat> addSchemaFilesFromCassandra(ZipOutputStream zip, + byte[] schemaFileZip) { + + final int initSize = 2048; + + log.debug("Starting copy from Schema file zip to CSAR zip"); + + try (ZipInputStream zipStream = new ZipInputStream(new ByteArrayInputStream(schemaFileZip)); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + BufferedOutputStream bos = new BufferedOutputStream(out, initSize);) { + + ZipEntry entry = null; + + while ((entry = zipStream.getNextEntry()) != null) { + + String entryName = entry.getName(); + int readSize = initSize; + byte[] entryData = new byte[initSize]; + + while ((readSize = zipStream.read(entryData, 0, readSize)) != -1) { + bos.write(entryData, 0, readSize); + } + + bos.flush(); + out.flush(); + zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + entryName)); + zip.write(out.toByteArray()); + zip.flush(); + out.reset(); + } + } catch (IOException | NullPointerException e) { + log.error("Error while writing the SDC schema file to the CSAR {}", e); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + log.debug("Finished coppy from Schema file zip to CSAR zip"); + + return Either.left(zip); + } + + private void addInnerComponentsToCache(Map<String, ImmutableTriple<String, String, Component>> componentCache, + Component childComponent) { + + List<ComponentInstance> instances = childComponent.getComponentInstances(); + + if (instances != null) { + instances.forEach(ci -> { + ImmutableTriple<String, String, Component> componentRecord = componentCache.get(ci.getComponentUid()); + if (componentRecord == null) { + // all resource must be only once! + Either<Resource, StorageOperationStatus> resource = toscaOperationFacade + .getToscaElement(ci.getComponentUid()); + if (resource == null || resource.isRight()) { + log.debug("Failed to fetch resource with id {} for instance {}"); + } else { + Component componentRI = resource.left().value(); + + Map<String, ArtifactDefinition> childToscaArtifacts = componentRI.getToscaArtifacts(); + ArtifactDefinition childArtifactDefinition = childToscaArtifacts + .get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); + if (childArtifactDefinition != null) { + // add to cache + addComponentToCache(componentCache, childArtifactDefinition.getEsId(), + childArtifactDefinition.getArtifactName(), componentRI); + } + + // if not atomic - insert inner components as well + if (!ModelConverter.isAtomicComponent(componentRI)) { + addInnerComponentsToCache(componentCache, componentRI); + } + } + } + }); + } + } + + private void addComponentToCache(Map<String, ImmutableTriple<String, String, Component>> componentCache, String id, + String fileName, Component component) { + + ImmutableTriple<String, String, Component> cachedComponent = componentCache.get(component.getInvariantUUID()); + if (cachedComponent == null || CommonBeUtils.compareAsdcComponentVersions(component.getVersion(), + cachedComponent.getRight().getVersion())) { + componentCache.put(component.getInvariantUUID(), + new ImmutableTriple<String, String, Component>(id, fileName, component)); + + if (cachedComponent != null) { + // overwriting component with newer version + log.warn("Overwriting component invariantID {} of version {} with a newer version {}", id, + cachedComponent.getRight().getVersion(), component.getVersion()); + } + } + } + + private Either<ZipOutputStream, ResponseFormat> writeComponentInterface(Component component, ZipOutputStream zip, + String fileName) { + try { + Either<ToscaRepresentation, ToscaError> componentInterface = toscaExportUtils + .exportComponentInterface(component); + ToscaRepresentation componentInterfaceYaml = componentInterface.left().value(); + String mainYaml = componentInterfaceYaml.getMainYaml(); + String interfaceFileName = DEFINITIONS_PATH + ToscaExportHandler.getInterfaceFilename(fileName); + + zip.putNextEntry(new ZipEntry(interfaceFileName)); + zip.write(mainYaml.getBytes()); + + } catch (Exception e) { + log.error("#writeComponentInterface - zip writing failed with error: ", e); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + return Either.left(zip); + } + + private Either<List<ArtifactDefinition>, ResponseFormat> handleAAIArtifacts(Component component, + boolean mockGenerator, List<ImmutablePair<Component, byte[]>> generatorInputs) { + + ComponentTypeEnum componentType = component.getComponentType(); + List<Artifact> generatedArtifacts; + List<ArtifactDefinition> aaiArtifacts = new LinkedList<>(); + + if (componentType == ComponentTypeEnum.SERVICE && !generatorInputs.isEmpty()) { + List<Artifact> convertedGeneratorInputs = convertToGeneratorArtifactsInput(generatorInputs); + + Either<List<Artifact>, String> generatorResponse; + + if (mockGenerator) { + generatorResponse = artifactGenerator(convertedGeneratorInputs, ArtifactType.OTHER, component); + } else { + generatorResponse = artifactGenerator(convertedGeneratorInputs, ArtifactType.AAI, component); + } + + if (generatorResponse.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat( + ActionStatus.AAI_ARTIFACT_GENERATION_FAILED, component.getComponentType().getValue(), + component.getName(), generatorResponse.right().value()); + return Either.right(responseFormat); + } + + generatedArtifacts = generatorResponse.left().value(); + + aaiArtifacts = convertToArtifactDefinitionFromArtifactGeneratedData(generatedArtifacts); + + } + + return Either.left(aaiArtifacts); + } + + private Either<ActionStatus, ResponseFormat> handleAllAAIArtifactsInDataModel(Component component, + List<ArtifactDefinition> artifactsFromAAI, boolean shouldLock, boolean inTransaction) { + + Either<ActionStatus, ResponseFormat> handleAAIArtifactsResponse; + User lastComponentUpdater; + + List<ArtifactDefinition> aaiArtifatcsToCreate = getAAIArtifatcsForCreate(artifactsFromAAI, component); + List<ArtifactDefinition> aaiArtifatcsToDelete = getAAIArtifatcsForDelete(artifactsFromAAI, component); + List<ArtifactDefinition> aaiArtifatcsToUpdate = getAAIArtifatcsForUpdate(artifactsFromAAI, component); + + String lastUpdaterUserId = component.getLastUpdaterUserId(); + Either<User, ResponseFormat> validateUserExists = artifactsBusinessLogic.validateUserExists(lastUpdaterUserId, + "CSAR creation util", true); + + if (validateUserExists.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat( + ActionStatus.AAI_ARTIFACT_GENERATION_FAILED, component.getComponentType().getValue(), + component.getName(), "User not found"); + return Either.right(responseFormat); + } + + lastComponentUpdater = validateUserExists.left().value(); + + handleAAIArtifactsResponse = handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToDelete, + artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.DELETE), + lastComponentUpdater, shouldLock, inTransaction); + + if (handleAAIArtifactsResponse.isRight()) { + return handleAAIArtifactsResponse; + } + + handleAAIArtifactsResponse = handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToCreate, + artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.CREATE), + lastComponentUpdater, shouldLock, inTransaction); + + if (handleAAIArtifactsResponse.isRight()) { + return handleAAIArtifactsResponse; + } + + return handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToUpdate, + artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.UPDATE), + lastComponentUpdater, shouldLock, inTransaction); + } + + private List<ArtifactDefinition> getAAIArtifatcsForUpdate(List<ArtifactDefinition> artifactsFromAAI, + Component component) { + + Set<String> componetDeploymentArtifactLables = component.getDeploymentArtifacts().keySet(); + Set<String> componetInformationalArtifactLables = component.getArtifacts().keySet(); + + return artifactsFromAAI.stream() + .filter(e -> componetDeploymentArtifactLables.contains(e.getArtifactLabel()) + || componetInformationalArtifactLables.contains(e.getArtifactLabel())) + .filter(e -> checkAaiForUpdate(component, e)).collect(Collectors.toList()); + } + + private boolean checkAaiForUpdate(Component component, ArtifactDefinition artifactDefinition) { + ArtifactDefinition artifactDefinitionComp = component.getDeploymentArtifacts() + .get(artifactDefinition.getArtifactLabel()); + + if (artifactDefinitionComp == null) { + log.warn("Failed to get {} artifact", artifactDefinition.getArtifactLabel()); + return false; + } + + // Old Artifacts before the generated flag introduction if contains "aai" ignore + // case prefix updated + if (artifactDefinitionComp.getGenerated() == null) { + if (artifactDefinitionComp.getArtifactLabel().toLowerCase().startsWith("aai")) { + return true; + } else { + log.warn("The artifact {} flag is null but AAI prefix is abssent Not updated", + artifactDefinition.getArtifactLabel()); + } + } else { + if (artifactDefinition.getGenerated()) { + return true; + } else { + log.warn("Generated artifact {} was already uploaded manually", artifactDefinition.getArtifactLabel()); + } + } + return false; + } + + private List<ArtifactDefinition> getAAIArtifatcsForDelete(List<ArtifactDefinition> artifactsFromAAI, + Component component) { + + Set<String> aaiLabels = artifactsFromAAI.stream().map(ArtifactDefinition::getArtifactLabel) + .collect(Collectors.toSet()); + + List<ArtifactDefinition> artifactsForDeleteDeployment = component.getDeploymentArtifacts().values().stream() + // Filter Out Artifacts that are not contained in artifacts returned + // from AAI API + .filter(e -> !aaiLabels.contains(e.getArtifactLabel())).collect(Collectors.toList()); + + List<ArtifactDefinition> artifactsForDeleteInformational = component.getArtifacts().values().stream() + // Filter Out Artifacts that are not contained in artifacts returned + // from AAI API + .filter(e -> !aaiLabels.contains(e.getArtifactLabel())).collect(Collectors.toList()); + + artifactsForDeleteDeployment.addAll(artifactsForDeleteInformational); + + return artifactsForDeleteDeployment.stream() + .filter(e -> (e.getGenerated() != null && e.getGenerated().equals(Boolean.TRUE)) + || (e.getGenerated() == null && e.getArtifactLabel().toLowerCase().startsWith("aai"))) + .collect(Collectors.toList()); + } + + private List<ArtifactDefinition> getAAIArtifatcsForCreate(List<ArtifactDefinition> artifactsFromAAI, + Component component) { + + Set<String> componentDeploymentLabels = component.getDeploymentArtifacts().keySet(); + Set<String> componentInfoLabels = component.getArtifacts().keySet(); + + // If the artifact label does not exist in the service - + // store the artifact (generate uuid and version, "generated" flag is TRUE) + return artifactsFromAAI.stream().filter(e -> !componentDeploymentLabels.contains(e.getArtifactLabel()) + && !componentInfoLabels.contains(e.getArtifactLabel())).collect(Collectors.toList()); + } + + private Either<ActionStatus, ResponseFormat> handleAAIArtifactsInDataModelByOperationType(Component component, + List<ArtifactDefinition> generatedArtifactsDefinitions, ArtifactOperationInfo operationType, User user, + boolean shouldLock, boolean inTransaction) { + + String componentUniqueId = component.getUniqueId(); + ComponentTypeEnum componentType = component.getComponentType(); + Either<ActionStatus, ResponseFormat> result = Either.left(ActionStatus.OK); + + for (ArtifactDefinition artDef : generatedArtifactsDefinitions) { + String data = gson.toJson(artDef); + String dataMD5 = GeneralUtility.calculateMD5Base64EncodedByString(data); + String artifactUniqueId = null; + + if ((operationType.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE) + || (operationType.getArtifactOperationEnum() == ArtifactOperationEnum.DELETE)) { + String artifactLabel = artDef.getArtifactLabel(); + ArtifactDefinition artifactDefinition = component.getDeploymentArtifacts().get(artifactLabel); + if (artifactDefinition != null) { + artifactUniqueId = artifactDefinition.getUniqueId(); + } + } + + Either<Either<ArtifactDefinition, Operation>, ResponseFormat> validateAndHandleArtifact = artifactsBusinessLogic + .validateAndHandleArtifact(componentUniqueId, componentType, operationType, artifactUniqueId, + artDef, dataMD5, data, null, null, user, component, shouldLock, inTransaction, false); + + if (validateAndHandleArtifact.isRight()) { + if (ArtifactOperationEnum.isCreateOrLink(operationType.getArtifactOperationEnum()) + || ArtifactOperationEnum.UPDATE == operationType.getArtifactOperationEnum()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat( + ActionStatus.AAI_ARTIFACT_GENERATION_FAILED, componentType.getValue(), component.getName(), + validateAndHandleArtifact.right().value().toString()); + + result = Either.right(responseFormat); + } else { + log.warn("Generated artifact {} could not be deleted", artDef.getArtifactLabel()); + } + } + } + + return result; + } + + private List<ArtifactDefinition> convertToArtifactDefinitionFromArtifactGeneratedData( + List<Artifact> generatorOutput) { + List<ArtifactDefinition> artifactDefList = new LinkedList<>(); + + for (Artifact artifact : generatorOutput) { + ArtifactDefinition newEntry = new ArtifactDefinition(); + newEntry.setArtifactName(artifact.getName()); + newEntry.setArtifactType(artifact.getType()); + newEntry.setArtifactGroupType(ArtifactGroupTypeEnum.findType(artifact.getGroupType())); + newEntry.setDescription(artifact.getDescription()); + + // Normalizing the artifact label to match those stored in DB + String normalizeArtifactLabel = ValidationUtils.normalizeArtifactLabel(artifact.getLabel()); + newEntry.setArtifactLabel(normalizeArtifactLabel); + newEntry.setPayload(Base64.decodeBase64(artifact.getPayload())); + newEntry.setArtifactChecksum(artifact.getChecksum()); + // Flag that set to true in case that the artifact is generated by AI&I + // generator + newEntry.setGenerated(Boolean.TRUE); + + artifactDefList.add(newEntry); + } + + return artifactDefList; + } + + // List<ImmutablePair<Component, byte[] artifactBytes>> + // artifact stored by label + private List<Artifact> convertToGeneratorArtifactsInput(List<ImmutablePair<Component, byte[]>> inputs) { + List<Artifact> listOfArtifactsInput = new LinkedList<>(); + for (ImmutablePair<Component, byte[]> triple : inputs) { + Component component = triple.getLeft(); + + Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts(); + ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); + + String artifactName = artifactDefinition.getArtifactName(); + String artifactType = artifactDefinition.getArtifactType(); + String artifactGroupType = artifactDefinition.getArtifactGroupType().getType(); + String artifactDescription = artifactDefinition.getDescription(); + String artifactLabel = artifactDefinition.getArtifactLabel(); + byte[] right = triple.getRight(); + // The md5 calculated on the uncoded data + String md5Hex = DigestUtils.md5Hex(right); + byte[] payload = Base64.encodeBase64(right); + String artifactVersion = artifactDefinition.getArtifactVersion(); + + Artifact convertedArtifact = new Artifact(artifactType, artifactGroupType, md5Hex, payload); + convertedArtifact.setName(artifactName); + convertedArtifact.setDescription(artifactDescription); + convertedArtifact.setLabel(artifactLabel); + convertedArtifact.setVersion(artifactVersion); + + listOfArtifactsInput.add(convertedArtifact); + } + + return listOfArtifactsInput; + } + + private Either<byte[], ActionStatus> getEntryData(String cassandraId, Component childComponent) { + byte[] content; + if (cassandraId == null || cassandraId.isEmpty()) { + Either<ToscaRepresentation, ToscaError> exportRes = toscaExportUtils.exportComponent(childComponent); + if (exportRes.isRight()) { + log.debug("Failed to export tosca template for child component {} error {}", + childComponent.getUniqueId(), exportRes.right().value()); + return Either.right(componentsUtils.convertFromToscaError(exportRes.right().value())); + } + content = exportRes.left().value().getMainYaml().getBytes(); + } else { + Either<byte[], ActionStatus> fromCassandra = getFromCassandra(cassandraId); + if (fromCassandra.isRight()) { + return Either.right(fromCassandra.right().value()); + } else { + content = fromCassandra.left().value(); + } + } + return Either.left(content); + } + + private Either<byte[], ResponseFormat> getLatestSchemaFilesFromCassandra() { + Either<List<SdcSchemaFilesData>, CassandraOperationStatus> specificSchemaFiles = sdcSchemaFilesCassandraDao + .getSpecificSchemaFiles(versionFirstThreeOctates, CONFORMANCE_LEVEL); + + if (specificSchemaFiles.isRight()) { + log.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}", versionFirstThreeOctates, + CONFORMANCE_LEVEL); + StorageOperationStatus storageStatus = DaoStatusConverter + .convertCassandraStatusToStorageStatus(specificSchemaFiles.right().value()); + ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(storageStatus); + return Either.right(componentsUtils.getResponseFormat(convertedFromStorageResponse)); + } + + List<SdcSchemaFilesData> listOfSchemas = specificSchemaFiles.left().value(); + + if (listOfSchemas.isEmpty()) { + log.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}", versionFirstThreeOctates, + CONFORMANCE_LEVEL); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.TOSCA_SCHEMA_FILES_NOT_FOUND, + versionFirstThreeOctates, CONFORMANCE_LEVEL)); + } + + SdcSchemaFilesData schemaFile = listOfSchemas.iterator().next(); + + return Either.left(schemaFile.getPayloadAsArray()); + } + + private Either<byte[], ActionStatus> getFromCassandra(String cassandraId) { + Either<ESArtifactData, CassandraOperationStatus> artifactResponse = artifactCassandraDao + .getArtifact(cassandraId); + + if (artifactResponse.isRight()) { + log.debug("Failed to fetch artifact from Cassandra by id {} error {} ", cassandraId, + artifactResponse.right().value()); + + StorageOperationStatus storageStatus = DaoStatusConverter + .convertCassandraStatusToStorageStatus(artifactResponse.right().value()); + ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(storageStatus); + return Either.right(convertedFromStorageResponse); + } + ESArtifactData artifactData = artifactResponse.left().value(); + return Either.left(artifactData.getDataAsArray()); + } + + private String createCsarBlock0(String metaFileVersion, String toscaConformanceLevel) { + final String BLOCK_0_TEMPLATE = "SDC-TOSCA-Meta-File-Version: %s\nSDC-TOSCA-Definitions-Version: %s\n"; + String readyBlock = String.format(BLOCK_0_TEMPLATE, metaFileVersion, toscaConformanceLevel); + return readyBlock; + } + + private String createToscaBlock0(String metaFileVersion, String csarVersion, String createdBy, String entryDef) { + final String block0template = "TOSCA-Meta-File-Version: %s\nCSAR-Version: %s\nCreated-By: %s\nEntry-Definitions: Definitions/%s\n\nName: csar.meta\nContent-Type: text/plain\n"; + return String.format(block0template, metaFileVersion, csarVersion, createdBy, entryDef); + } + + private Either<List<Artifact>, String> artifactGenerator(List<Artifact> artifactList, ArtifactType type, + Component component) { + + ArtifactGenerationServiceImpl artifactGenerationServiceImpl = new ArtifactGenerationServiceImpl(); + ArtifactTypes artifactTypes = new ArtifactTypes(); + List<ArtifactType> artifactTypesList = new LinkedList<>(); + ArtifactType otherType; + + if (type == null) { + otherType = ArtifactType.OTHER; + } else { + otherType = type; + } + + artifactTypesList.add(otherType); + artifactTypes.setArtifactTypes(artifactTypesList); + + String configJson = gson.toJson(artifactTypes); + Map<String, String> additionalParams = new HashMap<>(); + String version; + + if (UUID_NORMATIVE_NEW_VERSION.matcher(component.getVersion()).matches()) { + version = component.getVersion(); + } else { + String[] versionParts = component.getVersion() + .split(ToscaElementLifecycleOperation.VERSION_DELIMETER_REGEXP); + Integer majorVersion = Integer.parseInt(versionParts[0]); + + version = (majorVersion + 1) + ToscaElementLifecycleOperation.VERSION_DELIMETER + "0"; + } + + additionalParams.put(AdditionalParams.ServiceVersion.getName(), version); + GenerationData generatedArtifacts = artifactGenerationServiceImpl.generateArtifact(artifactList, configJson, + additionalParams); + + Map<String, List<String>> errorData = generatedArtifacts.getErrorData(); + + if (!errorData.isEmpty()) { + Set<String> keySet = errorData.keySet(); + StringBuilder error = new StringBuilder(); + + for (String key : keySet) { + List<String> errorList = errorData.get(key); + log.debug("The Artifact Generator Failed - {} with following: {}", key, errorList); + error.append(key + errorList); + } + + return Either.right(error.toString()); + } + + return Either.left(generatedArtifacts.getResultData()); + } + + /** + * Extracts artifacts of VFCs from CSAR + * + * @param csar + * @return Map of <String, List<ArtifactDefinition>> the contains Lists of + * artifacts according vfcToscaNamespace + */ + public static Map<String, List<ArtifactDefinition>> extractVfcsArtifactsFromCsar(Map<String, byte[]> csar) { + + Map<String, List<ArtifactDefinition>> artifacts = new HashMap<>(); + if (csar != null) { + log.debug("************* Going to extract VFCs artifacts from Csar. "); + Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>(); + csar.entrySet().stream() + // filter CSAR entry by node type artifact path + .filter(e -> Pattern.compile(VFC_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey()).matches()) + // extract ArtifactDefinition from CSAR entry for each entry with matching + // artifact path + .forEach(e -> addExtractedVfcArtifact(extractVfcArtifact(e, collectedWarningMessages), artifacts)); + // add counter suffix to artifact labels + handleWarningMessages(collectedWarningMessages); + + } + return artifacts; + } + + /** + * Print warnings to log + * + * @param collectedWarningMessages + */ + public static void handleWarningMessages(Map<String, Set<List<String>>> collectedWarningMessages) { + collectedWarningMessages.entrySet().stream() + // for each vfc + .forEach(e -> e.getValue().stream() + // add each warning message to log + .forEach(args -> log.warn(e.getKey(), args.toArray()))); + + } + + private static void addExtractedVfcArtifact(ImmutablePair<String, ArtifactDefinition> extractedVfcArtifact, + Map<String, List<ArtifactDefinition>> artifacts) { + if (extractedVfcArtifact != null) { + List<ArtifactDefinition> currArtifactsList; + String vfcToscaNamespace = extractedVfcArtifact.getKey(); + if (artifacts.containsKey(vfcToscaNamespace)) { + currArtifactsList = artifacts.get(vfcToscaNamespace); + } else { + currArtifactsList = new ArrayList<>(); + artifacts.put(vfcToscaNamespace, currArtifactsList); + } + currArtifactsList.add(extractedVfcArtifact.getValue()); + } + } + + private static ImmutablePair<String, ArtifactDefinition> extractVfcArtifact(Entry<String, byte[]> entry, + Map<String, Set<List<String>>> collectedWarningMessages) { + ArtifactDefinition artifact; + String[] parsedCsarArtifactPath = entry.getKey().split("/"); + Either<ArtifactGroupTypeEnum, Boolean> eitherArtifactGroupType = detectArtifactGroupType( + parsedCsarArtifactPath[2].toUpperCase(), collectedWarningMessages); + if (eitherArtifactGroupType.isLeft()) { + artifact = buildArtifactDefinitionFromCsarArtifactPath(entry, collectedWarningMessages, + parsedCsarArtifactPath, eitherArtifactGroupType.left().value()); + } else { + return null; + } + return new ImmutablePair<>(parsedCsarArtifactPath[1], artifact); + } + + private static Either<ArtifactGroupTypeEnum, Boolean> detectArtifactGroupType(String groupType, + Map<String, Set<List<String>>> collectedWarningMessages) { + Either<ArtifactGroupTypeEnum, Boolean> result; + try { + ArtifactGroupTypeEnum artifactGroupType = ArtifactGroupTypeEnum.findType(groupType.toUpperCase()); + if (artifactGroupType == null || (artifactGroupType != ArtifactGroupTypeEnum.INFORMATIONAL + && artifactGroupType != ArtifactGroupTypeEnum.DEPLOYMENT)) { + String warningMessage = "Warning - unrecognized artifact group type {} was received."; + List<String> messageArguments = new ArrayList<>(); + messageArguments.add(groupType); + if (!collectedWarningMessages.containsKey(warningMessage)) { + Set<List<String>> messageArgumentLists = new HashSet<>(); + messageArgumentLists.add(messageArguments); + collectedWarningMessages.put(warningMessage, messageArgumentLists); + } else { + collectedWarningMessages.get(warningMessage).add(messageArguments); + } + + result = Either.right(false); + } else { + + result = Either.left(artifactGroupType); + } + } catch (Exception e) { + log.debug("detectArtifactGroupType failed with exception", e); + result = Either.right(false); + } + return result; + } + + private static ArtifactDefinition buildArtifactDefinitionFromCsarArtifactPath(Entry<String, byte[]> entry, + Map<String, Set<List<String>>> collectedWarningMessages, String[] parsedCsarArtifactPath, + ArtifactGroupTypeEnum artifactGroupType) { + ArtifactDefinition artifact; + artifact = new ArtifactDefinition(); + artifact.setArtifactGroupType(artifactGroupType); + artifact.setArtifactType(detectArtifactTypeVFC(artifactGroupType, parsedCsarArtifactPath[3], + parsedCsarArtifactPath[1], collectedWarningMessages)); + artifact.setArtifactName( + ValidationUtils.normalizeFileName(parsedCsarArtifactPath[parsedCsarArtifactPath.length - 1])); + artifact.setPayloadData(Base64.encodeBase64String(entry.getValue())); + artifact.setArtifactDisplayName(artifact.getArtifactName().lastIndexOf('.') > 0 + ? artifact.getArtifactName().substring(0, artifact.getArtifactName().lastIndexOf('.')) + : artifact.getArtifactName()); + artifact.setArtifactLabel(ValidationUtils.normalizeArtifactLabel(artifact.getArtifactName())); + artifact.setDescription(ARTIFACT_CREATED_FROM_CSAR); + artifact.setIsFromCsar(true); + artifact.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(entry.getValue())); + return artifact; + } + + public static final class NonMetaArtifactInfo { + private final String path; + private final String artifactName; + private final String displayName; + private final String artifactLabel; + private final ArtifactTypeEnum artifactType; + private final ArtifactGroupTypeEnum artifactGroupType; + private String payloadData; + private String artifactChecksum; + private String artifactUniqueId; + private final boolean isFromCsar; + + public NonMetaArtifactInfo(String artifactName, String path, ArtifactTypeEnum artifactType, + ArtifactGroupTypeEnum artifactGroupType, byte[] payloadData, String artifactUniqueId, + boolean isFromCsar) { + super(); + this.path = path; + this.isFromCsar = isFromCsar; + this.artifactName = ValidationUtils.normalizeFileName(artifactName); + this.artifactType = artifactType; + this.artifactGroupType = artifactGroupType; + final int pointIndex = artifactName.lastIndexOf('.'); + if (pointIndex > 0) { + displayName = artifactName.substring(0, pointIndex); + } else { + displayName = artifactName; + } + this.artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactName); + if (payloadData != null) { + this.payloadData = Base64.encodeBase64String(payloadData); + this.artifactChecksum = GeneralUtility.calculateMD5Base64EncodedByByteArray(payloadData); + } + this.artifactUniqueId = artifactUniqueId; + } + + public String getPath() { + return path; + } + + public String getArtifactName() { + return artifactName; + } + + public ArtifactTypeEnum getArtifactType() { + return artifactType; + } + + public String getDisplayName() { + return displayName; + } + + public ArtifactGroupTypeEnum getArtifactGroupType() { + return artifactGroupType; + } + + public String getArtifactLabel() { + return artifactLabel; + } + + public boolean isFromCsar() { + return isFromCsar; + } + + public String getPayloadData() { + return payloadData; + } + + public String getArtifactChecksum() { + return artifactChecksum; + } + + public String getArtifactUniqueId() { + return artifactUniqueId; + } + + public void setArtifactUniqueId(String artifactUniqueId) { + this.artifactUniqueId = artifactUniqueId; + } + + } + + /** + * This method checks the artifact GroupType & Artifact Type. <br> + * if there is any problem warning messages are added to + * collectedWarningMessages + * + * @param artifactPath + * @param collectedWarningMessages + * @return + */ + public static Either<NonMetaArtifactInfo, Boolean> validateNonMetaArtifact(String artifactPath, byte[] payloadData, + Map<String, Set<List<String>>> collectedWarningMessages) { + Either<NonMetaArtifactInfo, Boolean> ret; + try { + String[] parsedArtifactPath = artifactPath.split("/"); + // Validate Artifact Group Type + Either<ArtifactGroupTypeEnum, Boolean> eitherGroupType = detectArtifactGroupType(parsedArtifactPath[1], + collectedWarningMessages); + if (eitherGroupType.isLeft()) { + final ArtifactGroupTypeEnum groupTypeEnum = eitherGroupType.left().value(); + + // Validate Artifact Type + String artifactType = parsedArtifactPath[2]; + artifactType = detectArtifactTypeVF(groupTypeEnum, artifactType, collectedWarningMessages); + + String artifactFileNameType = parsedArtifactPath[3]; + ret = Either.left(new NonMetaArtifactInfo(artifactFileNameType, artifactPath, + ArtifactTypeEnum.findType(artifactType), groupTypeEnum, payloadData, null, true)); + + } else { + ret = Either.right(eitherGroupType.right().value()); + } + } catch (Exception e) { + log.debug("detectArtifactGroupType failed with exception", e); + ret = Either.right(false); + } + return ret; + + } + + private static String detectArtifactTypeVFC(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, + String parentVfName, Map<String, Set<List<String>>> collectedWarningMessages) { + String warningMessage = "Warning - artifact type {} that was provided for VFC {} is not recognized."; + return detectArtifactType(artifactGroupType, receivedTypeName, warningMessage, collectedWarningMessages, + parentVfName); + } + + private static String detectArtifactTypeVF(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, + Map<String, Set<List<String>>> collectedWarningMessages) { + String warningMessage = "Warning - artifact type {} that was provided for VF is not recognized."; + return detectArtifactType(artifactGroupType, receivedTypeName, warningMessage, collectedWarningMessages); + } + + private static String detectArtifactType(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, + String warningMessage, Map<String, Set<List<String>>> collectedWarningMessages, String... arguments) { + + ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(receivedTypeName); + Map<String, ArtifactTypeConfig> resourceValidTypeArtifacts = null; + + if (artifactGroupType != null) { + switch (artifactGroupType) { + case INFORMATIONAL: + resourceValidTypeArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration() + .getResourceInformationalArtifacts(); + break; + case DEPLOYMENT: + resourceValidTypeArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration() + .getResourceDeploymentArtifacts(); + break; + default: + break; + } + } + + Set<String> validArtifactTypes = null; + if (resourceValidTypeArtifacts != null) { + validArtifactTypes = resourceValidTypeArtifacts.keySet(); + } + + if (validArtifactTypes == null || artifactType == null + || !validArtifactTypes.contains(artifactType.getType())) { + List<String> messageArguments = new ArrayList<>(); + messageArguments.add(receivedTypeName); + messageArguments.addAll(Arrays.asList(arguments)); + if (!collectedWarningMessages.containsKey(warningMessage)) { + Set<List<String>> messageArgumentLists = new HashSet<>(); + messageArgumentLists.add(messageArguments); + collectedWarningMessages.put(warningMessage, messageArgumentLists); + } else { + collectedWarningMessages.get(warningMessage).add(messageArguments); + } + } + + return artifactType == null ? ArtifactTypeEnum.OTHER.getType() : artifactType.getType(); + } + + private Either<ZipOutputStream, ResponseFormat> writeAllFilesToCsar(Component mainComponent, + CsarDefinition csarDefinition, ZipOutputStream zipstream, boolean isInCertificationRequest) + throws IOException { + ComponentArtifacts componentArtifacts = csarDefinition.getComponentArtifacts(); + + Either<ZipOutputStream, ResponseFormat> writeComponentArtifactsToSpecifiedPath = writeComponentArtifactsToSpecifiedPath( + mainComponent, componentArtifacts, zipstream, ARTIFACTS_PATH, isInCertificationRequest); + + if (writeComponentArtifactsToSpecifiedPath.isRight()) { + return Either.right(writeComponentArtifactsToSpecifiedPath.right().value()); + } + + ComponentTypeArtifacts mainTypeAndCIArtifacts = componentArtifacts.getMainTypeAndCIArtifacts(); + writeComponentArtifactsToSpecifiedPath = writeArtifactsInfoToSpecifiedPath(mainComponent, + mainTypeAndCIArtifacts.getComponentArtifacts(), zipstream, ARTIFACTS_PATH, isInCertificationRequest); + + if (writeComponentArtifactsToSpecifiedPath.isRight()) { + return Either.right(writeComponentArtifactsToSpecifiedPath.right().value()); + } + + Map<String, ArtifactsInfo> componentInstancesArtifacts = mainTypeAndCIArtifacts + .getComponentInstancesArtifacts(); + Set<String> keySet = componentInstancesArtifacts.keySet(); + + String currentPath = ARTIFACTS_PATH + RESOURCES_PATH; + for (String keyAssetName : keySet) { + ArtifactsInfo artifactsInfo = componentInstancesArtifacts.get(keyAssetName); + String pathWithAssetName = currentPath + keyAssetName + "/"; + writeComponentArtifactsToSpecifiedPath = writeArtifactsInfoToSpecifiedPath(mainComponent, artifactsInfo, + zipstream, pathWithAssetName, isInCertificationRequest); + + if (writeComponentArtifactsToSpecifiedPath.isRight()) { + return Either.right(writeComponentArtifactsToSpecifiedPath.right().value()); + } + } + writeComponentArtifactsToSpecifiedPath = writeOperationsArtifactsToCsar(mainComponent, zipstream); + + if (writeComponentArtifactsToSpecifiedPath.isRight()) { + return Either.right(writeComponentArtifactsToSpecifiedPath.right().value()); + } + return Either.left(zipstream); + } + + private Either<ZipOutputStream, ResponseFormat> writeOperationsArtifactsToCsar(Component component, + ZipOutputStream zipstream) { + if (component instanceof Service) { + return Either.left(zipstream); + } + if (Objects.isNull(((Resource) component).getInterfaces())) { + log.debug("Component Name {}- no interfaces found", component.getNormalizedName()); + return Either.left(zipstream); + } + final Map<String, InterfaceDefinition> interfaces = ((Resource) component).getInterfaces(); + + for (Map.Entry<String, InterfaceDefinition> interfaceEntry : interfaces.entrySet()) { + for (OperationDataDefinition operation : interfaceEntry.getValue().getOperations().values()) { + try { + if (Objects.isNull(operation.getImplementation())) { + log.debug( + "Component Name {}, Interface Id {}, Operation Name {} - no Operation Implementation found", + component.getNormalizedName(), interfaceEntry.getValue().getUniqueId(), + operation.getName()); + continue; + } + if (Objects.isNull(operation.getImplementation().getArtifactName())) { + log.debug("Component Name {}, Interface Id {}, Operation Name {} - no artifact found", + component.getNormalizedName(), interfaceEntry.getValue().getUniqueId(), + operation.getName()); + continue; + } + + final String artifactUUID = operation.getImplementation().getArtifactUUID(); + + final Either<byte[], ActionStatus> artifactFromCassandra = getFromCassandra(artifactUUID); + final String artifactName = operation.getImplementation().getArtifactName(); + if (artifactFromCassandra.isRight()) { + log.error("ArtifactName {}, unique ID {}", artifactName, artifactUUID); + log.error("Failed to get {} payload from DB reason: {}", artifactName, + artifactFromCassandra.right().value()); + return Either.right(componentsUtils.getResponseFormat( + ActionStatus.ARTIFACT_PAYLOAD_NOT_FOUND_DURING_CSAR_CREATION, "Resource", + component.getUniqueId(), artifactName, artifactUUID)); + } + + final byte[] payloadData = artifactFromCassandra.left().value(); + zipstream.putNextEntry(new ZipEntry( + OperationArtifactUtil.createOperationArtifactPath(component.getNormalizedName(), + interfaceEntry.getValue().getToscaResourceName(), operation))); + zipstream.write(payloadData); + + } catch (IOException | NullPointerException e) { + log.error("Component Name {}, Interface Name {}, Operation Name {}", component.getNormalizedName(), + interfaceEntry.getKey(), operation.getName()); + log.error("Error while writing the operation's artifacts to the CSAR " + "{}", e); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ERROR_DURING_CSAR_CREATION, + "Resource", component.getUniqueId())); + } + } + } + return Either.left(zipstream); + + } + + private Either<ZipOutputStream, ResponseFormat> writeComponentArtifactsToSpecifiedPath(Component mainComponent, + ComponentArtifacts componentArtifacts, ZipOutputStream zipstream, String currentPath, + boolean isInCertificationRequest) throws IOException { + Map<String, ComponentTypeArtifacts> componentTypeArtifacts = componentArtifacts.getComponentTypeArtifacts(); + // Keys are defined: + // <Inner Asset TOSCA name (e.g. VFC name)> folder name: <Inner Asset TOSCA name + // (e.g. VFC name)>_v<version>. + // E.g. "org.openecomp.resource.vf.vipr_atm_v1.0" + Set<String> componentTypeArtifactsKeys = componentTypeArtifacts.keySet(); + for (String keyAssetName : componentTypeArtifactsKeys) { + ComponentTypeArtifacts componentInstanceArtifacts = componentTypeArtifacts.get(keyAssetName); + ArtifactsInfo componentArtifacts2 = componentInstanceArtifacts.getComponentArtifacts(); + String pathWithAssetName = currentPath + keyAssetName + "/"; + Either<ZipOutputStream, ResponseFormat> writeArtifactsInfoToSpecifiedtPath = writeArtifactsInfoToSpecifiedPath( + mainComponent, componentArtifacts2, zipstream, pathWithAssetName, isInCertificationRequest); + + if (writeArtifactsInfoToSpecifiedtPath.isRight()) { + return writeArtifactsInfoToSpecifiedtPath; + } + } + + return Either.left(zipstream); + } + + private Either<ZipOutputStream, ResponseFormat> writeArtifactsInfoToSpecifiedPath(Component mainComponent, + ArtifactsInfo currArtifactsInfo, ZipOutputStream zip, String path, boolean isInCertificationRequest) + throws IOException { + Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> artifactsInfo = currArtifactsInfo + .getArtifactsInfo(); + Set<ArtifactGroupTypeEnum> groupTypeEnumKeySet = artifactsInfo.keySet(); + + for (ArtifactGroupTypeEnum artifactGroupTypeEnum : groupTypeEnumKeySet) { + String groupTypeFolder = path + WordUtils.capitalizeFully(artifactGroupTypeEnum.getType()) + "/"; + + Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactTypesMap = artifactsInfo.get(artifactGroupTypeEnum); + Set<ArtifactTypeEnum> artifactTypeEnumKeySet = artifactTypesMap.keySet(); + + for (ArtifactTypeEnum artifactTypeEnum : artifactTypeEnumKeySet) { + List<ArtifactDefinition> artifactDefinitionList = artifactTypesMap.get(artifactTypeEnum); + String artifactTypeFolder = groupTypeFolder + artifactTypeEnum.toString() + "/"; + + Either<ZipOutputStream, ResponseFormat> writeArtifactDefinition = writeArtifactDefinition(mainComponent, + zip, artifactDefinitionList, artifactTypeFolder, isInCertificationRequest); + + if (writeArtifactDefinition.isRight()) { + return writeArtifactDefinition; + } + } + } + + return Either.left(zip); + } + + private Either<ZipOutputStream, ResponseFormat> writeArtifactDefinition(Component mainComponent, + ZipOutputStream zip, List<ArtifactDefinition> artifactDefinitionList, String artifactPathAndFolder, + boolean isInCertificationRequest) throws IOException { + + ComponentTypeEnum componentType = mainComponent.getComponentType(); + String heatEnvType = ArtifactTypeEnum.HEAT_ENV.getType(); + + for (ArtifactDefinition artifactDefinition : artifactDefinitionList) { + if (!isInCertificationRequest && componentType == ComponentTypeEnum.SERVICE + && artifactDefinition.getArtifactType().equals(heatEnvType) || + // this is placeholder + (artifactDefinition.getEsId() == null && artifactDefinition.getMandatory())) { + continue; + } + + byte[] payloadData = artifactDefinition.getPayloadData(); + String artifactFileName = artifactDefinition.getArtifactName(); + + if (payloadData == null) { + Either<byte[], ActionStatus> fromCassandra = getFromCassandra(artifactDefinition.getEsId()); + + if (fromCassandra.isRight()) { + log.debug("ArtifactName {}, unique ID {}", artifactDefinition.getArtifactName(), + artifactDefinition.getUniqueId()); + log.debug("Failed to get {} payload from DB reason: {}", artifactFileName, + fromCassandra.right().value()); + continue; + } + payloadData = fromCassandra.left().value(); + } + zip.putNextEntry(new ZipEntry(artifactPathAndFolder + artifactFileName)); + zip.write(payloadData); + } + + return Either.left(zip); + } + + /************************************ + * Artifacts Structure + ******************************************************************/ + /** + * The artifacts Definition saved by their structure + */ + private class ArtifactsInfo { + // Key is the type of artifacts(Informational/Deployment) + // Value is a map between an artifact type and a list of all artifacts of this + // type + private Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> artifactsInfoField; + + public ArtifactsInfo() { + this.artifactsInfoField = new EnumMap<>(ArtifactGroupTypeEnum.class); + } + + public Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> getArtifactsInfo() { + return artifactsInfoField; + } + + public List<ArtifactDefinition> getFlatArtifactsListByType(ArtifactTypeEnum artifactType) { + List<ArtifactDefinition> artifacts = new ArrayList<>(); + for (List<ArtifactDefinition> artifactsByType : artifactsInfoField.get(artifactType).values()) { + artifacts.addAll(artifactsByType); + } + return artifacts; + } + + public void addArtifactsToGroup(ArtifactGroupTypeEnum artifactGroup, + Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactsDefinition) { + artifactsInfoField.put(artifactGroup, artifactsDefinition); + } + + public boolean isEmpty() { + return artifactsInfoField.isEmpty(); + } + + } + + /** + * The artifacts of the component and of all its composed instances + * + */ + private class ComponentTypeArtifacts { + private ArtifactsInfo componentArtifacts; // component artifacts (describes the Informational Deployment + // folders) + private Map<String, ArtifactsInfo> componentInstancesArtifacts; // artifacts of the composed instances mapped by + // the resourceInstance normalized name + // (describes the Resources folder) + + public ComponentTypeArtifacts() { + componentArtifacts = new ArtifactsInfo(); + componentInstancesArtifacts = new HashMap<>(); + } + + public ArtifactsInfo getComponentArtifacts() { + return componentArtifacts; + } + + public void setComponentArtifacts(ArtifactsInfo artifactsInfo) { + this.componentArtifacts = artifactsInfo; + } + + public Map<String, ArtifactsInfo> getComponentInstancesArtifacts() { + return componentInstancesArtifacts; + } + + public void setComponentInstancesArtifacts(Map<String, ArtifactsInfo> componentInstancesArtifacts) { + this.componentInstancesArtifacts = componentInstancesArtifacts; + } + + public void addComponentInstancesArtifacts(String normalizedName, ArtifactsInfo artifactsInfo) { + componentInstancesArtifacts.put(normalizedName, artifactsInfo); + } + + } + + private class ComponentArtifacts { + // artifacts of the component and CI's artifacts contained in it's composition + // (represents Informational, Deployment & Resource folders of main component) + private ComponentTypeArtifacts mainTypeAndCIArtifacts; + // artifacts of all component types mapped by their tosca name + private Map<String, ComponentTypeArtifacts> componentTypeArtifacts; + + public ComponentArtifacts() { + mainTypeAndCIArtifacts = new ComponentTypeArtifacts(); + componentTypeArtifacts = new HashMap<>(); + } + + public ComponentTypeArtifacts getMainTypeAndCIArtifacts() { + return mainTypeAndCIArtifacts; + } + + public void setMainTypeAndCIArtifacts(ComponentTypeArtifacts componentInstanceArtifacts) { + this.mainTypeAndCIArtifacts = componentInstanceArtifacts; + } + + public Map<String, ComponentTypeArtifacts> getComponentTypeArtifacts() { + return componentTypeArtifacts; + } + + public void setComponentTypeArtifacts(Map<String, ComponentTypeArtifacts> componentTypeArtifacts) { + this.componentTypeArtifacts = componentTypeArtifacts; + } + } + + private class CsarDefinition { + private ComponentArtifacts componentArtifacts; + + // add list of tosca artifacts and meta describes CSAR zip root + + public CsarDefinition(ComponentArtifacts componentArtifacts) { + this.componentArtifacts = componentArtifacts; + } + + public ComponentArtifacts getComponentArtifacts() { + return componentArtifacts; + } + } + + /************************************ + * Artifacts Structure END + ******************************************************************/ + + private Either<CsarDefinition, ResponseFormat> collectComponentCsarDefinition(Component component) { + ComponentArtifacts componentArtifacts = new ComponentArtifacts(); + Component updatedComponent = component; + + // get service to receive the AII artifacts uploaded to the service + if (updatedComponent.getComponentType() == ComponentTypeEnum.SERVICE) { + Either<Service, StorageOperationStatus> getServiceResponse = toscaOperationFacade + .getToscaElement(updatedComponent.getUniqueId()); + + if (getServiceResponse.isRight()) { + ActionStatus actionStatus = componentsUtils + .convertFromStorageResponse(getServiceResponse.right().value()); + return Either.right(componentsUtils.getResponseFormat(actionStatus)); + } + + updatedComponent = getServiceResponse.left().value(); + } + + // find the artifacts of the main component, it would have its composed + // instances artifacts in a separate folder + ComponentTypeArtifacts componentInstanceArtifacts = new ComponentTypeArtifacts(); + ArtifactsInfo artifactsInfo = collectComponentArtifacts(updatedComponent); + componentInstanceArtifacts.setComponentArtifacts(artifactsInfo); + componentArtifacts.setMainTypeAndCIArtifacts(componentInstanceArtifacts); + + Map<String, ComponentTypeArtifacts> resourceTypeArtifacts = componentArtifacts.getComponentTypeArtifacts(); // artifacts + // mapped + // by + // the + // component + // type(tosca + // name+version) + // get the component instances + List<ComponentInstance> componentInstances = updatedComponent.getComponentInstances(); + if (componentInstances != null) { + for (ComponentInstance componentInstance : componentInstances) { + // call recursive to find artifacts for all the path + Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts = collectComponentInstanceArtifacts( + updatedComponent, componentInstance, resourceTypeArtifacts, componentInstanceArtifacts); + if (collectComponentInstanceArtifacts.isRight()) { + return Either.right(collectComponentInstanceArtifacts.right().value()); + } + } + } + + if (log.isDebugEnabled()) { + printResult(componentArtifacts, updatedComponent.getName()); + } + + return Either.left(new CsarDefinition(componentArtifacts)); + } + + private void printResult(ComponentArtifacts componentArtifacts, String name) { + StringBuilder result = new StringBuilder(); + result.append("Artifacts of main component " + name + "\n"); + ComponentTypeArtifacts componentInstanceArtifacts = componentArtifacts.getMainTypeAndCIArtifacts(); + printArtifacts(componentInstanceArtifacts); + result.append("Type Artifacts\n"); + for (Map.Entry<String, ComponentTypeArtifacts> typeArtifacts : componentArtifacts.getComponentTypeArtifacts() + .entrySet()) { + result.append("Folder " + typeArtifacts.getKey() + "\n"); + result.append(printArtifacts(typeArtifacts.getValue())); + } + + if (log.isDebugEnabled()) { + log.debug(result.toString()); + } + } + + private String printArtifacts(ComponentTypeArtifacts componentInstanceArtifacts) { + StringBuilder result = new StringBuilder(); + ArtifactsInfo artifactsInfo = componentInstanceArtifacts.getComponentArtifacts(); + Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> componetArtifacts = artifactsInfo + .getArtifactsInfo(); + printArtifacts(componetArtifacts); + result = result.append("Resources\n"); + for (Map.Entry<String, ArtifactsInfo> resourceInstance : componentInstanceArtifacts + .getComponentInstancesArtifacts().entrySet()) { + result.append("Folder" + resourceInstance.getKey() + "\n"); + result.append(printArtifacts(resourceInstance.getValue().getArtifactsInfo())); + } + + return result.toString(); + } + + private String printArtifacts( + Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> componetArtifacts) { + StringBuilder result = new StringBuilder(); + for (Map.Entry<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> artifactGroup : componetArtifacts + .entrySet()) { + result.append(" " + artifactGroup.getKey().getType()); + for (Map.Entry<ArtifactTypeEnum, List<ArtifactDefinition>> groupArtifacts : artifactGroup.getValue() + .entrySet()) { + result.append(" " + groupArtifacts.getKey().getType()); + for (ArtifactDefinition artifact : groupArtifacts.getValue()) { + result.append(" " + artifact.getArtifactDisplayName()); + } + } + } + + return result.toString(); + } + + private ComponentTypeArtifacts collectComponentTypeArtifacts(Map<String, ComponentTypeArtifacts> resourcesArtifacts, + ComponentInstance componentInstance, Resource fetchedComponent) { + String toscaComponentName = componentInstance.getToscaComponentName() + "_v" + + componentInstance.getComponentVersion(); + + ComponentTypeArtifacts componentArtifactsInfo = resourcesArtifacts.get(toscaComponentName); + // if there are no artifacts for this component type we need to fetch and build + // them + if (componentArtifactsInfo == null) { + ArtifactsInfo componentArtifacts = collectComponentArtifacts(fetchedComponent); + componentArtifactsInfo = new ComponentTypeArtifacts(); + if (!componentArtifacts.isEmpty()) { + componentArtifactsInfo.setComponentArtifacts(componentArtifacts); + resourcesArtifacts.put(toscaComponentName, componentArtifactsInfo); + } + } + return componentArtifactsInfo; + } + + private Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts(Component parentComponent, + ComponentInstance componentInstance, Map<String, ComponentTypeArtifacts> resourcesTypeArtifacts, + ComponentTypeArtifacts instanceArtifactsLocation) { + // 1. get the component instance component + String componentUid = componentInstance.getComponentUid(); + Either<Resource, StorageOperationStatus> resource = toscaOperationFacade.getToscaElement(componentUid); + if (resource.isRight()) { + log.error("Failed to fetch resource with id {} for instance {}", componentUid, parentComponent.getUUID()); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ASSET_NOT_FOUND_DURING_CSAR_CREATION, + parentComponent.getComponentType().getValue(), parentComponent.getUUID(), + componentInstance.getOriginType().getComponentType().getValue(), componentUid)); + } + Resource fetchedComponent = resource.left().value(); + + // 2. fill the artifacts for the current component parent type + ComponentTypeArtifacts componentParentArtifacts = collectComponentTypeArtifacts(resourcesTypeArtifacts, + componentInstance, fetchedComponent); + + // 3. find the artifacts specific to the instance + Map<ArtifactTypeEnum, List<ArtifactDefinition>> componentInstanceSpecificInformationalArtifacts = getComponentInstanceSpecificArtifacts( + componentInstance.getArtifacts(), componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), + ArtifactGroupTypeEnum.INFORMATIONAL); + Map<ArtifactTypeEnum, List<ArtifactDefinition>> componentInstanceSpecificDeploymentArtifacts = getComponentInstanceSpecificArtifacts( + componentInstance.getDeploymentArtifacts(), + componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), ArtifactGroupTypeEnum.DEPLOYMENT); + + // 4. add the instances artifacts to the component type + ArtifactsInfo artifactsInfo = new ArtifactsInfo(); + if (!componentInstanceSpecificInformationalArtifacts.isEmpty()) { + artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.INFORMATIONAL, + componentInstanceSpecificInformationalArtifacts); + } + if (!componentInstanceSpecificDeploymentArtifacts.isEmpty()) { + artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, + componentInstanceSpecificDeploymentArtifacts); + } + if (!artifactsInfo.isEmpty()) { + instanceArtifactsLocation.addComponentInstancesArtifacts(componentInstance.getNormalizedName(), + artifactsInfo); + } + + // 5. do the same for all the component instances + List<ComponentInstance> componentInstances = fetchedComponent.getComponentInstances(); + if (componentInstances != null) { + for (ComponentInstance childComponentInstance : componentInstances) { + Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts = collectComponentInstanceArtifacts( + fetchedComponent, childComponentInstance, resourcesTypeArtifacts, componentParentArtifacts); + if (collectComponentInstanceArtifacts.isRight()) { + return collectComponentInstanceArtifacts; + } + } + } + + return Either.left(true); + } + + private Map<ArtifactTypeEnum, List<ArtifactDefinition>> getComponentInstanceSpecificArtifacts( + Map<String, ArtifactDefinition> componentArtifacts, + Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> componentTypeArtifacts, + ArtifactGroupTypeEnum artifactGroupTypeEnum) { + Map<ArtifactTypeEnum, List<ArtifactDefinition>> parentArtifacts = componentTypeArtifacts + .get(artifactGroupTypeEnum); // the artfiacts of the component itself and not the instance + + Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactsByTypeOfComponentInstance = new EnumMap<>( + ArtifactTypeEnum.class); + if (componentArtifacts != null) { + for (ArtifactDefinition artifact : componentArtifacts.values()) { + ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifact.getArtifactType()); + List<ArtifactDefinition> parentArtifactsByType = null; + if (parentArtifacts != null) { + parentArtifactsByType = parentArtifacts.get(artifactType); + } + // the artifact is of instance + if (parentArtifactsByType == null || !parentArtifactsByType.contains(artifact)) { + List<ArtifactDefinition> typeArtifacts = artifactsByTypeOfComponentInstance.get(artifactType); + if (typeArtifacts == null) { + typeArtifacts = new ArrayList<>(); + artifactsByTypeOfComponentInstance.put(artifactType, typeArtifacts); + } + typeArtifacts.add(artifact); + } + } + } + + return artifactsByTypeOfComponentInstance; + } + + private ArtifactsInfo collectComponentArtifacts(Component component) { + Map<String, ArtifactDefinition> informationalArtifacts = component.getArtifacts(); + Map<ArtifactTypeEnum, List<ArtifactDefinition>> informationalArtifactsByType = collectGroupArtifacts( + informationalArtifacts); + Map<String, ArtifactDefinition> deploymentArtifacts = component.getDeploymentArtifacts(); + Map<ArtifactTypeEnum, List<ArtifactDefinition>> deploymentArtifactsByType = collectGroupArtifacts( + deploymentArtifacts); + ArtifactsInfo artifactsInfo = new ArtifactsInfo(); + if (!informationalArtifactsByType.isEmpty()) { + artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.INFORMATIONAL, informationalArtifactsByType); + } + if (!deploymentArtifactsByType.isEmpty()) { + artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, deploymentArtifactsByType); + } + + return artifactsInfo; + } + + private Map<ArtifactTypeEnum, List<ArtifactDefinition>> collectGroupArtifacts( + Map<String, ArtifactDefinition> componentArtifacts) { + Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactsByType = new EnumMap<>(ArtifactTypeEnum.class); + for (ArtifactDefinition artifact : componentArtifacts.values()) { + if (artifact.getArtifactUUID() != null) { + ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifact.getArtifactType()); + List<ArtifactDefinition> typeArtifacts = artifactsByType.get(artifactType); + if (typeArtifacts == null) { + typeArtifacts = new ArrayList<>(); + artifactsByType.put(artifactType, typeArtifacts); + } + typeArtifacts.add(artifact); + } + } + return artifactsByType; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportHandler.java index 9f5ebdf7ca..8d8eac36b9 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportHandler.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportHandler.java @@ -680,7 +680,7 @@ public class ToscaExportHandler { componentInstance, dataTypes, nodeTemplate); if (capabilities.isRight()) { - convertNodeTemplatesRes = Either.right(requirements.right().value()); + convertNodeTemplatesRes = Either.right(capabilities.right().value()); break; } log.debug("Component instance Capabilities converted for instance {}", instanceUniqueId); diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/CapabiltyRequirementConvertorTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/CapabiltyRequirementConvertorTest.java index b00bd0f6b1..5f051b7970 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/CapabiltyRequirementConvertorTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/CapabiltyRequirementConvertorTest.java @@ -1,5 +1,4 @@ package org.openecomp.sdc.be.tosca; -// import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; @@ -9,116 +8,689 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; +import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.stream.Collectors; +import org.junit.Before; import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.model.CapabilityDefinition; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; +import org.openecomp.sdc.be.model.ComponentParametersView; +import org.openecomp.sdc.be.model.DataTypeDefinition; +import org.openecomp.sdc.be.model.RequirementDefinition; import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.tosca.ToscaUtils.SubstituitionEntry; +import org.openecomp.sdc.be.tosca.model.SubstitutionMapping; +import org.openecomp.sdc.be.tosca.model.ToscaNodeTemplate; +import org.openecomp.sdc.be.tosca.model.ToscaNodeType; +import org.openecomp.sdc.be.tosca.model.ToscaTemplateCapability; + +import fj.data.Either; +import mockit.Deencapsulation; public class CapabiltyRequirementConvertorTest { - CapabiltyRequirementConvertor capabiltyRequirementConvertor = Mockito.spy(new CapabiltyRequirementConvertor()); - ComponentInstance instanceProxy = Mockito.spy( new ComponentInstance() ); - ComponentInstance vfInstance = Mockito.spy( new ComponentInstance() ); - Component vfComponent = Mockito.spy( new Resource() ); - ComponentInstance vfcInstance = Mockito.spy( new ComponentInstance() ); - Component vfcComponent = Mockito.spy( new Resource() ); - - @Test - public void getReducedPathByOwner() throws Exception { - List<String> pathList = new ArrayList<>(); - String uniqueId = "41d3a665-1313-4b5e-9bf0-e901ecf4b806.a77df84e-83eb-4edc-9823-d1f9f6549693.lb_2"; - - String exerpt = "41d3a665-1313-4b5e-9bf0-e901ecf4b806.a77df84e-83eb-4edc-9823-d1f9f6549693.lb_1"; - String duplicate = "a77df84e-83eb-4edc-9823-d1f9f6549693.c79e9a4a-b172-4323-a2e2-1c48d6603241.lb_swu_direct_4_rvmi"; - pathList.add(exerpt); - pathList.add(duplicate); - pathList.add(duplicate); - pathList.add(uniqueId); - - pathList.add("5f172af9-1588-443e-8897-1432b19aad8c.2cb7514a-1e50-4280-8457-baacb97b50bf.vepdgtp4837vf0"); - pathList.add("86ae128e-3d0a-41f7-a957-db1df9fe598c.9cc8f8ac-6869-4dd6-a6e1-74ecb9570dc4.vepdgtp4837svc_proxy0"); - - List<String> reducedMap = new CapabiltyRequirementConvertor().getReducedPathByOwner( pathList , uniqueId ); - - assertThat( reducedMap ).isNotNull().doesNotContain(exerpt).containsOnlyOnce(duplicate).hasSize(4); - } - - //generate stub capability - private Map<String, List<CapabilityDefinition>> newCapabilities(String capabilityName){ - Map<String, List<CapabilityDefinition>> capabilities = new HashMap<>(); - List<CapabilityDefinition> list = new ArrayList<>(); - CapabilityDefinition capabilityDefinition = new CapabilityDefinition(); - capabilityDefinition.setName( capabilityName ); - capabilityDefinition.setType("att.Node"); - List<String> pathList = new ArrayList<>(); - - capabilityDefinition.setOwnerId("41d3a665-1313-4b5e-9bf0-e901ecf4b806.a77df84e-83eb-4edc-9823-d1f9f6549693"); - pathList.add("41d3a665-1313-4b5e-9bf0-e901ecf4b806.a77df84e-83eb-4edc-9823-d1f9f6549693.lb_1"); - //pathList.add("a77df84e-83eb-4edc-9823-d1f9f6549693.c79e9a4a-b172-4323-a2e2-1c48d6603241.lb_swu_direct_4_rvmi"); - pathList.add("5f172af9-1588-443e-8897-1432b19aad8c.2cb7514a-1e50-4280-8457-baacb97b50bf.vepdgtp4837vf0"); - pathList.add("86ae128e-3d0a-41f7-a957-db1df9fe598c.9cc8f8ac-6869-4dd6-a6e1-74ecb9570dc4.vepdgtp4837svc_proxy0"); - - capabilityDefinition.setPath(pathList); - list.add(capabilityDefinition); - capabilities.put(capabilityDefinition.getType() , list ); - - return capabilities; - } - - - @Test - public void testBuildName(){ - doReturn("1").when(instanceProxy).getActualComponentUid(); - doReturn("2").when(vfInstance).getActualComponentUid(); - doReturn("3").when(vfcInstance).getActualComponentUid(); - //region proxy - Component proxyOrigin = new Resource(); - - proxyOrigin.setName( "vepdgtp4837svc_proxy0" ); - proxyOrigin.setComponentType(ComponentTypeEnum.RESOURCE); - proxyOrigin.setComponentInstances( asList( vfInstance ) ); - - //endregion - //region vf+vfc - vfInstance.setName("vepdgtp4837vf0"); - vfInstance.setNormalizedName("vepdgtp4837vf0"); - vfInstance.setUniqueId("5f172af9-1588-443e-8897-1432b19aad8c.2cb7514a-1e50-4280-8457-baacb97b50bf.vepdgtp4837vf0"); - vfComponent.setName("vepdgtp4837vf0"); //origin - vfComponent.setComponentInstances(Arrays.asList(vfcInstance)); - vfcInstance.setUniqueId("41d3a665-1313-4b5e-9bf0-e901ecf4b806.a77df84e-83eb-4edc-9823-d1f9f6549693.lb_1"); - vfcInstance.setName("lb_1"); - vfcInstance.setNormalizedName("lb_1"); - vfcInstance.setName("41d3a665-1313-4b5e-9bf0-e901ecf4b806.a77df84e-83eb-4edc-9823-d1f9f6549693.lb_1"); - vfcComponent.setName("lb_1"); - //endregion - Map<String, List<CapabilityDefinition>> capabilities = newCapabilities("port"); - vfcComponent.setCapabilities(capabilities); - Map<Component, ComponentInstance> map = Collections.unmodifiableMap(new HashMap<Component, ComponentInstance>() { - { - put( proxyOrigin, null ); - put( vfComponent, vfInstance ); - put( vfcComponent, vfcInstance ); - } } ) ; - Map<String, Component> cache = Collections.unmodifiableMap(new HashMap<String, Component>() {{ - put( "1",proxyOrigin); - put( "2" ,vfComponent); - put( "3" ,vfcComponent); - }}); - instanceProxy.setCapabilities(capabilities); - proxyOrigin.setCapabilities( capabilities ); - List<CapabilityDefinition> flatList = capabilities.values().stream().flatMap(List::stream).collect(Collectors.toList()); - flatList.stream().forEach( (CapabilityDefinition capabilityDefinition) -> { - String name = capabiltyRequirementConvertor.buildCapabilityNameForComponentInstance(cache, instanceProxy, capabilityDefinition); - System.out.println("built name -> " + name); - assertThat(name).isEqualTo( "vepdgtp4837vf0.lb_1."+capabilityDefinition.getName() ); - }); - } -} + @InjectMocks + CapabiltyRequirementConvertor testSubject; + + @Mock + ToscaOperationFacade toscaOperationFacade; + + CapabiltyRequirementConvertor capabiltyRequirementConvertor = Mockito.spy(new CapabiltyRequirementConvertor()); + ComponentInstance instanceProxy = Mockito.spy(new ComponentInstance()); + ComponentInstance vfInstance = Mockito.spy(new ComponentInstance()); + Component vfComponent = Mockito.spy(new Resource()); + ComponentInstance vfcInstance = Mockito.spy(new ComponentInstance()); + Component vfcComponent = Mockito.spy(new Resource()); + + @Before + public void setUpMock() throws Exception { + MockitoAnnotations.initMocks(this); + } + + @Test + public void testGetInstance() { + CapabiltyRequirementConvertor.getInstance(); + } + + @Test + public void testConvertComponentInstanceCapabilties() { + Map<String, List<CapabilityDefinition>> capabilities = newCapabilities("port"); + vfInstance.setCapabilities(capabilities); + ToscaNodeTemplate nodeTemplate = new ToscaNodeTemplate(); + Map<String, DataTypeDefinition> testDataTypes = new HashMap<String, DataTypeDefinition>(); + + capabilities.get("att.Node").clear(); + testSubject.convertComponentInstanceCapabilties(vfInstance, testDataTypes, nodeTemplate); + + capabilities = newCapabilities("port"); + vfInstance.setCapabilities(capabilities); + vfInstance.setComponentUid("uid"); + + Mockito.when(toscaOperationFacade.getToscaElement(Mockito.any(String.class), + Mockito.any(ComponentParametersView.class))) + .thenReturn(Either.right(StorageOperationStatus.BAD_REQUEST)); + + testSubject.convertComponentInstanceCapabilties(vfInstance, testDataTypes, nodeTemplate); + + } + + @Test + public void testConvertComponentInstanceCapabilties_1() { + Map<String, List<CapabilityDefinition>> capabilities = newCapabilities("port"); + ToscaNodeTemplate nodeTemplate = new ToscaNodeTemplate(); + Map<String, DataTypeDefinition> testDataTypes = new HashMap<String, DataTypeDefinition>(); + + vfInstance.setComponentUid("uid"); + + vfInstance.setCapabilities(capabilities); + + Mockito.when(toscaOperationFacade.getToscaElement(Mockito.any(String.class), + Mockito.any(ComponentParametersView.class))) + .thenReturn(Either.right(StorageOperationStatus.BAD_REQUEST)); + + testSubject.convertComponentInstanceCapabilties(vfInstance, testDataTypes, nodeTemplate); + + } + + @Test + public void testConvertOverridenProperty() { + ComponentInstance instance = new ComponentInstance(); + Map<String, DataTypeDefinition> testDataTypes = new HashMap<String, DataTypeDefinition>(); + Map<String, ToscaTemplateCapability> capabilities = new HashMap<>(); + ComponentInstanceProperty p = new ComponentInstanceProperty(); + SchemaDefinition entrySchema = new SchemaDefinition(); + entrySchema.setProperty(new PropertyDataDefinition()); + p.setSchema(entrySchema); + + Deencapsulation.invoke(testSubject, "convertOverridenProperty", instance, testDataTypes, capabilities, p, + "port"); + } + + @Test + public void testConvertRequirements() { + ToscaNodeType nodeType = new ToscaNodeType(); + + testSubject.convertRequirements(vfComponent, nodeType); + + } + + @Test + public void testConvertRequirements_1() { + ToscaNodeType nodeType = new ToscaNodeType(); + Map<String, List<RequirementDefinition>> requirementsMap = new HashMap<String, List<RequirementDefinition>>(); + + List<RequirementDefinition> requirementsArray = new ArrayList<RequirementDefinition>(); + RequirementDefinition definition = new RequirementDefinition(); + definition.setOwnerId("id"); + requirementsArray.add(definition); + requirementsMap.put("key", requirementsArray); + vfComponent.setRequirements(requirementsMap); + vfComponent.setUniqueId("id"); + + testSubject.convertRequirements(vfComponent, nodeType); + + } + + @Test + public void testConvertSubstitutionMappingRequirements() { + Map<String, Component> componentsCache = new HashMap<>(); + SubstitutionMapping substitution = new SubstitutionMapping(); + Map<String, List<RequirementDefinition>> requirementsMap = new HashMap<String, List<RequirementDefinition>>(); + List<RequirementDefinition> requirementsArray = new ArrayList<RequirementDefinition>(); + RequirementDefinition definition = new RequirementDefinition(); + definition.setOwnerId("id"); + definition.setName("name"); + definition.setParentName("parentName"); + List<String> path = new ArrayList<>(); + path.add("path1"); + path.add("path2"); + definition.setPath(path); + requirementsArray.add(definition); + requirementsMap.put("key", requirementsArray); + List<ComponentInstance> instances = new ArrayList<>(); + ComponentInstance instance = new ComponentInstance(); + instance.setUniqueId("uid"); + instances.add(instance); + vfComponent.setRequirements(requirementsMap); + vfComponent.setComponentInstances(instances); + + testSubject.convertSubstitutionMappingRequirements(componentsCache, vfComponent, substitution); + } + + @Test + public void testConvertSubstitutionMappingRequirements_1() { + Map<String, Component> componentsCache = new HashMap<>(); + SubstitutionMapping substitution = new SubstitutionMapping(); + Map<String, List<RequirementDefinition>> requirementsMap = new HashMap<String, List<RequirementDefinition>>(); + List<RequirementDefinition> requirementsArray = new ArrayList<RequirementDefinition>(); + RequirementDefinition definition = new RequirementDefinition(); + definition.setName("name"); + definition.setParentName("parentName"); + List<String> path = new ArrayList<>(); + path.add("path1."); + path.add("id"); + definition.setPath(path); + requirementsArray.add(definition); + requirementsMap.put("key", requirementsArray); + List<ComponentInstance> instances = new ArrayList<>(); + ComponentInstance instance = new ComponentInstance(); + instance.setUniqueId("id"); + instance.setComponentUid("id"); + instances.add(instance); + vfComponent.setRequirements(requirementsMap); + vfComponent.setComponentInstances(instances); + + Mockito.when(toscaOperationFacade.getToscaElement(Mockito.any(String.class), + Mockito.any(ComponentParametersView.class))).thenReturn(Either.left(vfcComponent)); + + testSubject.convertSubstitutionMappingRequirements(componentsCache, vfComponent, substitution); + } + + @Test + public void testConvertSubstitutionMappingRequirementsAsMap() { + Map<String, Component> componentsCache = new HashMap<>(); + vfComponent.setRequirements(null); + + Deencapsulation.invoke(testSubject, "convertSubstitutionMappingRequirementsAsMap", componentsCache, + vfComponent); + } + + @Test + public void testBuildAddSubstitutionMappingsRequirements() { + Map<String, Component> componentsCache = new HashMap<>(); + Map<String, List<RequirementDefinition>> requirementsMap = new HashMap<String, List<RequirementDefinition>>(); + List<RequirementDefinition> requirementsArray = new ArrayList<RequirementDefinition>(); + RequirementDefinition definition = new RequirementDefinition(); + definition.setOwnerId("id"); + definition.setName("name"); + definition.setParentName("parentName"); + List<String> path = new ArrayList<>(); + path.add("path1"); + path.add("path2"); + definition.setPath(path); + requirementsArray.add(definition); + requirementsMap.put("key", requirementsArray); + vfComponent.setRequirements(requirementsMap); + List<ComponentInstance> componentInstances = new ArrayList<>(); + ComponentInstance instance = new ComponentInstance(); + instance.setUniqueId("id"); + componentInstances.add(instance); + + vfComponent.setComponentInstances(componentInstances); + + Deencapsulation.invoke(testSubject, "buildAddSubstitutionMappingsRequirements", componentsCache, vfComponent, + requirementsMap); + } + + @Test + public void testBuildAddSubstitutionMappingsCapabilities() { + Map<String, Component> componentsCache = new HashMap<>(); + Map<String, List<CapabilityDefinition>> capabilities = new HashMap<>(); + + Deencapsulation.invoke(testSubject, "buildAddSubstitutionMappingsCapabilities", componentsCache, vfComponent, + capabilities); + } + + @Test + public void testBuildAddSubstitutionMappingsCapabilities_1() { + Map<String, Component> componentsCache = new HashMap<>(); + Map<String, List<CapabilityDefinition>> capabilitiesMap = new HashMap<String, List<CapabilityDefinition>>(); + List<CapabilityDefinition> capabilitiesArray = new ArrayList<CapabilityDefinition>(); + CapabilityDefinition definition = new CapabilityDefinition(); + definition.setOwnerId("id"); + definition.setName("name"); + definition.setParentName("parentName"); + List<String> path = new ArrayList<>(); + path.add("path1"); + path.add("path2"); + definition.setPath(path); + capabilitiesArray.add(definition); + capabilitiesMap.put("key", capabilitiesArray); + vfComponent.setCapabilities(capabilitiesMap); + List<ComponentInstance> componentInstances = new ArrayList<>(); + ComponentInstance instance = new ComponentInstance(); + instance.setUniqueId("id"); + componentInstances.add(instance); + + vfComponent.setComponentInstances(componentInstances); + + Deencapsulation.invoke(testSubject, "buildAddSubstitutionMappingsCapabilities", componentsCache, vfComponent, + capabilitiesMap); + } + + @Test + public void testBuildSubstitutedNamePerInstance() { + Map<String, Component> componentsCache = new HashMap<>(); + String name = "name"; + String ownerId = "id"; + List<String> path = new ArrayList<>(); + path.add("id"); + SubstituitionEntry entry = new SubstituitionEntry(); + + List<ComponentInstance> componentInstances = new ArrayList<>(); + ComponentInstance instance = new ComponentInstance(); + instance.setUniqueId("id"); + instance.setComponentUid("uid"); + componentInstances.add(instance); + + vfComponent.setComponentInstances(componentInstances); + + Mockito.when(toscaOperationFacade.getToscaElement(Mockito.any(String.class), + Mockito.any(ComponentParametersView.class))) + .thenReturn(Either.right(StorageOperationStatus.BAD_REQUEST)); + + Deencapsulation.invoke(testSubject, "buildSubstitutedNamePerInstance", componentsCache, vfComponent, name, path, + ownerId, entry); + } + + @Test + public void testConvertRequirement() { + RequirementDefinition definition = new RequirementDefinition(); + List<String> path = new ArrayList<>(); + path.add("value"); + path.add("id"); + definition.setName("name"); + definition.setPath(path); + + List<ComponentInstance> componentInstances = new ArrayList<>(); + ComponentInstance instance = new ComponentInstance(); + instance.setUniqueId("id"); + componentInstances.add(instance); + + vfComponent.setComponentInstances(componentInstances); + + Deencapsulation.invoke(testSubject, "convertRequirement", vfComponent, false, definition); + } + + @Test + public void testConvertRequirement_1() { + RequirementDefinition definition = new RequirementDefinition(); + List<String> path = new ArrayList<>(); + path.add("id"); + definition.setName("name"); + definition.setPath(path); + + List<ComponentInstance> componentInstances = new ArrayList<>(); + ComponentInstance instance = new ComponentInstance(); + instance.setUniqueId("id"); + componentInstances.add(instance); + + vfComponent.setComponentInstances(componentInstances); + + Deencapsulation.invoke(testSubject, "convertRequirement", vfComponent, false, definition); + } + + @Test + public void testConvertRequirement_2() { + RequirementDefinition definition = new RequirementDefinition(); + List<String> path = new ArrayList<>(); + path.add("id"); + definition.setName("name"); + definition.setPath(path); + + List<ComponentInstance> componentInstances = new ArrayList<>(); + ComponentInstance instance = new ComponentInstance(); + instance.setUniqueId("id"); + componentInstances.add(instance); + + vfComponent.setComponentInstances(componentInstances); + + path.add("value"); + definition.setPath(path); + definition.setMaxOccurrences("1000"); + + Deencapsulation.invoke(testSubject, "convertRequirement", vfComponent, false, definition); + } + + @Test + public void testConvertCapabilities() { + Map<String, DataTypeDefinition> dataTypes = new HashMap<>(); + + testSubject.convertCapabilities(vfComponent, dataTypes); + Map<String, List<CapabilityDefinition>> capabilitiesMap = new HashMap<String, List<CapabilityDefinition>>(); + List<CapabilityDefinition> capabilitiesArray = new ArrayList<CapabilityDefinition>(); + CapabilityDefinition definition = new CapabilityDefinition(); + definition.setOwnerId("id"); + capabilitiesArray.add(definition); + capabilitiesMap.put("key", capabilitiesArray); + vfComponent.setUniqueId("id"); + vfComponent.setCapabilities(capabilitiesMap); + + testSubject.convertCapabilities(vfComponent, dataTypes); + } + + @Test + public void testConvertProxyCapabilities() { + Map<String, Component> componentsCache = new HashMap<>(); + Map<String, DataTypeDefinition> dataTypes = new HashMap<>(); + + List<ComponentInstance> componentInstances = new ArrayList<>(); + ComponentInstance instance = new ComponentInstance(); + instance.setUniqueId("id"); + componentInstances.add(instance); + + vfComponent.setComponentInstances(componentInstances); + + testSubject.convertProxyCapabilities(componentsCache, vfComponent, vfComponent, instance, dataTypes); + } + + @Test + public void testConvertProxyCapabilitiesWhenCapabilitiesNotNull() { + Map<String, Component> componentsCache = new HashMap<>(); + Map<String, DataTypeDefinition> dataTypes = new HashMap<>(); + + List<ComponentInstance> componentInstances = new ArrayList<>(); + ComponentInstance instance = new ComponentInstance(); + instance.setUniqueId("id"); + componentInstances.add(instance); + + vfComponent.setComponentInstances(componentInstances); + + Map<String, List<CapabilityDefinition>> capabilitiesMap = new HashMap<String, List<CapabilityDefinition>>(); + List<CapabilityDefinition> capabilitiesArray = new ArrayList<CapabilityDefinition>(); + CapabilityDefinition definition = new CapabilityDefinition(); + definition.setOwnerId("id"); + capabilitiesArray.add(definition); + capabilitiesMap.put("key", capabilitiesArray); + vfComponent.setUniqueId("id"); + + instance.setCapabilities(capabilitiesMap); + instance.setComponentUid("uid"); + + Mockito.when(toscaOperationFacade.getToscaElement(Mockito.any(String.class), + Mockito.any(ComponentParametersView.class))) + .thenReturn(Either.right(StorageOperationStatus.BAD_REQUEST)); + + testSubject.convertProxyCapabilities(componentsCache, vfComponent, vfComponent, instance, dataTypes); + } + + @Test + public void testConvertSubstitutionMappingCapabilities() { + Map<String, Component> componentsCache = new HashMap<>(); + + testSubject.convertSubstitutionMappingCapabilities(componentsCache, vfComponent); + + Map<String, List<CapabilityDefinition>> capabilitiesMap = new HashMap<String, List<CapabilityDefinition>>(); + List<CapabilityDefinition> capabilitiesArray = new ArrayList<CapabilityDefinition>(); + CapabilityDefinition definition = new CapabilityDefinition(); + definition.setOwnerId("id"); + definition.setName("name"); + definition.setParentName("parentName"); + List<String> path = new ArrayList<>(); + path.add("path1"); + path.add("id"); + definition.setPath(path); + capabilitiesArray.add(definition); + capabilitiesMap.put("key", capabilitiesArray); + vfComponent.setCapabilities(capabilitiesMap); + + List<ComponentInstance> instances = new ArrayList<>(); + ComponentInstance instance = new ComponentInstance(); + instance.setUniqueId("uid"); + instances.add(instance); + vfComponent.setComponentInstances(instances); + + testSubject.convertSubstitutionMappingCapabilities(componentsCache, vfComponent); + } + + @Test + public void testGetCapabilityPath() { + CapabilityDefinition definition = new CapabilityDefinition(); + List<String> path = new ArrayList<>(); + path.add("value"); + path.add("id"); + definition.setName("name"); + definition.setPath(path); + + List<ComponentInstance> componentInstances = new ArrayList<>(); + ComponentInstance instance = new ComponentInstance(); + instance.setUniqueId("id"); + componentInstances.add(instance); + + vfComponent.setComponentInstances(componentInstances); + + Deencapsulation.invoke(testSubject, "getCapabilityPath", definition, vfComponent); + } + + @Test + public void testGetCapabilityPath_1() { + CapabilityDefinition definition = new CapabilityDefinition(); + List<String> path = new ArrayList<>(); + path.add("id"); + definition.setName("name"); + definition.setPath(path); + + List<ComponentInstance> componentInstances = new ArrayList<>(); + ComponentInstance instance = new ComponentInstance(); + instance.setUniqueId("id"); + componentInstances.add(instance); + + vfComponent.setComponentInstances(componentInstances); + + Deencapsulation.invoke(testSubject, "getCapabilityPath", definition, vfComponent); + } + + @Test + public void testGetCapabilityPath_2() { + CapabilityDefinition definition = new CapabilityDefinition(); + List<String> path = new ArrayList<>(); + path.add("id"); + definition.setName("name"); + definition.setPath(path); + + List<ComponentInstance> componentInstances = new ArrayList<>(); + ComponentInstance instance = new ComponentInstance(); + instance.setUniqueId("id"); + componentInstances.add(instance); + + vfComponent.setComponentInstances(componentInstances); + + path.add("value"); + definition.setPath(path); + + Deencapsulation.invoke(testSubject, "getCapabilityPath", definition, vfComponent); + } + + @Test + public void testConvertCapability_1() { + Map<String, DataTypeDefinition> dataTypes = new HashMap<>(); + + Map<String, List<CapabilityDefinition>> capabilitiesMap = new HashMap<String, List<CapabilityDefinition>>(); + List<CapabilityDefinition> capabilitiesArray = new ArrayList<CapabilityDefinition>(); + CapabilityDefinition definition = new CapabilityDefinition(); + List<ComponentInstanceProperty> properties = new ArrayList<>(); + properties.add(new ComponentInstanceProperty()); + definition.setOwnerId("id"); + definition.setName("name"); + definition.setProperties(properties); + definition.setMaxOccurrences("1000"); + List<String> path = new ArrayList<>(); + path.add("value"); + path.add("id"); + definition.setPath(path); + capabilitiesArray.add(definition); + capabilitiesMap.put("key", capabilitiesArray); + vfComponent.setUniqueId("id"); + vfComponent.setCapabilities(capabilitiesMap); + + List<ComponentInstance> componentInstances = new ArrayList<>(); + ComponentInstance instance = new ComponentInstance(); + instance.setUniqueId("id"); + componentInstances.add(instance); + + vfComponent.setComponentInstances(componentInstances); + + Deencapsulation.invoke(testSubject, "convertCapabilty", vfComponent, new HashMap<>(), false, definition, + dataTypes, "name"); + } + + @Test + public void testBuildSubstitutedName() { + ComponentInstance instance = new ComponentInstance(); + instance.setUniqueId("id"); + List<ComponentInstance> resourceInstances = new ArrayList<>(); + resourceInstances.add(instance); + vfComponent.setComponentInstances(resourceInstances); + + List<String> path = new ArrayList<>(); + path.add("notId"); + + Deencapsulation.invoke(testSubject, "buildSubstitutedName", new HashMap<>(), vfComponent, path, "name"); + } + + @Test + public void testAppendNameRecursively() { + Map<String, Component> componentsCache = new HashMap<>(); + StringBuilder builder = new StringBuilder(); + List<String> path = new ArrayList<>(); + + path.add("id"); + Iterator<String> iter = path.iterator(); + List<ComponentInstance> resourceInstances = new ArrayList<>(); + ComponentInstance instance = new ComponentInstance(); + instance.setUniqueId("id"); + instance.setComponentUid("uid"); + resourceInstances.add(instance); + vfComponent.setComponentInstances(resourceInstances); + + Mockito.when(toscaOperationFacade.getToscaElement(Mockito.any(String.class), + Mockito.any(ComponentParametersView.class))) + .thenReturn(Either.right(StorageOperationStatus.BAD_REQUEST)); + + Deencapsulation.invoke(testSubject, "appendNameRecursively", componentsCache, vfComponent, iter, builder); + + } + + @Test + public void testGetFilter() { + ComponentInstance instance = new ComponentInstance(); + instance.setIsProxy(true); + + Deencapsulation.invoke(testSubject, "getFilter", instance); + } + + @Test + public void testGetReducedPathByOwner() throws Exception { + List<String> pathList = new ArrayList<>(); + String uniqueId = "41d3a665-1313-4b5e-9bf0-e901ecf4b806.a77df84e-83eb-4edc-9823-d1f9f6549693.lb_2"; + + String exerpt = "41d3a665-1313-4b5e-9bf0-e901ecf4b806.a77df84e-83eb-4edc-9823-d1f9f6549693.lb_1"; + String duplicate = "a77df84e-83eb-4edc-9823-d1f9f6549693.c79e9a4a-b172-4323-a2e2-1c48d6603241.lb_swu_direct_4_rvmi"; + pathList.add(exerpt); + pathList.add(duplicate); + pathList.add(duplicate); + pathList.add(uniqueId); + + pathList.add("5f172af9-1588-443e-8897-1432b19aad8c.2cb7514a-1e50-4280-8457-baacb97b50bf.vepdgtp4837vf0"); + pathList.add("86ae128e-3d0a-41f7-a957-db1df9fe598c.9cc8f8ac-6869-4dd6-a6e1-74ecb9570dc4.vepdgtp4837svc_proxy0"); + + List<String> reducedMap = new CapabiltyRequirementConvertor().getReducedPathByOwner(pathList, uniqueId); + + assertThat(reducedMap).isNotNull().doesNotContain(exerpt).containsOnlyOnce(duplicate).hasSize(4); + + List<String> path = new ArrayList<String>(); + + capabiltyRequirementConvertor.getReducedPathByOwner(path, uniqueId); + + path.add(""); + capabiltyRequirementConvertor.getReducedPathByOwner(path, uniqueId); + capabiltyRequirementConvertor.getReducedPathByOwner(path, ""); + } + + // generate stub capability + private Map<String, List<CapabilityDefinition>> newCapabilities(String capabilityName) { + Map<String, List<CapabilityDefinition>> capabilities = new HashMap<>(); + List<CapabilityDefinition> list = new ArrayList<>(); + CapabilityDefinition capabilityDefinition = new CapabilityDefinition(); + capabilityDefinition.setName(capabilityName); + capabilityDefinition.setType("att.Node"); + List<ComponentInstanceProperty> properties = new ArrayList<>(); + ComponentInstanceProperty prop = new ComponentInstanceProperty(); + prop.setValue("value"); + properties.add(prop); + capabilityDefinition.setProperties(properties); + List<String> pathList = new ArrayList<>(); + + capabilityDefinition.setOwnerId("41d3a665-1313-4b5e-9bf0-e901ecf4b806.a77df84e-83eb-4edc-9823-d1f9f6549693"); + pathList.add("41d3a665-1313-4b5e-9bf0-e901ecf4b806.a77df84e-83eb-4edc-9823-d1f9f6549693.lb_1"); + // pathList.add("a77df84e-83eb-4edc-9823-d1f9f6549693.c79e9a4a-b172-4323-a2e2-1c48d6603241.lb_swu_direct_4_rvmi"); + pathList.add("5f172af9-1588-443e-8897-1432b19aad8c.2cb7514a-1e50-4280-8457-baacb97b50bf.vepdgtp4837vf0"); + pathList.add("86ae128e-3d0a-41f7-a957-db1df9fe598c.9cc8f8ac-6869-4dd6-a6e1-74ecb9570dc4.vepdgtp4837svc_proxy0"); + + capabilityDefinition.setPath(pathList); + list.add(capabilityDefinition); + capabilities.put(capabilityDefinition.getType(), list); + + return capabilities; + } + + @Test + public void testBuildName() { + doReturn("1").when(instanceProxy).getActualComponentUid(); + doReturn("2").when(vfInstance).getActualComponentUid(); + doReturn("3").when(vfcInstance).getActualComponentUid(); + // region proxy + Component proxyOrigin = new Resource(); + + proxyOrigin.setName("vepdgtp4837svc_proxy0"); + proxyOrigin.setComponentType(ComponentTypeEnum.RESOURCE); + proxyOrigin.setComponentInstances(asList(vfInstance)); + + // endregion + // region vf+vfc + vfInstance.setName("vepdgtp4837vf0"); + vfInstance.setNormalizedName("vepdgtp4837vf0"); + vfInstance.setUniqueId( + "5f172af9-1588-443e-8897-1432b19aad8c.2cb7514a-1e50-4280-8457-baacb97b50bf.vepdgtp4837vf0"); + vfComponent.setName("vepdgtp4837vf0"); // origin + vfComponent.setComponentInstances(Arrays.asList(vfcInstance)); + vfcInstance.setUniqueId("41d3a665-1313-4b5e-9bf0-e901ecf4b806.a77df84e-83eb-4edc-9823-d1f9f6549693.lb_1"); + vfcInstance.setName("lb_1"); + vfcInstance.setNormalizedName("lb_1"); + vfcInstance.setName("41d3a665-1313-4b5e-9bf0-e901ecf4b806.a77df84e-83eb-4edc-9823-d1f9f6549693.lb_1"); + vfcComponent.setName("lb_1"); + // endregion + Map<String, List<CapabilityDefinition>> capabilities = newCapabilities("port"); + vfcComponent.setCapabilities(capabilities); + Map<Component, ComponentInstance> map = Collections + .unmodifiableMap(new HashMap<Component, ComponentInstance>() { + { + put(proxyOrigin, null); + put(vfComponent, vfInstance); + put(vfcComponent, vfcInstance); + } + }); + Map<String, Component> cache = Collections.unmodifiableMap(new HashMap<String, Component>() { + { + put("1", proxyOrigin); + put("2", vfComponent); + put("3", vfcComponent); + } + }); + instanceProxy.setCapabilities(capabilities); + proxyOrigin.setCapabilities(capabilities); + List<CapabilityDefinition> flatList = capabilities.values().stream().flatMap(List::stream) + .collect(Collectors.toList()); + flatList.stream().forEach((CapabilityDefinition capabilityDefinition) -> { + String name = capabiltyRequirementConvertor.buildCapabilityNameForComponentInstance(cache, instanceProxy, + capabilityDefinition); + System.out.println("built name -> " + name); + assertThat(name).isEqualTo("vepdgtp4837vf0.lb_1." + capabilityDefinition.getName()); + }); + } +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/CsarUtilsTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/CsarUtilsTest.java index 5ac1467a5c..adee99efab 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/CsarUtilsTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/CsarUtilsTest.java @@ -22,70 +22,1289 @@ package org.openecomp.sdc.be.tosca; import static org.junit.Assert.assertTrue; +import java.io.IOException; +import java.util.ArrayList; import java.util.HashMap; +import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Map.Entry; import java.util.Set; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; +import org.apache.commons.io.output.ByteArrayOutputStream; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.apache.commons.lang3.tuple.ImmutableTriple; +import org.apache.commons.lang3.tuple.Triple; import org.junit.Before; import org.junit.Test; -import org.openecomp.sdc.be.config.ConfigurationManager; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.sdc.generator.data.ArtifactType; +import org.openecomp.sdc.be.components.BeConfDependentTest; +import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; +import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationInfo; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao; +import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; +import org.openecomp.sdc.be.dao.cassandra.SdcSchemaFilesCassandraDao; +import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.OperationDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; +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.InterfaceDefinition; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +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.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.resources.data.ESArtifactData; +import org.openecomp.sdc.be.resources.data.SdcSchemaFilesData; import org.openecomp.sdc.be.tosca.CsarUtils.NonMetaArtifactInfo; -import org.openecomp.sdc.common.api.ConfigurationSource; -import org.openecomp.sdc.common.impl.ExternalConfiguration; -import org.openecomp.sdc.common.impl.FSConfigurationSource; +import org.openecomp.sdc.be.tosca.model.ToscaTemplate; +import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; +import org.openecomp.sdc.common.api.ArtifactTypeEnum; +import org.openecomp.sdc.exception.ResponseFormat; import fj.data.Either; +import mockit.Deencapsulation; -public class CsarUtilsTest { - @Before - public void setup() { - ExternalConfiguration.setAppName("catalog-be"); - - // init Configuration - String appConfigDir = "src/test/resources/config/catalog-be"; - ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); - ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); - } - - @Test - public void testValidateNonMetaArtifactHappyScenario(){ - String artifactPath = "Artifacts/Deployment/YANG_XML/myYang.xml"; - byte[] payloadData = "some payload data".getBytes(); - Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>(); - Either<NonMetaArtifactInfo, Boolean> eitherNonMetaArtifact = CsarUtils.validateNonMetaArtifact(artifactPath, payloadData, collectedWarningMessages); - assertTrue(eitherNonMetaArtifact.isLeft() ); - assertTrue(collectedWarningMessages.isEmpty() ); - - artifactPath = "Artifacts/Informational/OTHER/someArtifact.xml"; - eitherNonMetaArtifact = CsarUtils.validateNonMetaArtifact(artifactPath, payloadData, collectedWarningMessages); - assertTrue(eitherNonMetaArtifact.isLeft() ); - assertTrue(collectedWarningMessages.isEmpty() ); - } - - @Test - public void testValidateNonMetaArtifactScenarioWithWarnnings(){ - String artifactPath = "Artifacts/Deployment/Buga/myYang.xml"; - byte[] payloadData = "some payload data".getBytes(); - Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>(); - Either<NonMetaArtifactInfo, Boolean> eitherNonMetaArtifact = CsarUtils.validateNonMetaArtifact(artifactPath, payloadData, collectedWarningMessages); - assertTrue(eitherNonMetaArtifact.isLeft() ); - - artifactPath = "Artifacts/Informational/Buga2/someArtifact.xml"; - eitherNonMetaArtifact = CsarUtils.validateNonMetaArtifact(artifactPath, payloadData, collectedWarningMessages); - assertTrue(eitherNonMetaArtifact.isLeft() ); - - assertTrue(collectedWarningMessages.size() == 1 ); - assertTrue(collectedWarningMessages.values().iterator().next().size() == 2); - } - - @Test - public void testValidateNonMetaArtifactUnhappyScenario(){ - String artifactPath = "Artifacts/Buga/YANG_XML/myYang.xml"; - byte[] payloadData = "some payload data".getBytes(); - Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>(); - Either<NonMetaArtifactInfo, Boolean> eitherNonMetaArtifact = CsarUtils.validateNonMetaArtifact(artifactPath, payloadData, collectedWarningMessages); - assertTrue(eitherNonMetaArtifact.isRight() ); - assertTrue( !collectedWarningMessages.isEmpty() ); - } +public class CsarUtilsTest extends BeConfDependentTest { + + @InjectMocks + CsarUtils testSubject; + + @Mock + private ArtifactCassandraDao artifactCassandraDao; + + @Mock + private ComponentsUtils componentsUtils; + + @Mock + private ToscaExportHandler toscaExportUtils; + + @Mock + private SdcSchemaFilesCassandraDao sdcSchemaFilesCassandraDao; + + @Mock + private ToscaOperationFacade toscaOperationFacade; + + @Mock + private ArtifactsBusinessLogic artifactsBusinessLogic; + + @Before + public void setUpMock() throws Exception { + MockitoAnnotations.initMocks(this); + + } + + private NonMetaArtifactInfo createNonMetaArtifactInfoTestSubject() { + return new CsarUtils.NonMetaArtifactInfo("mock", "mock", ArtifactTypeEnum.AAI_SERVICE_MODEL, + ArtifactGroupTypeEnum.DEPLOYMENT, new byte[0], "mock", true); + } + + @Test + public void testCreateCsar() { + Component component = new Resource(); + Map<String, ArtifactDefinition> toscaArtifacts = new HashMap<>(); + ArtifactDefinition artifact = new ArtifactDefinition(); + artifact.setArtifactName("artifactName"); + artifact.setEsId("esId"); + toscaArtifacts.put("assettoscatemplate", artifact); + + component.setToscaArtifacts(toscaArtifacts); + + Mockito.when(artifactCassandraDao.getArtifact(Mockito.any(String.class))) + .thenReturn(Either.right(CassandraOperationStatus.GENERAL_ERROR)); + + Mockito.when(componentsUtils.convertFromStorageResponse(Mockito.any(StorageOperationStatus.class))) + .thenReturn(ActionStatus.GENERAL_ERROR); + + testSubject.createCsar(component, true, true); + } + + @Test + public void testCreateCsarWithGenerateCsarZipResponseIsLeft() { + Component component = new Resource(); + Map<String, ArtifactDefinition> toscaArtifacts = new HashMap<>(); + ArtifactDefinition artifact = new ArtifactDefinition(); + artifact.setArtifactName("artifactName"); + artifact.setEsId("esId"); + artifact.setArtifactUUID("artifactUUID"); + artifact.setArtifactType("YANG"); + toscaArtifacts.put("assettoscatemplate", artifact); + + component.setToscaArtifacts(toscaArtifacts); + component.setDeploymentArtifacts(toscaArtifacts); + component.setArtifacts(toscaArtifacts); + ESArtifactData artifactData = new ESArtifactData(); + byte[] data = "value".getBytes(); + artifactData.setDataAsArray(data); + + ToscaTemplate toscaTemplate = new ToscaTemplate("version"); + List<Triple<String, String, Component>> dependencies = new ArrayList<>(); + toscaTemplate.setDependencies(dependencies); + + List<SdcSchemaFilesData> filesData = new ArrayList<>(); + SdcSchemaFilesData filedata = new SdcSchemaFilesData(); + filedata.setPayloadAsArray(data); + filesData.add(filedata); + + Mockito.when(artifactCassandraDao.getArtifact(Mockito.any(String.class))).thenReturn(Either.left(artifactData)); + + Mockito.when(componentsUtils.convertFromStorageResponse(Mockito.any(StorageOperationStatus.class))) + .thenReturn(ActionStatus.GENERAL_ERROR); + + Mockito.when(toscaExportUtils.getDependencies(Mockito.any(Component.class))) + .thenReturn(Either.left(toscaTemplate)); + + Mockito.when( + sdcSchemaFilesCassandraDao.getSpecificSchemaFiles(Mockito.any(String.class), Mockito.any(String.class))) + .thenReturn(Either.left(filesData)); + + testSubject.createCsar(component, false, true); + } + + @Test + public void testGenerateCsarZipThrowsIOException() { + Deencapsulation.invoke(testSubject, "generateCsarZip", byte[].class, byte[].class, new Resource(), true, false, + false); + } + + @Test + public void testPopulateZipWhenGetDependenciesIsRight() { + Component component = new Service(); + boolean getFromCS = false; + + Map<String, ArtifactDefinition> toscaArtifacts = new HashMap<>(); + ArtifactDefinition artifact = new ArtifactDefinition(); + artifact.setArtifactName("artifactName"); + artifact.setEsId("esId"); + artifact.setArtifactUUID("artifactUUID"); + artifact.setArtifactType("YANG"); + toscaArtifacts.put("assettoscatemplate", artifact); + + component.setToscaArtifacts(toscaArtifacts); + component.setDeploymentArtifacts(toscaArtifacts); + component.setArtifacts(toscaArtifacts); + component.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + ESArtifactData artifactData = new ESArtifactData(); + byte[] data = "value".getBytes(); + artifactData.setDataAsArray(data); + + ToscaRepresentation tosca = new ToscaRepresentation(); + tosca.setMainYaml("value"); + + Mockito.when(artifactCassandraDao.getArtifact(Mockito.any(String.class))).thenReturn(Either.left(artifactData)); + + Mockito.when(toscaExportUtils.exportComponent(Mockito.any(Component.class))).thenReturn(Either.left(tosca)); + + Mockito.when(toscaExportUtils.getDependencies(Mockito.any(Component.class))) + .thenReturn(Either.right(ToscaError.GENERAL_ERROR)); + + try (ByteArrayOutputStream out = new ByteArrayOutputStream(); ZipOutputStream zip = new ZipOutputStream(out);) { + Deencapsulation.invoke(testSubject, "populateZip", component, getFromCS, zip, false, false); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Test + public void testPopulateZipWhenExportComponentIsRight() { + Component component = new Resource(); + boolean getFromCS = false; + + Map<String, ArtifactDefinition> toscaArtifacts = new HashMap<>(); + ArtifactDefinition artifact = new ArtifactDefinition(); + artifact.setArtifactName("artifactName"); + artifact.setEsId("esId"); + artifact.setArtifactUUID("artifactUUID"); + artifact.setArtifactType("YANG"); + toscaArtifacts.put("assettoscatemplate", artifact); + + component.setToscaArtifacts(toscaArtifacts); + component.setDeploymentArtifacts(toscaArtifacts); + component.setArtifacts(toscaArtifacts); + component.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + ESArtifactData artifactData = new ESArtifactData(); + byte[] data = "value".getBytes(); + artifactData.setDataAsArray(data); + + Mockito.when(toscaExportUtils.exportComponent(Mockito.any(Component.class))) + .thenReturn(Either.right(ToscaError.GENERAL_ERROR)); + + try (ByteArrayOutputStream out = new ByteArrayOutputStream(); ZipOutputStream zip = new ZipOutputStream(out);) { + Deencapsulation.invoke(testSubject, "populateZip", component, getFromCS, zip, false, false); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Test + public void testPopulateZipWhenComponentIsServiceAndCollectComponentCsarDefinitionIsRight() { + Component component = new Service(); + boolean getFromCS = false; + + Map<String, ArtifactDefinition> toscaArtifacts = new HashMap<>(); + ArtifactDefinition artifact = new ArtifactDefinition(); + artifact.setArtifactName("artifactName"); + artifact.setEsId("esId"); + artifact.setArtifactUUID("artifactUUID"); + artifact.setArtifactType("YANG"); + artifact.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); + artifact.setDescription("description"); + artifact.setArtifactLabel("artifactLabel"); + toscaArtifacts.put("assettoscatemplate", artifact); + + component.setToscaArtifacts(toscaArtifacts); + component.setDeploymentArtifacts(toscaArtifacts); + component.setArtifacts(toscaArtifacts); + component.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + component.setVersion("1.0"); + component.setLastUpdaterUserId("userId"); + component.setUniqueId("uid"); + ESArtifactData artifactData = new ESArtifactData(); + byte[] data = "value".getBytes(); + artifactData.setDataAsArray(data); + + List<SdcSchemaFilesData> filesData = new ArrayList<>(); + SdcSchemaFilesData filedata = new SdcSchemaFilesData(); + filedata.setPayloadAsArray(data); + filesData.add(filedata); + + ToscaTemplate toscaTemplate = new ToscaTemplate("version"); + List<Triple<String, String, Component>> dependencies = new ArrayList<>(); + Triple<String, String, Component> triple = Triple.of("fileName", "cassandraId", component); + dependencies.add(triple); + toscaTemplate.setDependencies(dependencies); + + ToscaRepresentation tosca = new ToscaRepresentation(); + tosca.setMainYaml("value"); + + Mockito.when(artifactCassandraDao.getArtifact(Mockito.any(String.class))).thenReturn(Either.left(artifactData)); + + Mockito.when(toscaExportUtils.exportComponent(Mockito.any(Component.class))).thenReturn(Either.left(tosca)); + + Mockito.when(toscaExportUtils.getDependencies(Mockito.any(Component.class))) + .thenReturn(Either.left(toscaTemplate)); + + Mockito.when( + sdcSchemaFilesCassandraDao.getSpecificSchemaFiles(Mockito.any(String.class), Mockito.any(String.class))) + .thenReturn(Either.left(filesData)); + + Mockito.when(toscaOperationFacade.getToscaElement(Mockito.any(String.class))) + .thenReturn(Either.right(StorageOperationStatus.BAD_REQUEST)); + + Mockito.when(artifactsBusinessLogic.validateUserExists(Mockito.any(String.class), Mockito.any(String.class), + Mockito.any(Boolean.class))).thenReturn(Either.left(new User())); + + Mockito.when(artifactsBusinessLogic.validateAndHandleArtifact(Mockito.any(String.class), + Mockito.any(ComponentTypeEnum.class), Mockito.any(ArtifactOperationInfo.class), Mockito.isNull(), + Mockito.any(ArtifactDefinition.class), Mockito.any(String.class), Mockito.any(String.class), + Mockito.isNull(), Mockito.isNull(), Mockito.any(User.class), Mockito.any(Component.class), + Mockito.any(Boolean.class), Mockito.any(Boolean.class), Mockito.any(Boolean.class))) + .thenReturn(Either.left(Mockito.any(Either.class))); + + try (ByteArrayOutputStream out = new ByteArrayOutputStream(); ZipOutputStream zip = new ZipOutputStream(out);) { + Deencapsulation.invoke(testSubject, "populateZip", component, getFromCS, zip, true, true); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Test + public void testPopulateZipWhenGetEntryDataIsRight() { + Component component = new Service(); + boolean getFromCS = true; + + Map<String, ArtifactDefinition> toscaArtifacts = new HashMap<>(); + ArtifactDefinition artifact = new ArtifactDefinition(); + artifact.setArtifactName("artifactName"); + artifact.setEsId("esId"); + artifact.setArtifactUUID("artifactUUID"); + artifact.setArtifactType("YANG"); + artifact.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); + artifact.setDescription("description"); + artifact.setArtifactLabel("artifactLabel"); + toscaArtifacts.put("assettoscatemplate", artifact); + + component.setToscaArtifacts(toscaArtifacts); + component.setDeploymentArtifacts(toscaArtifacts); + component.setArtifacts(toscaArtifacts); + component.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + component.setVersion("1.0"); + component.setLastUpdaterUserId("userId"); + component.setUniqueId("uid"); + ESArtifactData artifactData = new ESArtifactData(); + byte[] data = "value".getBytes(); + artifactData.setDataAsArray(data); + + ToscaTemplate toscaTemplate = new ToscaTemplate("version"); + List<Triple<String, String, Component>> dependencies = new ArrayList<>(); + Triple<String, String, Component> triple = Triple.of("fileName", "", component); + dependencies.add(triple); + toscaTemplate.setDependencies(dependencies); + + Mockito.when(artifactCassandraDao.getArtifact(Mockito.any(String.class))).thenReturn(Either.left(artifactData)); + + Mockito.when(toscaExportUtils.exportComponent(Mockito.any(Component.class))) + .thenReturn(Either.right(ToscaError.GENERAL_ERROR)); + + Mockito.when(toscaExportUtils.getDependencies(Mockito.any(Component.class))) + .thenReturn(Either.left(toscaTemplate)); + + try (ByteArrayOutputStream out = new ByteArrayOutputStream(); ZipOutputStream zip = new ZipOutputStream(out);) { + Deencapsulation.invoke(testSubject, "populateZip", component, getFromCS, zip, true, true); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Test + public void testPopulateZipWhenGetEntryDataOfInnerComponentIsRight() { + Component component = new Service(); + boolean getFromCS = false; + + Map<String, ArtifactDefinition> toscaArtifacts = new HashMap<>(); + ArtifactDefinition artifact = new ArtifactDefinition(); + artifact.setArtifactName("artifactName"); + artifact.setEsId("esId"); + artifact.setArtifactUUID("artifactUUID"); + artifact.setArtifactType("YANG"); + artifact.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); + artifact.setDescription("description"); + artifact.setArtifactLabel("artifactLabel"); + toscaArtifacts.put("assettoscatemplate", artifact); + + component.setToscaArtifacts(toscaArtifacts); + component.setDeploymentArtifacts(toscaArtifacts); + component.setArtifacts(toscaArtifacts); + component.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + component.setVersion("1.0"); + component.setLastUpdaterUserId("userId"); + component.setUniqueId("uid"); + ESArtifactData artifactData = new ESArtifactData(); + byte[] data = "value".getBytes(); + artifactData.setDataAsArray(data); + + ToscaTemplate toscaTemplate = new ToscaTemplate("version"); + List<Triple<String, String, Component>> dependencies = new ArrayList<>(); + Triple<String, String, Component> triple = Triple.of("fileName", "", component); + dependencies.add(triple); + toscaTemplate.setDependencies(dependencies); + + ToscaRepresentation tosca = new ToscaRepresentation(); + tosca.setMainYaml("value"); + + Mockito.when(artifactCassandraDao.getArtifact(Mockito.any(String.class))).thenReturn(Either.left(artifactData)); + + Mockito.when(toscaExportUtils.exportComponent(Mockito.any(Component.class))).thenReturn(Either.left(tosca), + Either.left(tosca), Either.right(ToscaError.GENERAL_ERROR)); + + Mockito.when(toscaExportUtils.getDependencies(Mockito.any(Component.class))) + .thenReturn(Either.left(toscaTemplate)); + + try (ByteArrayOutputStream out = new ByteArrayOutputStream(); ZipOutputStream zip = new ZipOutputStream(out);) { + Deencapsulation.invoke(testSubject, "populateZip", component, getFromCS, zip, true, true); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Test + public void testPopulateZipWhenLatestSchemaFilesFromCassandraIsRight() { + Component component = new Service(); + boolean getFromCS = false; + + Map<String, ArtifactDefinition> toscaArtifacts = new HashMap<>(); + ArtifactDefinition artifact = new ArtifactDefinition(); + artifact.setArtifactName("artifactName"); + artifact.setEsId("esId"); + artifact.setArtifactUUID("artifactUUID"); + artifact.setArtifactType("YANG"); + artifact.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); + artifact.setDescription("description"); + artifact.setArtifactLabel("artifactLabel"); + toscaArtifacts.put("assettoscatemplate", artifact); + + component.setToscaArtifacts(toscaArtifacts); + component.setDeploymentArtifacts(toscaArtifacts); + component.setArtifacts(toscaArtifacts); + component.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + component.setVersion("1.0"); + component.setLastUpdaterUserId("userId"); + component.setUniqueId("uid"); + ESArtifactData artifactData = new ESArtifactData(); + byte[] data = "value".getBytes(); + artifactData.setDataAsArray(data); + + ToscaTemplate toscaTemplate = new ToscaTemplate("version"); + List<Triple<String, String, Component>> dependencies = new ArrayList<>(); + Triple<String, String, Component> triple = Triple.of("fileName", "", component); + dependencies.add(triple); + toscaTemplate.setDependencies(dependencies); + + ToscaRepresentation tosca = new ToscaRepresentation(); + tosca.setMainYaml("value"); + + Mockito.when(artifactCassandraDao.getArtifact(Mockito.any(String.class))).thenReturn(Either.left(artifactData)); + + Mockito.when(toscaExportUtils.exportComponent(Mockito.any(Component.class))).thenReturn(Either.left(tosca)); + + Mockito.when(toscaExportUtils.getDependencies(Mockito.any(Component.class))) + .thenReturn(Either.left(toscaTemplate)); + + Mockito.when( + sdcSchemaFilesCassandraDao.getSpecificSchemaFiles(Mockito.any(String.class), Mockito.any(String.class))) + .thenReturn(Either.right(CassandraOperationStatus.GENERAL_ERROR)); + + try (ByteArrayOutputStream out = new ByteArrayOutputStream(); ZipOutputStream zip = new ZipOutputStream(out);) { + Deencapsulation.invoke(testSubject, "populateZip", component, getFromCS, zip, true, true); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Test + public void testPopulateZipWhenAddSchemaFilesFromCassandraIsRight() { + Component component = new Service(); + boolean getFromCS = false; + + Map<String, ArtifactDefinition> toscaArtifacts = new HashMap<>(); + ArtifactDefinition artifact = new ArtifactDefinition(); + artifact.setArtifactName("artifactName"); + artifact.setEsId("esId"); + artifact.setArtifactUUID("artifactUUID"); + artifact.setArtifactType("YANG"); + artifact.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); + artifact.setDescription("description"); + artifact.setArtifactLabel("artifactLabel"); + toscaArtifacts.put("assettoscatemplate", artifact); + + component.setToscaArtifacts(toscaArtifacts); + component.setDeploymentArtifacts(toscaArtifacts); + component.setArtifacts(toscaArtifacts); + component.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + component.setVersion("1.0"); + component.setLastUpdaterUserId("userId"); + component.setUniqueId("uid"); + ESArtifactData artifactData = new ESArtifactData(); + byte[] data = "value".getBytes(); + artifactData.setDataAsArray(data); + + ToscaTemplate toscaTemplate = new ToscaTemplate("version"); + List<Triple<String, String, Component>> dependencies = new ArrayList<>(); + Triple<String, String, Component> triple = Triple.of("fileName", "", component); + dependencies.add(triple); + toscaTemplate.setDependencies(dependencies); + + ToscaRepresentation tosca = new ToscaRepresentation(); + tosca.setMainYaml("value"); + + List<SdcSchemaFilesData> schemaList = new ArrayList<>(); + SdcSchemaFilesData schemaData = new SdcSchemaFilesData(); + schemaData.setPayloadAsArray(null); + schemaList.add(schemaData); + + Mockito.when(artifactCassandraDao.getArtifact(Mockito.any(String.class))).thenReturn(Either.left(artifactData)); + + Mockito.when(toscaExportUtils.exportComponent(Mockito.any(Component.class))).thenReturn(Either.left(tosca)); + + Mockito.when(toscaExportUtils.getDependencies(Mockito.any(Component.class))) + .thenReturn(Either.left(toscaTemplate)); + + Mockito.when( + sdcSchemaFilesCassandraDao.getSpecificSchemaFiles(Mockito.any(String.class), Mockito.any(String.class))) + .thenReturn(Either.left(schemaList)); + + try (ByteArrayOutputStream out = new ByteArrayOutputStream(); ZipOutputStream zip = new ZipOutputStream(out);) { + Deencapsulation.invoke(testSubject, "populateZip", component, getFromCS, zip, true, true); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Test + public void testPopulateZipWhenHandleAllAAIArtifactsInDataModelIsRight() { + Component component = new Service(); + boolean getFromCS = false; + + Map<String, ArtifactDefinition> toscaArtifacts = new HashMap<>(); + ArtifactDefinition artifact = new ArtifactDefinition(); + artifact.setArtifactName("artifactName"); + artifact.setEsId("esId"); + artifact.setArtifactUUID("artifactUUID"); + artifact.setArtifactType("YANG"); + artifact.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); + artifact.setDescription("description"); + artifact.setArtifactLabel("artifactLabel"); + toscaArtifacts.put("assettoscatemplate", artifact); + + component.setToscaArtifacts(toscaArtifacts); + component.setDeploymentArtifacts(toscaArtifacts); + component.setArtifacts(toscaArtifacts); + component.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + component.setVersion("1.0"); + component.setLastUpdaterUserId("userId"); + component.setUniqueId("uid"); + ESArtifactData artifactData = new ESArtifactData(); + byte[] data = "value".getBytes(); + artifactData.setDataAsArray(data); + + ToscaTemplate toscaTemplate = new ToscaTemplate("version"); + List<Triple<String, String, Component>> dependencies = new ArrayList<>(); + Triple<String, String, Component> triple = Triple.of("fileName", "", component); + dependencies.add(triple); + toscaTemplate.setDependencies(dependencies); + + ToscaRepresentation tosca = new ToscaRepresentation(); + tosca.setMainYaml("value"); + + List<SdcSchemaFilesData> schemaList = new ArrayList<>(); + SdcSchemaFilesData schemaData = new SdcSchemaFilesData(); + schemaData.setPayloadAsArray(data); + schemaList.add(schemaData); + + Mockito.when(artifactCassandraDao.getArtifact(Mockito.any(String.class))).thenReturn(Either.left(artifactData)); + + Mockito.when(toscaExportUtils.exportComponent(Mockito.any(Component.class))).thenReturn(Either.left(tosca)); + + Mockito.when(toscaExportUtils.getDependencies(Mockito.any(Component.class))) + .thenReturn(Either.left(toscaTemplate)); + + Mockito.when( + sdcSchemaFilesCassandraDao.getSpecificSchemaFiles(Mockito.any(String.class), Mockito.any(String.class))) + .thenReturn(Either.left(schemaList)); + + Mockito.when(artifactsBusinessLogic.validateUserExists(Mockito.any(String.class), Mockito.any(String.class), + Mockito.any(Boolean.class))).thenReturn(Either.right(new ResponseFormat(500))); + + try (ByteArrayOutputStream out = new ByteArrayOutputStream(); ZipOutputStream zip = new ZipOutputStream(out);) { + Deencapsulation.invoke(testSubject, "populateZip", component, getFromCS, zip, true, true); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Test + public void testAddSchemaFilesFromCassandra() { + try (ByteArrayOutputStream out = new ByteArrayOutputStream(); + ZipOutputStream zip = new ZipOutputStream(out); + ByteArrayOutputStream outMockStream = new ByteArrayOutputStream(); + ZipOutputStream outMock = new ZipOutputStream(outMockStream);) { + + outMock.putNextEntry(new ZipEntry("mock1")); + outMock.write(new byte[1]); + outMock.putNextEntry(new ZipEntry("mock2")); + outMock.write(new byte[3]); + outMock.close(); + byte[] byteArray = outMockStream.toByteArray(); + Deencapsulation.invoke(testSubject, "addSchemaFilesFromCassandra", zip, byteArray); + } catch (Exception e) { + e.printStackTrace(); + } + + } + + @Test + public void testAddInnerComponentsToCache() { + Map<String, ImmutableTriple<String, String, Component>> componentCache = new HashMap<>(); + Component childComponent = new Resource(); + Component componentRI = new Service(); + List<ComponentInstance> componentInstances = new ArrayList<>(); + ComponentInstance instance = new ComponentInstance(); + instance.setComponentUid("resourceUid"); + componentInstances.add(instance); + childComponent.setComponentInstances(componentInstances); + + Map<String, ArtifactDefinition> toscaArtifacts = new HashMap<>(); + ArtifactDefinition artifact = new ArtifactDefinition(); + artifact.setArtifactName("artifactName"); + artifact.setEsId("esId"); + artifact.setArtifactUUID("artifactUUID"); + artifact.setArtifactType("YANG"); + artifact.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); + artifact.setDescription("description"); + artifact.setArtifactLabel("artifactLabel"); + toscaArtifacts.put("assettoscatemplate", artifact); + + componentRI.setToscaArtifacts(toscaArtifacts); + + Mockito.when(toscaOperationFacade.getToscaElement(Mockito.any(String.class))) + .thenReturn(Either.left(componentRI)); + + Deencapsulation.invoke(testSubject, "addInnerComponentsToCache", componentCache, childComponent); + } + + @Test + public void testAddInnerComponentsToCacheWhenGetToscaElementIsRight() { + Map<String, ImmutableTriple<String, String, Component>> componentCache = new HashMap<>(); + Component childComponent = new Resource(); + + List<ComponentInstance> componentInstances = new ArrayList<>(); + ComponentInstance instance = new ComponentInstance(); + componentInstances.add(instance); + childComponent.setComponentInstances(componentInstances); + + Map<String, ArtifactDefinition> toscaArtifacts = new HashMap<>(); + ArtifactDefinition artifact = new ArtifactDefinition(); + artifact.setArtifactName("artifactName"); + artifact.setEsId("esId"); + artifact.setArtifactUUID("artifactUUID"); + artifact.setArtifactType("YANG"); + artifact.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); + artifact.setDescription("description"); + artifact.setArtifactLabel("artifactLabel"); + toscaArtifacts.put("assettoscatemplate", artifact); + + Component componentRI = new Service(); + + componentRI.setToscaArtifacts(toscaArtifacts); + + Mockito.when(toscaOperationFacade.getToscaElement(Mockito.any(String.class))) + .thenReturn(Either.right(StorageOperationStatus.BAD_REQUEST)); + + Deencapsulation.invoke(testSubject, "addInnerComponentsToCache", componentCache, childComponent); + } + + @Test + public void testAddComponentToCache() { + Map<String, ImmutableTriple<String, String, Component>> componentCache = new HashMap<>(); + String id = "id"; + String fileName = "fileName"; + Component component = new Resource(); + component.setInvariantUUID("key"); + component.setVersion("1.0"); + + Component cachedComponent = new Resource(); + cachedComponent.setVersion("0.3"); + + componentCache.put("key", new ImmutableTriple<String, String, Component>(id, fileName, cachedComponent)); + + Deencapsulation.invoke(testSubject, "addComponentToCache", componentCache, id, fileName, component); + } + + @Test + public void testWriteComponentInterface() { + String fileName = "name.hello"; + ToscaRepresentation tosca = new ToscaRepresentation(); + tosca.setMainYaml("value"); + + Mockito.when(toscaExportUtils.exportComponentInterface(Mockito.any(Component.class))) + .thenReturn(Either.left(tosca)); + + try (ByteArrayOutputStream out = new ByteArrayOutputStream(); ZipOutputStream zip = new ZipOutputStream(out);) { + Deencapsulation.invoke(testSubject, "writeComponentInterface", new Resource(), zip, fileName); + } catch (IOException e) { + e.printStackTrace(); + } + + } + + @Test + public void testHandleAAIArtifacts() { + Component component = new Service(); + component.setComponentType(ComponentTypeEnum.SERVICE); + byte[] data = "value".getBytes(); + + List<ImmutablePair<Component, byte[]>> generatorInputs = new ArrayList<>(); + generatorInputs.add(new ImmutablePair<Component, byte[]>(component, data)); + + Map<String, ArtifactDefinition> toscaArtifacts = new HashMap<>(); + ArtifactDefinition artifact = new ArtifactDefinition(); + artifact.setArtifactName("artifactName"); + artifact.setEsId("esId"); + artifact.setArtifactUUID("artifactUUID"); + artifact.setArtifactType("YANG"); + artifact.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); + artifact.setDescription("description"); + artifact.setArtifactLabel("artifactLabel"); + toscaArtifacts.put("assettoscatemplate", artifact); + component.setToscaArtifacts(toscaArtifacts); + component.setVersion("1.3"); + + Deencapsulation.invoke(testSubject, "handleAAIArtifacts", component, false, generatorInputs); + } + + @Test + public void testHandleAllAAIArtifactsInDataModelWhenArtifactOperationDeleteAndCreateIsRight() { + Component component = new Resource(); + List<ArtifactDefinition> artifactsFromAAI = new ArrayList<>(); + ArtifactDefinition AAIartifact = new ArtifactDefinition(); + AAIartifact.setArtifactLabel("artifactLabel"); + AAIartifact.setGenerated(true); + Map<String, ArtifactDefinition> deploymentArtifacts = new HashMap<>(); + artifactsFromAAI.add(AAIartifact); + ArtifactDefinition artifact = new ArtifactDefinition(); + artifact.setArtifactLabel("label"); + artifact.setGenerated(true); + deploymentArtifacts.put("label", artifact); + component.setDeploymentArtifacts(deploymentArtifacts); + component.setArtifacts(deploymentArtifacts); + component.setLastUpdaterUserId("userId"); + component.setUniqueId("id"); + + Mockito.when(artifactsBusinessLogic.validateUserExists(Mockito.any(String.class), Mockito.any(String.class), + Mockito.any(Boolean.class))).thenReturn(Either.left(new User())); + + Mockito.when(artifactsBusinessLogic.validateAndHandleArtifact(Mockito.any(String.class), + Mockito.any(ComponentTypeEnum.class), Mockito.any(ArtifactOperationInfo.class), Mockito.isNull(), + Mockito.any(ArtifactDefinition.class), Mockito.any(String.class), Mockito.any(String.class), + Mockito.isNull(), Mockito.isNull(), Mockito.any(User.class), Mockito.any(Component.class), + Mockito.any(Boolean.class), Mockito.any(Boolean.class), Mockito.any(Boolean.class))) + .thenReturn(Either.right(new ResponseFormat())); + + Deencapsulation.invoke(testSubject, "handleAllAAIArtifactsInDataModel", component, artifactsFromAAI, true, + true); + } + + @Test + public void testCheckAaiForUpdateWithGetGeneratedFalse() { + Component component = new Resource(); + ArtifactDefinition artifact = new ArtifactDefinition(); + artifact.setArtifactLabel("label"); + artifact.setGenerated(false); + Map<String, ArtifactDefinition> deploymentArtifacts = new HashMap<>(); + deploymentArtifacts.put("label", artifact); + component.setDeploymentArtifacts(deploymentArtifacts); + + Deencapsulation.invoke(testSubject, "checkAaiForUpdate", component, artifact); + } + + @Test + public void testCheckAaiForUpdateWithGetGeneratedTrue() { + Component component = new Resource(); + ArtifactDefinition artifact = new ArtifactDefinition(); + artifact.setArtifactLabel("label"); + artifact.setGenerated(true); + Map<String, ArtifactDefinition> deploymentArtifacts = new HashMap<>(); + deploymentArtifacts.put("label", artifact); + component.setDeploymentArtifacts(deploymentArtifacts); + + Deencapsulation.invoke(testSubject, "checkAaiForUpdate", component, artifact); + } + + @Test + public void testCheckAaiForUpdateWithDeploymentArtifactIsNull() { + Component component = new Resource(); + ArtifactDefinition artifact = new ArtifactDefinition(); + artifact.setArtifactLabel("label1"); + artifact.setGenerated(true); + Map<String, ArtifactDefinition> deploymentArtifacts = new HashMap<>(); + deploymentArtifacts.put("label", artifact); + component.setDeploymentArtifacts(deploymentArtifacts); + + Deencapsulation.invoke(testSubject, "checkAaiForUpdate", component, artifact); + } + + @Test + public void testGetEntryData() { + String cassandraId = "id"; + Component childComponent = new Resource(); + + Mockito.when(artifactCassandraDao.getArtifact(Mockito.any(String.class))) + .thenReturn(Either.right(CassandraOperationStatus.GENERAL_ERROR)); + + Deencapsulation.invoke(testSubject, "getEntryData", cassandraId, childComponent); + } + + @Test + public void testGetLatestSchemaFilesFromCassandraWhenListOfSchemasIsEmpty() { + List<SdcSchemaFilesData> filesData = new ArrayList<>(); + + Mockito.when( + sdcSchemaFilesCassandraDao.getSpecificSchemaFiles(Mockito.any(String.class), Mockito.any(String.class))) + .thenReturn(Either.left(filesData)); + Deencapsulation.invoke(testSubject, "getLatestSchemaFilesFromCassandra"); + } + + @Test + public void testArtifactGenerator() { + Component component = new Resource(); + + component.setVersion("1.0"); + + Deencapsulation.invoke(testSubject, "artifactGenerator", new ArrayList<>(), ArtifactType.class, component); + } + + @Test + public void testExtractVfcsArtifactsFromCsar() { + String key = "Artifacts/org.openecomp.resource.some/path/to/resource"; + byte[] data = "value".getBytes(); + + Map<String, byte[]> csar = new HashMap<>(); + csar.put(key, data); + + CsarUtils.extractVfcsArtifactsFromCsar(csar); + } + + @Test + public void testAddExtractedVfcArtifactWhenArtifactsContainsExtractedArtifactKey() { + ImmutablePair<String, ArtifactDefinition> extractedVfcArtifact = new ImmutablePair<String, ArtifactDefinition>( + "key", new ArtifactDefinition()); + Map<String, List<ArtifactDefinition>> artifacts = new HashMap<>(); + artifacts.put("key", new ArrayList<>()); + + Deencapsulation.invoke(testSubject, "addExtractedVfcArtifact", extractedVfcArtifact, artifacts); + } + + @Test + public void testAddExtractedVfcArtifactWhenArtifactsDoesntContainsExtractedArtifactKey() { + ImmutablePair<String, ArtifactDefinition> extractedVfcArtifact = new ImmutablePair<String, ArtifactDefinition>( + "key", new ArtifactDefinition()); + Map<String, List<ArtifactDefinition>> artifacts = new HashMap<>(); + artifacts.put("key1", new ArrayList<>()); + + Deencapsulation.invoke(testSubject, "addExtractedVfcArtifact", extractedVfcArtifact, artifacts); + } + + @Test + public void testExtractVfcArtifact() { + String path = "path/to/informational/artificat"; + Map<String, byte[]> map = new HashMap<>(); + map.put(path, "value".getBytes()); + Entry<String, byte[]> entry = map.entrySet().iterator().next(); + + Deencapsulation.invoke(testSubject, "extractVfcArtifact", entry, new HashMap<>()); + } + + @Test + public void testDetectArtifactGroupTypeWithExceptionBeingCaught() { + Deencapsulation.invoke(testSubject, "detectArtifactGroupType", "type", Map.class); + } + + @Test + public void testDetectArtifactGroupTypeWWhenCollectedWarningMessagesContainesKey() { + Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>(); + + collectedWarningMessages.put("Warning - unrecognized artifact group type {} was received.", new HashSet<>()); + Deencapsulation.invoke(testSubject, "detectArtifactGroupType", "type", collectedWarningMessages); + } + + @Test + public void testNonMetaArtifactInfoCtor() { + createNonMetaArtifactInfoTestSubject(); + } + + @Test + public void testNonMetaArtifactInfoGetPath() { + NonMetaArtifactInfo testSubject = createNonMetaArtifactInfoTestSubject(); + + testSubject.getPath(); + } + + @Test + public void testNonMetaArtifactInfoGetArtifactName() { + NonMetaArtifactInfo testSubject = createNonMetaArtifactInfoTestSubject(); + + testSubject.getArtifactName(); + } + + @Test + public void testNonMetaArtifactInfoGetArtifactType() { + NonMetaArtifactInfo testSubject = createNonMetaArtifactInfoTestSubject(); + + testSubject.getArtifactType(); + } + + @Test + public void testNonMetaArtifactInfoGetDisplayName() { + NonMetaArtifactInfo testSubject = createNonMetaArtifactInfoTestSubject(); + + testSubject.getDisplayName(); + } + + @Test + public void testNonMetaArtifactInfoGetArtifactGroupType() { + NonMetaArtifactInfo testSubject = createNonMetaArtifactInfoTestSubject(); + + testSubject.getArtifactGroupType(); + } + + @Test + public void testNonMetaArtifactInfoGetArtifactLabel() { + NonMetaArtifactInfo testSubject = createNonMetaArtifactInfoTestSubject(); + + testSubject.getArtifactLabel(); + } + + @Test + public void testNonMetaArtifactInfoGetIsFromCsar() { + NonMetaArtifactInfo testSubject = createNonMetaArtifactInfoTestSubject(); + + testSubject.isFromCsar(); + } + + @Test + public void testNonMetaArtifactInfoGetPayloadData() { + NonMetaArtifactInfo testSubject = createNonMetaArtifactInfoTestSubject(); + + testSubject.getPayloadData(); + } + + @Test + public void testNonMetaArtifactInfoGetArtifaactChecksum() { + NonMetaArtifactInfo testSubject = createNonMetaArtifactInfoTestSubject(); + + testSubject.getArtifactChecksum(); + } + + @Test + public void testNonMetaArtifactInfoGetArtifactUniqueId() { + NonMetaArtifactInfo testSubject = createNonMetaArtifactInfoTestSubject(); + + testSubject.getArtifactUniqueId(); + } + + @Test + public void testNonMetaArtifactInfosetArtifactUniqueId() { + NonMetaArtifactInfo testSubject = createNonMetaArtifactInfoTestSubject(); + + testSubject.setArtifactUniqueId("artifactUniqueId"); + } + + @Test + public void testValidateNonMetaArtifactWithExceptionCaught() { + CsarUtils.validateNonMetaArtifact("", new byte[0], new HashMap<>()); + } + + @Test + public void testWriteAllFilesToCsarWhenWriteOperationsArtifactsToCsarIsRight() { + Component component = new Resource(); + Map<String, ArtifactDefinition> toscaArtifacts = new HashMap<>(); + ArtifactDefinition artifact = new ArtifactDefinition(); + artifact.setArtifactName("artifactName"); + artifact.setEsId("esId"); + artifact.setArtifactUUID("artifactUUID"); + artifact.setArtifactType("YANG"); + toscaArtifacts.put("assettoscatemplate", artifact); + + component.setToscaArtifacts(toscaArtifacts); + component.setDeploymentArtifacts(toscaArtifacts); + component.setArtifacts(toscaArtifacts); + Map<String, InterfaceDefinition> interfaces = new HashMap<>(); + InterfaceDefinition interfaceDef = new InterfaceDefinition(); + Map<String, OperationDataDefinition> operations = new HashMap<>(); + OperationDataDefinition operation = new OperationDataDefinition(); + ArtifactDataDefinition implementation = new ArtifactDataDefinition(); + implementation.setArtifactUUID("artifactUUID"); + implementation.setArtifactName("artifactName"); + operation.setImplementation(implementation); + operations.put("key", operation); + interfaceDef.setOperations(operations); + interfaces.put("key", interfaceDef); + ((Resource) component).setInterfaces(interfaces); + + ESArtifactData artifactData = new ESArtifactData(); + byte[] data = "value".getBytes(); + artifactData.setDataAsArray(data); + + ToscaTemplate toscaTemplate = new ToscaTemplate("version"); + List<Triple<String, String, Component>> dependencies = new ArrayList<>(); + toscaTemplate.setDependencies(dependencies); + + List<SdcSchemaFilesData> filesData = new ArrayList<>(); + SdcSchemaFilesData filedata = new SdcSchemaFilesData(); + filedata.setPayloadAsArray(data); + filesData.add(filedata); + + Mockito.when(artifactCassandraDao.getArtifact(Mockito.any(String.class))).thenReturn(Either.left(artifactData), + Either.right(CassandraOperationStatus.GENERAL_ERROR)); + + Mockito.when(componentsUtils.convertFromStorageResponse(Mockito.any(StorageOperationStatus.class))) + .thenReturn(ActionStatus.GENERAL_ERROR); + + Mockito.when(toscaExportUtils.getDependencies(Mockito.any(Component.class))) + .thenReturn(Either.left(toscaTemplate)); + + Mockito.when( + sdcSchemaFilesCassandraDao.getSpecificSchemaFiles(Mockito.any(String.class), Mockito.any(String.class))) + .thenReturn(Either.left(filesData)); + + testSubject.createCsar(component, false, true); + } + + @Test + public void testWriteOperationsArtifactsToCsarWhenComponentIsService() { + Component component = new Service(); + + try (ByteArrayOutputStream out = new ByteArrayOutputStream(); ZipOutputStream zip = new ZipOutputStream(out);) { + Deencapsulation.invoke(testSubject, "writeOperationsArtifactsToCsar", component, zip); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Test + public void testWriteOperationsArtifactsToCsarWhenOperationGetImplementaionIsNull() { + Component component = new Resource(); + Map<String, InterfaceDefinition> interfaces = new HashMap<>(); + InterfaceDefinition interfaceDef = new InterfaceDefinition(); + Map<String, OperationDataDefinition> operations = new HashMap<>(); + operations.put("key", new OperationDataDefinition()); + interfaceDef.setOperations(operations); + interfaces.put("key", interfaceDef); + + ((Resource) component).setInterfaces(interfaces); + + try (ByteArrayOutputStream out = new ByteArrayOutputStream(); ZipOutputStream zip = new ZipOutputStream(out);) { + Deencapsulation.invoke(testSubject, "writeOperationsArtifactsToCsar", component, zip); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Test + public void testWriteOperationsArtifactsToCsarWhenOperationGetArtifactNameIsNull() { + Component component = new Resource(); + + Map<String, InterfaceDefinition> interfaces = new HashMap<>(); + InterfaceDefinition interfaceDef = new InterfaceDefinition(); + Map<String, OperationDataDefinition> operations = new HashMap<>(); + OperationDataDefinition operation = new OperationDataDefinition(); + ArtifactDataDefinition implementation = new ArtifactDataDefinition(); + operation.setImplementation(implementation); + operations.put("key", operation); + interfaceDef.setOperations(operations); + interfaces.put("key", interfaceDef); + ((Resource) component).setInterfaces(interfaces); + + try (ByteArrayOutputStream out = new ByteArrayOutputStream(); ZipOutputStream zip = new ZipOutputStream(out);) { + Deencapsulation.invoke(testSubject, "writeOperationsArtifactsToCsar", component, zip); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Test + public void testWriteOperationsArtifactsToCsarWhenGettingArtifactFromCassandra() { + Component component = new Resource(); + + Map<String, InterfaceDefinition> interfaces = new HashMap<>(); + InterfaceDefinition interfaceDef = new InterfaceDefinition(); + Map<String, OperationDataDefinition> operations = new HashMap<>(); + OperationDataDefinition operation = new OperationDataDefinition(); + ArtifactDataDefinition implementation = new ArtifactDataDefinition(); + implementation.setArtifactName("artifactName"); + implementation.setArtifactUUID("artifactUUID"); + operation.setImplementation(implementation); + operations.put("key", operation); + interfaceDef.setOperations(operations); + interfaceDef.setToscaResourceName("toscaResourceName"); + interfaces.put("key", interfaceDef); + ((Resource) component).setInterfaces(interfaces); + component.setNormalizedName("normalizedName"); + + ESArtifactData data = new ESArtifactData(); + data.setDataAsArray("data".getBytes()); + + Mockito.when(artifactCassandraDao.getArtifact(Mockito.any(String.class))).thenReturn(Either.left(data)); + + try (ByteArrayOutputStream out = new ByteArrayOutputStream(); ZipOutputStream zip = new ZipOutputStream(out);) { + Deencapsulation.invoke(testSubject, "writeOperationsArtifactsToCsar", component, zip); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Test + public void testWriteOperationsArtifactsToCsarWhenNullPointerExceptionIsCaught() { + Component component = new Resource(); + + Map<String, InterfaceDefinition> interfaces = new HashMap<>(); + InterfaceDefinition interfaceDef = new InterfaceDefinition(); + Map<String, OperationDataDefinition> operations = new HashMap<>(); + OperationDataDefinition operation = new OperationDataDefinition(); + ArtifactDataDefinition implementation = new ArtifactDataDefinition(); + implementation.setArtifactName("artifactName"); + implementation.setArtifactUUID("artifactUUID"); + operation.setImplementation(implementation); + operations.put("key", operation); + interfaceDef.setOperations(operations); + interfaceDef.setToscaResourceName("toscaResourceName"); + interfaces.put("key", interfaceDef); + ((Resource) component).setInterfaces(interfaces); + component.setNormalizedName("normalizedName"); + + Mockito.when(artifactCassandraDao.getArtifact(Mockito.any(String.class))) + .thenReturn(Either.left(new ESArtifactData())); + + try (ByteArrayOutputStream out = new ByteArrayOutputStream(); ZipOutputStream zip = new ZipOutputStream(out);) { + Deencapsulation.invoke(testSubject, "writeOperationsArtifactsToCsar", component, zip); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Test + public void testWriteArtifactDefinition() { + Component component = new Service(); + List<ArtifactDefinition> artifactDefinitionList = new ArrayList<>(); + String artifactPathAndFolder = ""; + + ArtifactDefinition artifact = new ArtifactDefinition(); + artifact.setArtifactType(ArtifactTypeEnum.HEAT_ENV.getType()); + artifactDefinitionList.add(artifact); + + try (ByteArrayOutputStream out = new ByteArrayOutputStream(); ZipOutputStream zip = new ZipOutputStream(out);) { + Deencapsulation.invoke(testSubject, "writeArtifactDefinition", component, zip, artifactDefinitionList, + artifactPathAndFolder, false); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Test + public void testCollectComponentCsarDefinitionWhenComponentIsServiceAndGetToscaElementIsLeft() { + Component component = new Service(); + component.setUniqueId("uniqueId"); + List<ComponentInstance> resourceInstances = new ArrayList<>(); + ComponentInstance instance = new ComponentInstance(); + instance.setComponentUid("resourceUid"); + instance.setOriginType(OriginTypeEnum.SERVICE); + resourceInstances.add(instance); + component.setComponentInstances(resourceInstances); + + Map<String, ArtifactDefinition> toscaArtifacts = new HashMap<>(); + ArtifactDefinition artifact = new ArtifactDefinition(); + artifact.setArtifactName("artifactName"); + artifact.setEsId("esId"); + artifact.setArtifactUUID("artifactUUID"); + artifact.setArtifactType("YANG"); + toscaArtifacts.put("assettoscatemplate", artifact); + + component.setToscaArtifacts(toscaArtifacts); + component.setDeploymentArtifacts(toscaArtifacts); + component.setArtifacts(toscaArtifacts); + + Mockito.when(toscaOperationFacade.getToscaElement(Mockito.any(String.class))).thenReturn(Either.left(component), + Either.right(StorageOperationStatus.BAD_REQUEST)); + + Deencapsulation.invoke(testSubject, "collectComponentCsarDefinition", component); + + } + + @Test + public void testCollectComponentTypeArtifactsWhenFetchedComponentHasComponentInstances() { + Component component = new Service(); + Component fetchedComponent = new Resource(); + component.setUniqueId("uniqueId"); + List<ComponentInstance> resourceInstances = new ArrayList<>(); + ComponentInstance instance = new ComponentInstance(); + instance.setComponentUid("resourceUid"); + instance.setOriginType(OriginTypeEnum.SERVICE); + resourceInstances.add(instance); + component.setComponentInstances(resourceInstances); + fetchedComponent.setComponentInstances(resourceInstances); + + Map<String, ArtifactDefinition> toscaArtifacts = new HashMap<>(); + ArtifactDefinition artifact = new ArtifactDefinition(); + artifact.setArtifactName("artifactName"); + artifact.setEsId("esId"); + artifact.setArtifactUUID("artifactUUID"); + artifact.setArtifactType("YANG"); + toscaArtifacts.put("assettoscatemplate", artifact); + + component.setToscaArtifacts(toscaArtifacts); + component.setDeploymentArtifacts(toscaArtifacts); + component.setArtifacts(toscaArtifacts); + + fetchedComponent.setToscaArtifacts(toscaArtifacts); + fetchedComponent.setDeploymentArtifacts(toscaArtifacts); + fetchedComponent.setArtifacts(toscaArtifacts); + + Mockito.when(toscaOperationFacade.getToscaElement(Mockito.any(String.class))).thenReturn(Either.left(component), + Either.left(fetchedComponent), Either.right(StorageOperationStatus.BAD_REQUEST)); + + Deencapsulation.invoke(testSubject, "collectComponentCsarDefinition", component); + } + + @Test + public void testCollectComponentTypeArtifactsWhenFetchedComponentDontHaveComponentInstances() { + Component component = new Service(); + Component fetchedComponent = new Resource(); + component.setUniqueId("uniqueId"); + List<ComponentInstance> resourceInstances = new ArrayList<>(); + ComponentInstance instance = new ComponentInstance(); + instance.setComponentUid("resourceUid"); + instance.setOriginType(OriginTypeEnum.SERVICE); + + Map<String, ArtifactDefinition> toscaArtifacts = new HashMap<>(); + ArtifactDefinition artifact = new ArtifactDefinition(); + artifact.setArtifactName("artifactName"); + artifact.setEsId("esId"); + artifact.setArtifactUUID("artifactUUID"); + artifact.setArtifactType("PLAN"); + toscaArtifacts.put("assettoscatemplate", artifact); + + instance.setDeploymentArtifacts(toscaArtifacts); + + resourceInstances.add(instance); + component.setComponentInstances(resourceInstances); + + component.setToscaArtifacts(toscaArtifacts); + component.setDeploymentArtifacts(toscaArtifacts); + component.setArtifacts(toscaArtifacts); + + fetchedComponent.setToscaArtifacts(toscaArtifacts); + fetchedComponent.setDeploymentArtifacts(toscaArtifacts); + fetchedComponent.setArtifacts(toscaArtifacts); + + Mockito.when(toscaOperationFacade.getToscaElement(Mockito.any(String.class))).thenReturn(Either.left(component), + Either.left(fetchedComponent)); + + Deencapsulation.invoke(testSubject, "collectComponentCsarDefinition", component); + } + + @Test + public void testValidateNonMetaArtifactHappyScenario() { + String artifactPath = "Artifacts/Deployment/YANG_XML/myYang.xml"; + byte[] payloadData = "some payload data".getBytes(); + Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>(); + Either<NonMetaArtifactInfo, Boolean> eitherNonMetaArtifact = CsarUtils.validateNonMetaArtifact(artifactPath, + payloadData, collectedWarningMessages); + assertTrue(eitherNonMetaArtifact.isLeft()); + assertTrue(collectedWarningMessages.isEmpty()); + + artifactPath = "Artifacts/Informational/OTHER/someArtifact.xml"; + eitherNonMetaArtifact = CsarUtils.validateNonMetaArtifact(artifactPath, payloadData, collectedWarningMessages); + assertTrue(eitherNonMetaArtifact.isLeft()); + assertTrue(collectedWarningMessages.isEmpty()); + } + + @Test + public void testValidateNonMetaArtifactScenarioWithWarnnings() { + String artifactPath = "Artifacts/Deployment/Buga/myYang.xml"; + byte[] payloadData = "some payload data".getBytes(); + Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>(); + Either<NonMetaArtifactInfo, Boolean> eitherNonMetaArtifact = CsarUtils.validateNonMetaArtifact(artifactPath, + payloadData, collectedWarningMessages); + assertTrue(eitherNonMetaArtifact.isLeft()); + + artifactPath = "Artifacts/Informational/Buga2/someArtifact.xml"; + eitherNonMetaArtifact = CsarUtils.validateNonMetaArtifact(artifactPath, payloadData, collectedWarningMessages); + assertTrue(eitherNonMetaArtifact.isLeft()); + + assertTrue(collectedWarningMessages.size() == 1); + assertTrue(collectedWarningMessages.values().iterator().next().size() == 2); + } + + @Test + public void testValidateNonMetaArtifactUnhappyScenario() { + String artifactPath = "Artifacts/Buga/YANG_XML/myYang.xml"; + byte[] payloadData = "some payload data".getBytes(); + Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>(); + Either<NonMetaArtifactInfo, Boolean> eitherNonMetaArtifact = CsarUtils.validateNonMetaArtifact(artifactPath, + payloadData, collectedWarningMessages); + assertTrue(eitherNonMetaArtifact.isRight()); + assertTrue(!collectedWarningMessages.isEmpty()); + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/PropertyConvertorTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/PropertyConvertorTest.java index 139de137d9..18e2ec9fa0 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/PropertyConvertorTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/PropertyConvertorTest.java @@ -16,6 +16,7 @@ import java.util.Map; import org.junit.Before; import org.junit.Test; import org.openecomp.sdc.be.components.utils.PropertyDataDefinitionBuilder; +import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; import org.openecomp.sdc.be.model.DataTypeDefinition; import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.Resource; @@ -38,6 +39,15 @@ public class PropertyConvertorTest { dataTypes.put(property.getName(), new DataTypeDefinition()); } + @Test + public void testConvertProperty() { + SchemaDefinition schema = new SchemaDefinition(); + schema.setProperty(property); + + property.setSchema(schema); + + PropertyConvertor.getInstance().convertProperty(dataTypes, property, true); + } @Test public void convertPropertyWhenValueAndDefaultNull() { @@ -141,5 +151,28 @@ public class PropertyConvertorTest { ToscaProperty toscaProperty = PropertyConvertor.getInstance().convertProperty(Collections.emptyMap(), property1, false); assertThat(toscaProperty.getDefaultp()).isEqualTo("/"); } + + @Test + public void testConvertToToscaObject() { + dataTypes.put(ToscaPropertyType.Root.getType(), new DataTypeDefinition()); + + PropertyConvertor.getInstance().convertToToscaObject(ToscaPropertyType.Root.getType(), "", "innerType", dataTypes); + } + + @Test + public void testConvertToToscaObjectWhenPropertyTypeAndInnerTypeNull() { + dataTypes.put(ToscaPropertyType.Root.getType(), new DataTypeDefinition()); + + PropertyConvertor.getInstance().convertToToscaObject(null, "value", null, dataTypes); + } + + @Test + public void testConvertToToscaObjectWhenIsScalarTypeIsNotNull() { + DataTypeDefinition def = new DataTypeDefinition(); + def.setName("integer"); + dataTypes.put("type", def); + + PropertyConvertor.getInstance().convertToToscaObject("type", "value", "innerType", dataTypes); + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/ToscaExportHandlerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/ToscaExportHandlerTest.java new file mode 100644 index 0000000000..92819ca012 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/ToscaExportHandlerTest.java @@ -0,0 +1,1244 @@ +package org.openecomp.sdc.be.tosca; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Supplier; + +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.apache.commons.lang3.tuple.Triple; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.sdc.be.components.BeConfDependentTest; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathElementDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; +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.ComponentInstance; +import org.openecomp.sdc.be.model.ComponentInstanceInput; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; +import org.openecomp.sdc.be.model.ComponentParametersView; +import org.openecomp.sdc.be.model.DataTypeDefinition; +import org.openecomp.sdc.be.model.GroupDefinition; +import org.openecomp.sdc.be.model.GroupInstance; +import org.openecomp.sdc.be.model.GroupProperty; +import org.openecomp.sdc.be.model.InputDefinition; +import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.be.model.RelationshipInfo; +import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; +import org.openecomp.sdc.be.model.RequirementDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; +import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.openecomp.sdc.be.model.category.SubCategoryDefinition; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.tosca.model.SubstitutionMapping; +import org.openecomp.sdc.be.tosca.model.ToscaCapability; +import org.openecomp.sdc.be.tosca.model.ToscaGroupTemplate; +import org.openecomp.sdc.be.tosca.model.ToscaMetadata; +import org.openecomp.sdc.be.tosca.model.ToscaNodeTemplate; +import org.openecomp.sdc.be.tosca.model.ToscaNodeType; +import org.openecomp.sdc.be.tosca.model.ToscaTemplate; +import org.openecomp.sdc.be.tosca.model.ToscaTemplateRequirement; +import org.openecomp.sdc.be.tosca.model.ToscaTopolgyTemplate; + +import fj.data.Either; +import mockit.Deencapsulation; + +public class ToscaExportHandlerTest extends BeConfDependentTest { + + @InjectMocks + ToscaExportHandler testSubject; + + @Mock + ApplicationDataTypeCache dataTypeCache; + + @Mock + ToscaOperationFacade toscaOperationFacade; + + @Mock + CapabiltyRequirementConvertor capabiltyRequirementConvertor; + + @Before + public void setUpMock() throws Exception { + MockitoAnnotations.initMocks(this); + } + + private Resource getNewResource() { + Resource resource = new Resource(); + List<CategoryDefinition> categories = new ArrayList<>(); + CategoryDefinition category = new CategoryDefinition(); + List<SubCategoryDefinition> subcategories = new ArrayList<>(); + SubCategoryDefinition subcategory = new SubCategoryDefinition(); + + subcategory.setName("name"); + subcategories.add(subcategory); + category.setName("name"); + category.setSubcategories(subcategories); + categories.add(category); + + resource.setCategories(categories); + resource.setVersion("version"); + resource.setVendorName("vendorName"); + resource.setVendorRelease("vendorRelease"); + resource.setResourceVendorModelNumber("resourceVendorModelNumber"); + + return resource; + } + + private Service getNewService() { + Service service = new Service(); + List<CategoryDefinition> categories = new ArrayList<>(); + CategoryDefinition category = new CategoryDefinition(); + List<SubCategoryDefinition> subcategories = new ArrayList<>(); + SubCategoryDefinition subcategory = new SubCategoryDefinition(); + + subcategory.setName("name"); + subcategories.add(subcategory); + category.setName("name"); + category.setSubcategories(subcategories); + categories.add(category); + + service.setCategories(categories); + service.setComponentType(ComponentTypeEnum.SERVICE); + service.setServiceType("serviceType"); + service.setServiceRole("serviceRole"); + service.setEnvironmentContext("environmentContext"); + + return service; + } + + @Test + public void testExportComponent() throws Exception { + Component component = getNewResource(); + Either<ToscaRepresentation, ToscaError> result; + + Mockito.when(dataTypeCache.getAll()).thenReturn(Either.left(new HashMap<>())); + Mockito.when(capabiltyRequirementConvertor.convertRequirements(Mockito.any(Resource.class), + Mockito.any(ToscaNodeType.class))).thenReturn(Either.left(new ToscaNodeType())); + + // default test when component is Resource + result = testSubject.exportComponent(component); + + component = getNewService(); + Mockito.when(capabiltyRequirementConvertor.convertRequirements(Mockito.any(Service.class), + Mockito.any(ToscaNodeType.class))).thenReturn(Either.left(new ToscaNodeType())); + Mockito.when(dataTypeCache.getAll()).thenReturn(Either.right(TitanOperationStatus.NOT_FOUND)); + + // default test when component is Service + result = testSubject.exportComponent(component); + } + + @Test + public void testExportComponentInterface() throws Exception { + Component component = getNewResource(); + Either<ToscaRepresentation, ToscaError> result; + + ((Resource) component).setInterfaces(new HashMap<>()); + + Mockito.when(dataTypeCache.getAll()).thenReturn(Either.right(TitanOperationStatus.NOT_FOUND)); + + // default test when convertInterfaceNodeType is right + result = testSubject.exportComponentInterface(component); + + Mockito.when(dataTypeCache.getAll()).thenReturn(Either.left(new HashMap<>())); + Mockito.when(capabiltyRequirementConvertor.convertRequirements(Mockito.any(Resource.class), + Mockito.any(ToscaNodeType.class))).thenReturn(Either.left(new ToscaNodeType())); + + // default test when convertInterfaceNodeType is left + result = testSubject.exportComponentInterface(component); + + } + + @Test + public void testCreateToscaRepresentation() throws Exception { + ToscaTemplate toscaTemplate = new ToscaTemplate(""); + ToscaRepresentation result; + + // default test + result = testSubject.createToscaRepresentation(toscaTemplate); + } + + @Test + public void testGetDependencies() throws Exception { + + Component component = new Resource(); + Either<ToscaTemplate, ToscaError> result; + + // default test + result = testSubject.getDependencies(component); + } + + @Test + public void testConvertToscaTemplate() throws Exception { + + Component component = getNewResource(); + ToscaTemplate toscaNode = new ToscaTemplate(""); + Either<ToscaTemplate, ToscaError> result; + List<ComponentInstance> resourceInstances = new ArrayList<>(); + ComponentInstance instance = new ComponentInstance(); + + instance.setOriginType(OriginTypeEnum.SERVICE); + instance.setSourceModelUid("targetModelUid"); + resourceInstances.add(instance); + + component.setComponentInstances(resourceInstances); + + Mockito.when(dataTypeCache.getAll()).thenReturn(Either.left(new HashMap<>())); + Mockito.when(capabiltyRequirementConvertor.getOriginComponent(Mockito.any(Map.class), + Mockito.any(ComponentInstance.class))).thenReturn(Either.right(false)); + + // default test + result = Deencapsulation.invoke(testSubject, "convertToscaTemplate", component, toscaNode); + } + + @Test + public void testConvertToscaTemplateWhenComponentContainsGroup() { + Component component = getNewResource(); + ToscaTemplate toscaNode = new ToscaTemplate(""); + Either<ToscaTemplate, ToscaError> result; + component.setComponentInstances(new ArrayList<>()); + + List<GroupDefinition> groups = new ArrayList<>(); + GroupDefinition group = new GroupDefinition(); + List<String> artifacts = new ArrayList<>(); + artifacts.add("artifact"); + group.setType("org.openecomp.groups.VfModule"); + group.setArtifacts(artifacts); + groups.add(group); + component.setGroups(groups); + + Map<String, String[]> substitutionMappingMap = new HashMap<>(); + String[] array = { "value1", "value2" }; + substitutionMappingMap.put("key", array); + + Mockito.when(capabiltyRequirementConvertor.convertSubstitutionMappingCapabilities(Mockito.any(Map.class), + Mockito.any(Component.class))).thenReturn(Either.left(substitutionMappingMap)); + + Mockito.when(capabiltyRequirementConvertor.convertSubstitutionMappingRequirements(Mockito.any(Map.class), + Mockito.any(Component.class), Mockito.any(SubstitutionMapping.class))) + .thenReturn(Either.left(new SubstitutionMapping())); + + Mockito.when(dataTypeCache.getAll()).thenReturn(Either.left(new HashMap<>())); + + // test component contains group + result = Deencapsulation.invoke(testSubject, "convertToscaTemplate", component, toscaNode); + } + + @Test + public void testConvertToscaTemplateWhenComponentIsService() throws Exception { + Component component = getNewService(); + ToscaTemplate toscaNode = new ToscaTemplate(""); + Either<ToscaTemplate, ToscaError> result; + component.setComponentInstances(new ArrayList<>()); + + List<GroupDefinition> groups = new ArrayList<>(); + GroupDefinition group = new GroupDefinition(); + List<String> artifacts = new ArrayList<>(); + artifacts.add("artifact"); + group.setType("org.openecomp.groups.VfModule"); + group.setArtifacts(artifacts); + groups.add(group); + component.setGroups(groups); + + Map<String, String[]> substitutionMappingMap = new HashMap<>(); + String[] array = { "value1", "value2" }; + substitutionMappingMap.put("key", array); + + Mockito.when(capabiltyRequirementConvertor.convertSubstitutionMappingCapabilities(Mockito.any(Map.class), + Mockito.any(Component.class))).thenReturn(Either.left(substitutionMappingMap)); + + Mockito.when(capabiltyRequirementConvertor.convertSubstitutionMappingRequirements(Mockito.any(Map.class), + Mockito.any(Component.class), Mockito.any(SubstitutionMapping.class))) + .thenReturn(Either.left(new SubstitutionMapping())); + + Mockito.when(dataTypeCache.getAll()).thenReturn(Either.left(new HashMap<>())); + + // test component contains group + result = Deencapsulation.invoke(testSubject, "convertToscaTemplate", component, toscaNode); + } + + @Test + public void testFillInputs() throws Exception { + Component component = new Resource(); + ToscaTopolgyTemplate topologyTemplate = new ToscaTopolgyTemplate(); + Map<String, DataTypeDefinition> dataTypes = new HashMap<>(); + Either<ToscaTopolgyTemplate, ToscaError> result; + + InputDefinition input = new InputDefinition(); + + List<InputDefinition> inputs = new ArrayList<>(); + inputs.add(input); + component.setInputs(inputs); + + // default test + result = Deencapsulation.invoke(testSubject, "fillInputs", component, topologyTemplate, dataTypes); + } + + @Test + public void testConvertMetadata_1() throws Exception { + + Component component = getNewResource(); + boolean isInstance = true; + ComponentInstance componentInstance = new ComponentInstance(); + componentInstance.setOriginType(OriginTypeEnum.ServiceProxy); + componentInstance.setSourceModelInvariant("targetModelInvariant"); + + ToscaMetadata result; + + // default test + + result = Deencapsulation.invoke(testSubject, "convertMetadata", component, isInstance, componentInstance); + } + + @Test + public void testFillImports() throws Exception { + + Component component = getNewService(); + ToscaTemplate toscaTemplate = new ToscaTemplate(""); + Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> result; + + ComponentInstance instance = new ComponentInstance(); + List<ComponentInstance> resourceInstances = new ArrayList<>(); + instance.setComponentUid("name"); + resourceInstances.add(instance); + component.setComponentInstances(resourceInstances); + Map<String, ArtifactDefinition> toscaArtifacts = new HashMap<>(); + ArtifactDefinition artifact = new ArtifactDefinition(); + artifact.setArtifactName("name.name2"); + toscaArtifacts.put("assettoscatemplate", artifact); + component.setToscaArtifacts(toscaArtifacts); + + Mockito.when(toscaOperationFacade.getToscaFullElement(Mockito.any(String.class))) + .thenReturn(Either.left(component)); + + // default test + result = Deencapsulation.invoke(testSubject, "fillImports", component, toscaTemplate); + } + + @Test + public void testCreateDependency() throws Exception { + + Map<String, Component> componentCache = new HashMap<>(); + List<Map<String, Map<String, String>>> imports = new ArrayList<>(); + List<Triple<String, String, Component>> dependecies = new ArrayList<>(); + ComponentInstance ci = new ComponentInstance(); + Component component = getNewResource(); + + Map<String, ArtifactDefinition> toscaArtifacts = new HashMap<>(); + ArtifactDefinition artifact = new ArtifactDefinition(); + artifact.setArtifactName("name.name2"); + toscaArtifacts.put("assettoscatemplate", artifact); + component.setToscaArtifacts(toscaArtifacts); + ci.setComponentUid("name"); + ci.setOriginType(OriginTypeEnum.ServiceProxy); + ci.setSourceModelUid("modelName"); + + Mockito.when(toscaOperationFacade.getToscaFullElement(Mockito.eq("name"))).thenReturn(Either.left(component)); + + Mockito.when(toscaOperationFacade.getToscaFullElement(Mockito.eq("modelName"))) + .thenReturn(Either.left(new Service())); + + // default test + Deencapsulation.invoke(testSubject, "createDependency", componentCache, imports, dependecies, ci); + } + + @Test + public void testGetInterfaceFilename() throws Exception { + String artifactName = "artifact.name"; + String result; + + // default test + result = ToscaExportHandler.getInterfaceFilename(artifactName); + } + + @Test + public void testConvertNodeType() throws Exception { + Component component = new Resource(); + ToscaTemplate toscaNode = new ToscaTemplate(""); + Map<String, ToscaNodeType> nodeTypes = new HashMap<>(); + Either<ToscaTemplate, ToscaError> result; + + Mockito.when(dataTypeCache.getAll()).thenReturn(Either.right(TitanOperationStatus.ALREADY_EXIST)); + + // default test + result = Deencapsulation.invoke(testSubject, "convertNodeType", component, toscaNode, nodeTypes); + } + + @Test + public void testConvertInterfaceNodeType() throws Exception { + Component component = getNewResource(); + ToscaTemplate toscaNode = new ToscaTemplate(""); + Map<String, ToscaNodeType> nodeTypes = new HashMap<>(); + Either<ToscaTemplate, ToscaError> result; + List<InputDefinition> inputs = new ArrayList<>(); + inputs.add(new InputDefinition()); + component.setInputs(inputs); + + Mockito.when(dataTypeCache.getAll()).thenReturn(Either.left(new HashMap<>())); + + Mockito.when(capabiltyRequirementConvertor.convertRequirements(Mockito.any(Resource.class), + Mockito.any(ToscaNodeType.class))).thenReturn(Either.left(new ToscaNodeType())); + + // default test + result = Deencapsulation.invoke(testSubject, "convertInterfaceNodeType", component, toscaNode, nodeTypes); + } + + @Test + public void testConvertReqCapAndTypeName() throws Exception { + Component component = new Resource(); + ToscaTemplate toscaNode = new ToscaTemplate(""); + Map<String, ToscaNodeType> nodeTypes = new HashMap(); + ToscaNodeType toscaNodeType = new ToscaNodeType(); + Map<String, DataTypeDefinition> dataTypes = new HashMap<>(); + Either<ToscaTemplate, ToscaError> result; + + Mockito.when( + capabiltyRequirementConvertor.convertCapabilities(Mockito.any(Resource.class), Mockito.any(Map.class))) + .thenReturn(new HashMap<>()); + + Mockito.when(capabiltyRequirementConvertor.convertRequirements(Mockito.any(Resource.class), + Mockito.any(ToscaNodeType.class))).thenReturn(Either.left(new ToscaNodeType())); + + // default test + result = Deencapsulation.invoke(testSubject, "convertReqCapAndTypeName", component, toscaNode, nodeTypes, + toscaNodeType, dataTypes); + + component = new Service(); + + Mockito.when(capabiltyRequirementConvertor.convertRequirements(Mockito.any(Service.class), + Mockito.any(ToscaNodeType.class))).thenReturn(Either.left(new ToscaNodeType())); + + // test when component is service + result = Deencapsulation.invoke(testSubject, "convertReqCapAndTypeName", component, toscaNode, nodeTypes, + toscaNodeType, dataTypes); + } + + @Test + public void testConvertNodeTemplates() throws Exception { + Component component = getNewResource(); + List<ComponentInstance> componentInstances = new ArrayList<>(); + Map<String, List<ComponentInstanceProperty>> componentInstancesProperties = new HashMap<>(); + Map<String, Component> componentCache = new HashMap<>(); + Map<String, DataTypeDefinition> dataTypes = new HashMap<>(); + ToscaTopolgyTemplate topologyTemplate = new ToscaTopolgyTemplate(); + Either<Map<String, ToscaNodeTemplate>, ToscaError> result; + Map<String, List<ComponentInstanceInput>> componentInstancesInputs = new HashMap<>(); + List<ComponentInstanceInput> inputs = new ArrayList<>(); + inputs.add(new ComponentInstanceInput()); + componentInstancesInputs.put("key", inputs); + List<RequirementCapabilityRelDef> resourceInstancesRelations = new ArrayList<>(); + RequirementCapabilityRelDef reldef = new RequirementCapabilityRelDef(); + reldef.setFromNode("node"); + resourceInstancesRelations.add(reldef); + component.setComponentInstancesRelations(resourceInstancesRelations); + + ComponentInstance instance = new ComponentInstance(); + instance.setUniqueId("id"); + instance.setComponentUid("uid"); + instance.setOriginType(OriginTypeEnum.ServiceProxy); + List<GroupInstance> groupInstances = new ArrayList<>(); + GroupInstance groupInst = new GroupInstance(); + List<String> artifacts = new ArrayList<>(); + artifacts.add("artifact"); + groupInst.setArtifacts(artifacts); + groupInst.setType("type"); + groupInstances.add(groupInst); + instance.setGroupInstances(groupInstances); + componentInstances.add(instance); + + component.setComponentInstancesInputs(componentInstancesInputs); + component.setInvariantUUID("uuid"); + component.setUUID("uuid"); + component.setDescription("desc"); + + componentCache.put("uid", component); + + componentInstancesProperties.put("id", new ArrayList<>()); + componentInstancesInputs.put("id", new ArrayList<>()); + + Mockito.when(capabiltyRequirementConvertor.getOriginComponent(Mockito.any(Map.class), + Mockito.any(ComponentInstance.class))).thenReturn(Either.left(component)); + + Mockito.when(capabiltyRequirementConvertor.convertComponentInstanceCapabilties( + Mockito.any(ComponentInstance.class), Mockito.any(Map.class), Mockito.any(ToscaNodeTemplate.class))) + .thenReturn(Either.left(new ToscaNodeTemplate())); + + // default test + result = Deencapsulation.invoke(testSubject, "convertNodeTemplates", component, componentInstances, + componentInstancesProperties, componentCache, dataTypes, topologyTemplate); + } + + @Test + public void testConvertNodeTemplatesWhenComponentIsService() throws Exception { + Component component = getNewService(); + List<ComponentInstance> componentInstances = new ArrayList<>(); + Map<String, List<ComponentInstanceProperty>> componentInstancesProperties = new HashMap<>(); + Map<String, Component> componentCache = new HashMap<>(); + Map<String, DataTypeDefinition> dataTypes = new HashMap<>(); + ToscaTopolgyTemplate topologyTemplate = new ToscaTopolgyTemplate(); + Either<Map<String, ToscaNodeTemplate>, ToscaError> result; + Map<String, List<ComponentInstanceInput>> componentInstancesInputs = new HashMap<>(); + List<ComponentInstanceInput> inputs = new ArrayList<>(); + inputs.add(new ComponentInstanceInput()); + componentInstancesInputs.put("key", inputs); + List<RequirementCapabilityRelDef> resourceInstancesRelations = new ArrayList<>(); + RequirementCapabilityRelDef reldef = new RequirementCapabilityRelDef(); + reldef.setFromNode("node"); + resourceInstancesRelations.add(reldef); + component.setComponentInstancesRelations(resourceInstancesRelations); + + ComponentInstance instance = new ComponentInstance(); + instance.setUniqueId("id"); + instance.setComponentUid("uid"); + instance.setOriginType(OriginTypeEnum.ServiceProxy); + List<GroupInstance> groupInstances = new ArrayList<>(); + GroupInstance groupInst = new GroupInstance(); + List<String> artifacts = new ArrayList<>(); + artifacts.add("artifact"); + groupInst.setArtifacts(artifacts); + groupInst.setType("type"); + groupInstances.add(groupInst); + instance.setGroupInstances(groupInstances); + componentInstances.add(instance); + + component.setComponentInstancesInputs(componentInstancesInputs); + component.setInvariantUUID("uuid"); + component.setUUID("uuid"); + component.setDescription("desc"); + + Map<String, ForwardingPathDataDefinition> forwardingPaths = new HashMap<>(); + ForwardingPathDataDefinition path = new ForwardingPathDataDefinition(); + ListDataDefinition<ForwardingPathElementDataDefinition> list = new ListDataDefinition<>(); + path.setPathElements(list); + forwardingPaths.put("key", path); + + ((Service) component).setForwardingPaths(forwardingPaths); + + componentCache.put("uid", component); + + componentInstancesProperties.put("id", new ArrayList<>()); + componentInstancesInputs.put("id", new ArrayList<>()); + + Mockito.when(capabiltyRequirementConvertor.getOriginComponent(Mockito.any(Map.class), + Mockito.any(ComponentInstance.class))).thenReturn(Either.left(component)); + + Mockito.when(capabiltyRequirementConvertor.convertComponentInstanceCapabilties( + Mockito.any(ComponentInstance.class), Mockito.any(Map.class), Mockito.any(ToscaNodeTemplate.class))) + .thenReturn(Either.left(new ToscaNodeTemplate())); + + // default test + result = Deencapsulation.invoke(testSubject, "convertNodeTemplates", component, componentInstances, + componentInstancesProperties, componentCache, dataTypes, topologyTemplate); + } + + @Test + public void testConvertNodeTemplatesWhenConvertComponentInstanceCapabilitiesIsRight() throws Exception { + Component component = getNewResource(); + List<ComponentInstance> componentInstances = new ArrayList<>(); + Map<String, List<ComponentInstanceProperty>> componentInstancesProperties = new HashMap<>(); + Map<String, Component> componentCache = new HashMap<>(); + Map<String, DataTypeDefinition> dataTypes = new HashMap<>(); + ToscaTopolgyTemplate topologyTemplate = new ToscaTopolgyTemplate(); + Either<Map<String, ToscaNodeTemplate>, ToscaError> result; + Map<String, List<ComponentInstanceInput>> componentInstancesInputs = new HashMap<>(); + List<ComponentInstanceInput> inputs = new ArrayList<>(); + inputs.add(new ComponentInstanceInput()); + componentInstancesInputs.put("key", inputs); + List<RequirementCapabilityRelDef> resourceInstancesRelations = new ArrayList<>(); + RequirementCapabilityRelDef reldef = new RequirementCapabilityRelDef(); + reldef.setFromNode("node"); + resourceInstancesRelations.add(reldef); + component.setComponentInstancesRelations(resourceInstancesRelations); + + ComponentInstance instance = new ComponentInstance(); + instance.setUniqueId("id"); + instance.setComponentUid("uid"); + instance.setOriginType(OriginTypeEnum.ServiceProxy); + componentInstances.add(instance); + + component.setComponentInstancesInputs(componentInstancesInputs); + component.setInvariantUUID("uuid"); + component.setUUID("uuid"); + component.setDescription("desc"); + + componentCache.put("uid", component); + + Mockito.when(capabiltyRequirementConvertor.getOriginComponent(Mockito.any(Map.class), + Mockito.any(ComponentInstance.class))).thenReturn(Either.left(component)); + + Mockito.when(capabiltyRequirementConvertor.convertComponentInstanceCapabilties( + Mockito.any(ComponentInstance.class), Mockito.any(Map.class), Mockito.any(ToscaNodeTemplate.class))) + .thenReturn(Either.right(ToscaError.GENERAL_ERROR)); + + // default test + result = Deencapsulation.invoke(testSubject, "convertNodeTemplates", component, componentInstances, + componentInstancesProperties, componentCache, dataTypes, topologyTemplate); + } + + @Test + public void testConvetNodeTemplateWhenGetOriginComponentIsRight() throws Exception { + Component component = getNewResource(); + List<ComponentInstance> componentInstances = new ArrayList<>(); + Map<String, List<ComponentInstanceProperty>> componentInstancesProperties = new HashMap<>(); + Map<String, Component> componentCache = new HashMap<>(); + Map<String, DataTypeDefinition> dataTypes = new HashMap<>(); + ToscaTopolgyTemplate topologyTemplate = new ToscaTopolgyTemplate(); + Either<Map<String, ToscaNodeTemplate>, ToscaError> result; + Map<String, List<ComponentInstanceInput>> componentInstancesInputs = new HashMap<>(); + List<ComponentInstanceInput> inputs = new ArrayList<>(); + inputs.add(new ComponentInstanceInput()); + componentInstancesInputs.put("key", inputs); + List<RequirementCapabilityRelDef> resourceInstancesRelations = new ArrayList<>(); + RequirementCapabilityRelDef reldef = new RequirementCapabilityRelDef(); + reldef.setFromNode("id"); + resourceInstancesRelations.add(reldef); + component.setComponentInstancesRelations(resourceInstancesRelations); + + ComponentInstance instance = new ComponentInstance(); + instance.setUniqueId("id"); + instance.setComponentUid("uid"); + instance.setOriginType(OriginTypeEnum.ServiceProxy); + componentInstances.add(instance); + + component.setComponentInstancesInputs(componentInstancesInputs); + component.setInvariantUUID("uuid"); + component.setUUID("uuid"); + component.setDescription("desc"); + + componentCache.put("uid", component); + + Mockito.when(capabiltyRequirementConvertor.getOriginComponent(Mockito.any(Map.class), + Mockito.any(ComponentInstance.class))).thenReturn(Either.right(false)); + + // default test + result = Deencapsulation.invoke(testSubject, "convertNodeTemplates", component, componentInstances, + componentInstancesProperties, componentCache, dataTypes, topologyTemplate); + } + + @Test + public void testConvertNodeTemplatesWhenConvertComponentInstanceRequirmentsIsRight() { + Component component = new Resource(); + List<ComponentInstance> componentInstances = new ArrayList<>(); + Map<String, List<ComponentInstanceProperty>> componentInstancesProperties = new HashMap<>(); + Map<String, Component> componentCache = new HashMap<>(); + Map<String, DataTypeDefinition> dataTypes = new HashMap<>(); + ToscaTopolgyTemplate topologyTemplate = new ToscaTopolgyTemplate(); + Either<Map<String, ToscaNodeTemplate>, ToscaError> result; + Map<String, List<ComponentInstanceInput>> componentInstancesInputs = new HashMap<>(); + List<ComponentInstanceInput> inputs = new ArrayList<>(); + inputs.add(new ComponentInstanceInput()); + componentInstancesInputs.put("key", inputs); + List<RequirementCapabilityRelDef> resourceInstancesRelations = new ArrayList<>(); + RequirementCapabilityRelDef reldef = new RequirementCapabilityRelDef(); + reldef.setFromNode("id"); + reldef.setToNode("node"); + List<CapabilityRequirementRelationship> relationships = new ArrayList<>(); + CapabilityRequirementRelationship relationship = new CapabilityRequirementRelationship(); + relationship.setRelation(new RelationshipInfo()); + relationships.add(relationship); + reldef.setRelationships(relationships); + resourceInstancesRelations.add(reldef); + component.setComponentInstancesRelations(resourceInstancesRelations); + + ComponentInstance instance = new ComponentInstance(); + instance.setUniqueId("id"); + componentInstances.add(instance); + + component.setComponentInstancesInputs(componentInstancesInputs); + component.setComponentInstances(componentInstances); + + Mockito.when(capabiltyRequirementConvertor.getOriginComponent(Mockito.any(Map.class), + Mockito.any(ComponentInstance.class))).thenReturn(Either.left(component)); + + // default test + result = Deencapsulation.invoke(testSubject, "convertNodeTemplates", component, componentInstances, + componentInstancesProperties, componentCache, dataTypes, topologyTemplate); + } + + @Test + public void testAddComponentInstanceInputs() throws Exception { + + Map<String, DataTypeDefinition> dataTypes = new HashMap<>(); + Map<String, List<ComponentInstanceInput>> componentInstancesInputs = new HashMap<>(); + ComponentInstance componentInstance = new ComponentInstance(); + String instanceUniqueId = "id"; + Map<String, Object> props = new HashMap<>(); + + List<ComponentInstanceInput> componentInstanceInputs = new ArrayList<>(); + componentInstanceInputs.add(new ComponentInstanceInput()); + + componentInstancesInputs.put(instanceUniqueId, componentInstanceInputs); + + // default test + Deencapsulation.invoke(testSubject, "addComponentInstanceInputs", dataTypes, componentInstancesInputs, + componentInstance, instanceUniqueId, props); + } + + @Test + public void testAddPropertiesOfComponentInstance() throws Exception { + Map<String, List<ComponentInstanceProperty>> componentInstancesProperties = new HashMap<>(); + Map<String, DataTypeDefinition> dataTypes = new HashMap<>(); + ComponentInstance componentInstance = new ComponentInstance(); + String instanceUniqueId = "id"; + Map<String, Object> props = new HashMap<>(); + + ComponentInstanceProperty cip = new ComponentInstanceProperty(); + cip.setInstanceUniqueId("id"); + + List<ComponentInstanceProperty> list = new ArrayList<>(); + list.add(cip); + + componentInstancesProperties.put("id", list); + + // default test + Deencapsulation.invoke(testSubject, "addPropertiesOfComponentInstance", componentInstancesProperties, dataTypes, + componentInstance, instanceUniqueId, props); + } + + @Test + public void testAddPropertiesOfParentComponent() throws Exception { + Map<String, DataTypeDefinition> dataTypes = new HashMap<>(); + ComponentInstance componentInstance = new ComponentInstance(); + Component componentOfInstance = new Resource(); + Map<String, Object> props = new HashMap<>(); + + List<PropertyDefinition> properties = new ArrayList<>(); + properties.add(new PropertyDefinition()); + + ((Resource) componentOfInstance).setProperties(properties); + + // default test + Deencapsulation.invoke(testSubject, "addPropertiesOfParentComponent", dataTypes, componentInstance, + componentOfInstance, props); + } + + @Test + public void testConvertAndAddValue() throws Exception { + Map<String, DataTypeDefinition> dataTypes = new HashMap<>(); + ComponentInstance componentInstance = new ComponentInstance(); + Map<String, Object> props = new HashMap<>(); + PropertyDefinition prop = new PropertyDefinition(); + Supplier<String> supplier = () -> ""; + + // default test + Deencapsulation.invoke(testSubject, "convertAndAddValue", dataTypes, componentInstance, props, prop, supplier); + } + + @Test + public void testConvertValue() throws Exception { + Map<String, DataTypeDefinition> dataTypes = new HashMap<>(); + ComponentInstance componentInstance = new ComponentInstance(); + Supplier<String> supplier = () -> ""; + PropertyDefinition input = new PropertyDefinition(); + SchemaDefinition schema = new SchemaDefinition(); + schema.setProperty(new PropertyDataDefinition()); + input.setSchema(schema); + Object result; + + // default test + result = Deencapsulation.invoke(testSubject, "convertValue", dataTypes, componentInstance, input, supplier); + + } + + @Test + public void testConvertGroupInstance() throws Exception { + + GroupInstance groupInstance = new GroupInstance(); + groupInstance.setType("type"); + ToscaGroupTemplate result; + + // default test + + result = Deencapsulation.invoke(testSubject, "convertGroupInstance", groupInstance); + } + + @Test + public void testFillGroupProperties() throws Exception { + List<GroupProperty> groupProps = new ArrayList<>(); + GroupProperty property = new GroupProperty(); + property.setName("isBase"); + groupProps.add(property); + Map<String, Object> result; + + // test when property name is 'isBase' + result = Deencapsulation.invoke(testSubject, "fillGroupProperties", groupProps); + + groupProps.get(0).setName("name"); + groupProps.get(0).setType("integer"); + groupProps.get(0).setValue("123"); + + // test when property name isn't 'isBase' and value type is integer + result = Deencapsulation.invoke(testSubject, "fillGroupProperties", groupProps); + + groupProps.get(0).setType("boolean"); + groupProps.get(0).setValue("false"); + + // test when property name isn't 'isBase' and value type is boolean + result = Deencapsulation.invoke(testSubject, "fillGroupProperties", groupProps); + + } + + @Test + public void testCreateNodeType() throws Exception { + + Component component = new Resource(); + List<String> array = new ArrayList<>(); + array.add("value"); + ((Resource) component).setDerivedFrom(array); + ToscaNodeType result; + + // test when component is resource + result = Deencapsulation.invoke(testSubject, "createNodeType", component); + + component = new Service(); + // test when component is service + result = Deencapsulation.invoke(testSubject, "createNodeType", component); + } + + @Test + public void testCreateProxyNodeTypes() throws Exception { + Map<String, Component> componentCache = new HashMap<>(); + Component container = new Resource(); + Either<Map<String, ToscaNodeType>, ToscaError> result; + List<ComponentInstance> componentInstances = new ArrayList<>(); + ComponentInstance instance = new ComponentInstance(); + instance.setOriginType(OriginTypeEnum.ServiceProxy); + instance.setSourceModelUid("targetModelUid"); + + componentInstances.add(instance); + container.setComponentInstances(componentInstances); + + Mockito.when(toscaOperationFacade.getLatestByName("serviceProxy")) + .thenReturn(Either.right(StorageOperationStatus.BAD_REQUEST)); + + // test when getLatestByName return is right + result = Deencapsulation.invoke(testSubject, "createProxyNodeTypes", componentCache, container); + + } + + @Test + public void testCreateProxyNodeTypesWhenGetLatestByNameReturnValue() { + Map<String, Component> componentCache = new HashMap<>(); + Component container = new Resource(); + Either<Map<String, ToscaNodeType>, ToscaError> result; + List<ComponentInstance> componentInstances = new ArrayList<>(); + ComponentInstance instance = new ComponentInstance(); + instance.setOriginType(OriginTypeEnum.ServiceProxy); + instance.setSourceModelUid("targetModelUid"); + + componentInstances.add(instance); + container.setComponentInstances(componentInstances); + + Mockito.when(toscaOperationFacade.getLatestByName("serviceProxy")).thenReturn(Either.left(new Resource())); + + ComponentParametersView parameterView = new ComponentParametersView(); + parameterView.disableAll(); + parameterView.setIgnoreCategories(false); + + Mockito.when(toscaOperationFacade.getToscaElement(Mockito.any(String.class), + Mockito.any(ComponentParametersView.class))) + .thenReturn(Either.right(StorageOperationStatus.BAD_REQUEST)); + + Mockito.when(dataTypeCache.getAll()).thenReturn(Either.left(new HashMap<>())); + + // test when getLatestByName is left + result = Deencapsulation.invoke(testSubject, "createProxyNodeTypes", componentCache, container); + } + + @Test + public void testCreateProxyNodeType() throws Exception { + Map<String, Component> componentCache = new HashMap<>(); + Component origComponent = new Resource(); + Component proxyComponent = new Resource(); + ComponentInstance instance = new ComponentInstance(); + ToscaNodeType result; + + Mockito.when(dataTypeCache.getAll()).thenReturn(Either.left(new HashMap<>())); + + // default test + result = Deencapsulation.invoke(testSubject, "createProxyNodeType", componentCache, origComponent, + proxyComponent, instance); + } + + @Test + public void testConvertComponentInstanceRequirements() throws Exception { + Component component = new Resource(); + ComponentInstance componentInstance = new ComponentInstance(); + List<RequirementCapabilityRelDef> relations = new ArrayList<>(); + ToscaNodeTemplate nodeTypeTemplate = new ToscaNodeTemplate(); + Component originComponent = new Resource(); + Map<String, Component> componentCache = new HashMap<>(); + Either<ToscaNodeTemplate, ToscaError> result; + + // default test + result = Deencapsulation.invoke(testSubject, "convertComponentInstanceRequirements", component, + componentInstance, relations, nodeTypeTemplate, originComponent, componentCache); + + RequirementCapabilityRelDef reldef = new RequirementCapabilityRelDef(); + reldef.setFromNode("name"); + reldef.setToNode("name1"); + List<CapabilityRequirementRelationship> relationships = new ArrayList<>(); + CapabilityRequirementRelationship cap = new CapabilityRequirementRelationship(); + cap.setRelation(new RelationshipInfo()); + relationships.add(cap); + reldef.setRelationships(relationships); + relations.add(reldef); + componentInstance.setUniqueId("name"); + + List<ComponentInstance> instances = new ArrayList<>(); + instances.add(componentInstance); + component.setComponentInstances(instances); + + // test when filteredRElations ins't empty + result = Deencapsulation.invoke(testSubject, "convertComponentInstanceRequirements", component, + componentInstance, relations, nodeTypeTemplate, originComponent, componentCache); + } + + @Test + public void testAddRequirement() throws Exception { + ComponentInstance fromInstance = new ComponentInstance(); + Component fromOriginComponent = new Resource(); + List<ComponentInstance> instancesList = new ArrayList<>(); + RequirementCapabilityRelDef rel = new RequirementCapabilityRelDef(); + List<Map<String, ToscaTemplateRequirement>> toscaRequirements = new ArrayList<>(); + Map<String, Component> componentCache = new HashMap<>(); + boolean result; + + List<CapabilityRequirementRelationship> relationships = new ArrayList<>(); + CapabilityRequirementRelationship cap = new CapabilityRequirementRelationship(); + cap.setRequirement(new RequirementDataDefinition()); + RelationshipInfo relation = new RelationshipInfo(); + relation.setRequirementUid("Uid"); + relation.setRequirement("requirment"); + relation.setCapability("cap"); + relation.setCapabilityOwnerId("id1"); + cap.setRelation(relation); + relationships.add(cap); + rel.setRelationships(relationships); + rel.setToNode("name"); + fromInstance.setUniqueId("name"); + fromInstance.setComponentUid("string"); + instancesList.add(fromInstance); + Map<String, List<RequirementDefinition>> requirements = new HashMap<>(); + fromOriginComponent.setRequirements(requirements); + + // default test + result = Deencapsulation.invoke(testSubject, "addRequirement", fromInstance, fromOriginComponent, instancesList, + rel, toscaRequirements, componentCache); + + } + + @Test + public void testAddRequirmentsWhenFindRequirmentsReturnsValue() { + + ComponentInstance fromInstance = new ComponentInstance(); + Component fromOriginComponent = new Resource(); + List<ComponentInstance> instancesList = new ArrayList<>(); + RequirementCapabilityRelDef rel = new RequirementCapabilityRelDef(); + List<Map<String, ToscaTemplateRequirement>> toscaRequirements = new ArrayList<>(); + Map<String, Component> componentCache = new HashMap<>(); + boolean result; + + List<CapabilityRequirementRelationship> relationships = new ArrayList<>(); + CapabilityRequirementRelationship cap = new CapabilityRequirementRelationship(); + cap.setRequirement(new RequirementDataDefinition()); + RelationshipInfo relation = new RelationshipInfo(); + relation.setRequirementUid("Uid"); + relation.setRequirement("requirment"); + relation.setCapability("cap"); + relation.setCapabilityOwnerId("id1"); + cap.setRelation(relation); + relationships.add(cap); + rel.setRelationships(relationships); + rel.setToNode("name"); + fromInstance.setUniqueId("name"); + fromInstance.setComponentUid("string"); + instancesList.add(fromInstance); + Map<String, List<RequirementDefinition>> requirements = new HashMap<>(); + + List<RequirementDefinition> defs = new ArrayList<>(); + RequirementDefinition def = new RequirementDefinition(); + def.setName("requirment"); + def.setCapability("cap"); + defs.add(def); + requirements.put("key", defs); + fromOriginComponent.setRequirements(requirements); + + Mockito.when(toscaOperationFacade.getToscaElement(Mockito.any(String.class), + Mockito.any(ComponentParametersView.class))) + .thenReturn(Either.right(StorageOperationStatus.BAD_REQUEST)); + + // default test + result = Deencapsulation.invoke(testSubject, "addRequirement", fromInstance, fromOriginComponent, instancesList, + rel, toscaRequirements, componentCache); + } + + @Test + public void testAddRequirmentsWhenCapabilityBelongsToRelation() { + ComponentInstance fromInstance = new ComponentInstance(); + Component fromOriginComponent = new Resource(); + List<ComponentInstance> instancesList = new ArrayList<>(); + RequirementCapabilityRelDef rel = new RequirementCapabilityRelDef(); + List<Map<String, ToscaTemplateRequirement>> toscaRequirements = new ArrayList<>(); + Map<String, Component> componentCache = new HashMap<>(); + boolean result; + + List<CapabilityRequirementRelationship> relationships = new ArrayList<>(); + CapabilityRequirementRelationship cap = new CapabilityRequirementRelationship(); + cap.setRequirement(new RequirementDataDefinition()); + RelationshipInfo relation = new RelationshipInfo(); + relation.setRequirementUid("Uid"); + relation.setRequirement("requirment"); + relation.setCapability("cap"); + relation.setCapabilityOwnerId("id1"); + cap.setRelation(relation); + relationships.add(cap); + rel.setRelationships(relationships); + rel.setToNode("name"); + fromInstance.setUniqueId("name"); + fromInstance.setComponentUid("string"); + instancesList.add(fromInstance); + Map<String, List<RequirementDefinition>> requirements = new HashMap<>(); + + List<RequirementDefinition> defs = new ArrayList<>(); + RequirementDefinition def = new RequirementDefinition(); + def.setName("requirment"); + def.setCapability("cap"); + defs.add(def); + requirements.put("key", defs); + fromOriginComponent.setRequirements(requirements); + + Map<String, List<CapabilityDefinition>> capabilities = new HashMap<>(); + List<CapabilityDefinition> caps = new ArrayList<>(); + CapabilityDefinition capdef = new CapabilityDefinition(); + capdef.setOwnerId("id"); + capdef.setName("name"); + capdef.setType("type"); + caps.add(capdef); + capabilities.put("cap", caps); + + fromOriginComponent.setCapabilities(capabilities); + + Mockito.when(toscaOperationFacade.getToscaElement(Mockito.any(String.class), + Mockito.any(ComponentParametersView.class))).thenReturn(Either.left(fromOriginComponent)); + + // default test + result = Deencapsulation.invoke(testSubject, "addRequirement", fromInstance, fromOriginComponent, instancesList, + rel, toscaRequirements, componentCache); + } + + @Test + public void testAddRequirmentsWithBuildAndAddRequirements() { + ComponentInstance fromInstance = new ComponentInstance(); + Component fromOriginComponent = new Resource(); + List<ComponentInstance> instancesList = new ArrayList<>(); + RequirementCapabilityRelDef rel = new RequirementCapabilityRelDef(); + List<Map<String, ToscaTemplateRequirement>> toscaRequirements = new ArrayList<>(); + Map<String, Component> componentCache = new HashMap<>(); + boolean result; + + List<CapabilityRequirementRelationship> relationships = new ArrayList<>(); + CapabilityRequirementRelationship cap = new CapabilityRequirementRelationship(); + cap.setRequirement(new RequirementDataDefinition()); + RelationshipInfo relation = new RelationshipInfo(); + relation.setRequirementUid("Uid"); + relation.setRequirement("requirment"); + relation.setCapability("cap"); + relation.setCapabilityOwnerId("id"); + cap.setRelation(relation); + relationships.add(cap); + rel.setRelationships(relationships); + rel.setToNode("name"); + fromInstance.setUniqueId("name"); + fromInstance.setComponentUid("string"); + instancesList.add(fromInstance); + Map<String, List<RequirementDefinition>> requirements = new HashMap<>(); + + List<RequirementDefinition> defs = new ArrayList<>(); + RequirementDefinition def = new RequirementDefinition(); + def.setName("requirment"); + def.setCapability("cap"); + defs.add(def); + requirements.put("key", defs); + fromOriginComponent.setRequirements(requirements); + + Map<String, List<CapabilityDefinition>> capabilities = new HashMap<>(); + List<CapabilityDefinition> caps = new ArrayList<>(); + CapabilityDefinition capdef = new CapabilityDefinition(); + capdef.setOwnerId("id"); + capdef.setName("cap"); + capdef.setType("type"); + caps.add(capdef); + capabilities.put("cap", caps); + fromOriginComponent.setCapabilities(capabilities); + + Mockito.when(toscaOperationFacade.getToscaElement(Mockito.any(String.class), + Mockito.any(ComponentParametersView.class))).thenReturn(Either.left(fromOriginComponent)); + + Mockito.when(capabiltyRequirementConvertor.buildSubstitutedName(Mockito.any(Map.class), + Mockito.any(Component.class), Mockito.any(List.class), Mockito.anyString())) + .thenReturn(Either.right(false)); + + // default test + result = Deencapsulation.invoke(testSubject, "addRequirement", fromInstance, fromOriginComponent, instancesList, + rel, toscaRequirements, componentCache); + } + + @Test + public void testBuildAndAddRequirement() throws Exception { + List<Map<String, ToscaTemplateRequirement>> toscaRequirements = new ArrayList<>(); + Component fromOriginComponent = new Resource(); + Component toOriginComponent = new Resource(); + CapabilityDefinition capability = new CapabilityDefinition(); + RequirementDefinition requirement = new RequirementDefinition(); + RelationshipInfo reqAndRelationshipPair = new RelationshipInfo(); + ComponentInstance toInstance = new ComponentInstance(); + Map<String, Component> componentCache = new HashMap<>(); + boolean result; + capability.setPath(new ArrayList<>()); + reqAndRelationshipPair.setCapability("cap"); + requirement.setPath(new ArrayList<>()); + reqAndRelationshipPair.setRequirement("req"); + + Mockito.when(capabiltyRequirementConvertor.buildSubstitutedName(new HashMap<>(), toOriginComponent, + new ArrayList<>(), "cap")).thenReturn(Either.left("buildCapNameRes")); + + Mockito.when(capabiltyRequirementConvertor.buildSubstitutedName(new HashMap<>(), fromOriginComponent, + new ArrayList<>(), "req")).thenReturn(Either.right(false)); + + // default test + result = Deencapsulation.invoke(testSubject, "buildAndAddRequirement", toscaRequirements, fromOriginComponent, + toOriginComponent, capability, requirement, reqAndRelationshipPair, toInstance, componentCache); + } + + @Test + public void testBuildAndAddRequirementBuildSubtitutedNameReturnsValueTwice() { + List<Map<String, ToscaTemplateRequirement>> toscaRequirements = new ArrayList<>(); + Component fromOriginComponent = new Resource(); + Component toOriginComponent = new Resource(); + CapabilityDefinition capability = new CapabilityDefinition(); + RequirementDefinition requirement = new RequirementDefinition(); + RelationshipInfo reqAndRelationshipPair = new RelationshipInfo(); + ComponentInstance toInstance = new ComponentInstance(); + Map<String, Component> componentCache = new HashMap<>(); + boolean result; + capability.setPath(new ArrayList<>()); + reqAndRelationshipPair.setCapability("cap"); + requirement.setPath(new ArrayList<>()); + reqAndRelationshipPair.setRequirement("req"); + + Mockito.when(capabiltyRequirementConvertor.buildSubstitutedName(Mockito.anyMap(), Mockito.any(Resource.class), + Mockito.anyList(), Mockito.anyString())).thenReturn(Either.left("buildCapNameRes")); + + // default test + result = Deencapsulation.invoke(testSubject, "buildAndAddRequirement", toscaRequirements, fromOriginComponent, + toOriginComponent, capability, requirement, reqAndRelationshipPair, toInstance, componentCache); + } + + @Test + public void testIsRequirementBelongToRelation() throws Exception { + + Component originComponent = new Resource(); + RelationshipInfo reqAndRelationshipPair = new RelationshipInfo(); + RequirementDefinition requirement = new RequirementDefinition(); + String fromInstanceId = ""; + boolean result; + + requirement.setName("name"); + reqAndRelationshipPair.setRequirement("name1"); + + // test return false + result = Deencapsulation.invoke(testSubject, "isRequirementBelongToRelation", originComponent, + reqAndRelationshipPair, requirement, fromInstanceId); + } + + @Test + public void testIsRequirementBelongToRelationWithNonAtomicComponent() { + + Component originComponent = new Service(); + RelationshipInfo reqAndRelationshipPair = new RelationshipInfo(); + RequirementDefinition requirement = new RequirementDefinition(); + String fromInstanceId = ""; + boolean result; + + // default test return true + result = Deencapsulation.invoke(testSubject, "isRequirementBelongToRelation", originComponent, + reqAndRelationshipPair, requirement, fromInstanceId); + } + + @Test + public void testIsRequirementBelongToOwner() throws Exception { + + RelationshipInfo reqAndRelationshipPair = new RelationshipInfo(); + RequirementDefinition requirement = new RequirementDefinition(); + String fromInstanceId = ""; + Component originComponent = new Resource(); + boolean result; + + requirement.setOwnerId("owner1"); + reqAndRelationshipPair.setRequirementOwnerId("owner"); + + // default test + result = Deencapsulation.invoke(testSubject, "isRequirementBelongToOwner", reqAndRelationshipPair, requirement, + fromInstanceId, originComponent); + } + + @Test + public void testIsCvfc() throws Exception { + + Component component = new Resource(); + boolean result; + + component = new Service(); + + result = Deencapsulation.invoke(testSubject, "isCvfc", component); + } + + @Test + public void testConvertCapabilities() throws Exception { + Component component = new Resource(); + SubstitutionMapping substitutionMappings = new SubstitutionMapping(); + Map<String, Component> componentCache = new HashMap<>(); + Either<SubstitutionMapping, ToscaError> result; + + Mockito.when(capabiltyRequirementConvertor.convertSubstitutionMappingCapabilities(componentCache, component)) + .thenReturn(Either.right(ToscaError.NODE_TYPE_CAPABILITY_ERROR)); + + // default test return isRight + result = Deencapsulation.invoke(testSubject, "convertCapabilities", component, substitutionMappings, + componentCache); + } + + @Test + public void testConvertCapabilities_1() throws Exception { + Component component = new Resource(); + ToscaNodeType nodeType = new ToscaNodeType(); + Map<String, DataTypeDefinition> dataTypes = new HashMap<>(); + Either<ToscaNodeType, ToscaError> result; + + Map<String, ToscaCapability> capabilities = new HashMap<>(); + capabilities.put("key", new ToscaCapability()); + + Mockito.when(capabiltyRequirementConvertor.convertCapabilities(component, dataTypes)).thenReturn(capabilities); + + // default test + result = Deencapsulation.invoke(testSubject, "convertCapabilities", component, nodeType, dataTypes); + } +}
\ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/ToscaExportUtilsTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/ToscaExportUtilsTest.java deleted file mode 100644 index 041973a0b4..0000000000 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/ToscaExportUtilsTest.java +++ /dev/null @@ -1,121 +0,0 @@ -package org.openecomp.sdc.be.tosca; - -import org.junit.Test; -import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; -import org.openecomp.sdc.be.model.operations.impl.ComponentInstanceOperation; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -public class ToscaExportUtilsTest { - private static final Logger log = LoggerFactory.getLogger(ToscaExportUtilsTest.class); - @javax.annotation.Resource - private ComponentInstanceBusinessLogic componentInstanceBusinessLogic; - @Autowired - private ToscaExportHandler exportUtils; - @Autowired - private ComponentInstanceOperation componentInstanceOperation; - - Gson gson = new GsonBuilder().setPrettyPrinting().create(); - - @Test - public void testExportService() { - /* Resource resource1 = ResourceTestUtils.prepareResource(0); - resource1.setResourceType(ResourceTypeEnum.VF); - Either<Resource, ResponseFormat> createResource1 = resourceBusinessLogic.createResource(resource1, getAdminUser(), null, null); - assertTrue(createResource1.isLeft()); - Resource certifiedVFC1 = changeResourceStateToCertify(createResource1.left().value()); - - Resource resource2 = ResourceTestUtils.prepareResource(1); - resource2.setResourceType(ResourceTypeEnum.VF); - Either<Resource, ResponseFormat> createResource2 = resourceBusinessLogic.createResource(resource2, getAdminUser(), null, null); - assertTrue(createResource2.isLeft()); - Resource certifiedVFC2 = changeResourceStateToCertify(createResource2.left().value()); - - Service service = ResourceTestUtils.prepareService(0); - Either<Service, ResponseFormat> createService = serviceBusinessLogic.createService(service, getAdminUser()); - assertTrue(createService.isLeft()); - - // add VFC instance to VF - ComponentInstance vfcResourceInstance1 = new ComponentInstance(); - vfcResourceInstance1.setDescription("VFC instance 1"); - vfcResourceInstance1.setName(certifiedVFC1.getName()); - vfcResourceInstance1.setComponentUid(certifiedVFC1.getUniqueId()); - - Either<ComponentInstance, ResponseFormat> createResourceVfcInstance1 = serviceInstanceBusinessLogic.createComponentInstance(ComponentTypeEnum.SERVICE_PARAM_NAME, createService.left().value().getUniqueId(), adminUser.getAttuid(), - vfcResourceInstance1); - assertTrue(createResourceVfcInstance1.isLeft()); - - ComponentInstance vfcResourceInstance2 = new ComponentInstance(); - vfcResourceInstance2.setDescription("VFC instance 2"); - vfcResourceInstance2.setName(certifiedVFC2.getName()); - vfcResourceInstance2.setComponentUid(certifiedVFC2.getUniqueId()); - Either<ComponentInstance, ResponseFormat> createResourceVfcInstance2 = serviceInstanceBusinessLogic.createComponentInstance(ComponentTypeEnum.SERVICE_PARAM_NAME, createService.left().value().getUniqueId(), adminUser.getAttuid(), - vfcResourceInstance2); - assertTrue(createResourceVfcInstance2.isLeft()); - - Either<Service, ResponseFormat> serviceFetch = serviceBusinessLogic.getService(createService.left().value().getUniqueId(), adminUser); - assertTrue(serviceFetch.isLeft()); - - List<ComponentInstance> componentInstances = serviceFetch.left().value().getComponentInstances(); - String ciname1 = null; - String ciname2 = null; - - for (ComponentInstance ci : componentInstances) { - if (ci.getComponentUid().equals(certifiedVFC1.getUniqueId())) { - ciname1 = ci.getName(); - } - if (ci.getComponentUid().equals(certifiedVFC2.getUniqueId())) { - ciname2 = ci.getName(); - } - } - - Either<ToscaRepresentation, ToscaError> result = exportUtils.exportComponent(serviceFetch.left().value()); - assertTrue(result.isLeft()); - - String mainYaml = result.left().value().getMainYaml(); - assertNotNull(mainYaml); - - YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter(); - assertTrue(yamlToObjectConverter.isValidYaml(mainYaml.getBytes())); - log.debug(mainYaml); - - Yaml yaml = new Yaml(); - - InputStream inputStream = new ByteArrayInputStream(mainYaml.getBytes()); - Map<String, Object> load = (Map<String, Object>) yaml.load(inputStream); - Map<String, Object> imports = (Map<String, Object>) load.get("imports"); - assertNotNull(imports); - assertEquals("Validate imports size in yml", 2, imports.size()); - - Map<String, Object> metadata = (Map<String, Object>) load.get("metadata"); - assertNotNull(metadata); - validateMetadata(metadata, serviceFetch.left().value(), false); - - Map<String, Object> vf1 = (Map<String, Object>) imports.get(certifiedVFC1.getName()); - String fileName = (String) vf1.get(ToscaExportHandler.IMPORTS_FILE_KEY); - ArtifactDefinition artifactDefinition = certifiedVFC1.getToscaArtifacts().get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); - assertEquals("Validate 1 file name", artifactDefinition.getArtifactName(), fileName); - - Map<String, Object> topology_template = (Map<String, Object>) load.get("topology_template"); - Map<String, Object> node_templates = (Map<String, Object>) topology_template.get("node_templates"); - Map<String, Object> inst1 = (Map<String, Object>) node_templates.get(ciname1); - Map<String, Object> inst2 = (Map<String, Object>) node_templates.get(ciname2); - - Map<String, Object> inst1MD = (Map<String, Object>) inst1.get("metadata"); - Map<String, Object> inst2MD = (Map<String, Object>) inst2.get("metadata"); - - validateMetadata(inst1MD, certifiedVFC1, true); - - Map<String, Object> vf2 = (Map<String, Object>) imports.get(certifiedVFC2.getName()); - fileName = (String) vf2.get(ToscaExportHandler.IMPORTS_FILE_KEY); - artifactDefinition = certifiedVFC2.getToscaArtifacts().get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); - assertEquals("Validate 2 file name", artifactDefinition.getArtifactName(), fileName); - - validateMetadata(inst2MD, certifiedVFC2, true);*/ - } - -} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/ToscaRepresentationTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/ToscaRepresentationTest.java index f7c6f72932..fad85b2fd8 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/ToscaRepresentationTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/ToscaRepresentationTest.java @@ -50,10 +50,10 @@ public class ToscaRepresentationTest { @Test public void testSetDependencies() throws Exception { ToscaRepresentation testSubject; - List<Triple<String, String, Component>> dependancies = null; + List<Triple<String, String, Component>> dependencies = null; // default test testSubject = createTestSubject(); - testSubject.setDependencies(dependancies); + testSubject.setDependencies(dependencies); } }
\ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/ToscaUtilsTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/ToscaUtilsTest.java index a9c87f7f61..0c7d5cf5ce 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/ToscaUtilsTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/ToscaUtilsTest.java @@ -1,54 +1,32 @@ package org.openecomp.sdc.be.tosca; -import java.util.List; import java.util.Map; import org.junit.Test; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.model.Component; - -import com.datastax.driver.core.UserType.Field; +import org.openecomp.sdc.be.model.Resource; public class ToscaUtilsTest { - - private ToscaUtils createTestSubject() { - return new ToscaUtils(); - } - - - @Test - public void testIsAtomicType() throws Exception { - Component component = null; - boolean result; - - // default test - } - @Test public void testIsComplexVfc() throws Exception { - Component component = null; + Component component = new Resource(); + component.setComponentType(ComponentTypeEnum.RESOURCE); boolean result; // default test + ToscaUtils.isComplexVfc(component); } @Test public void testObjectToMap() throws Exception { Object objectToConvert = null; - Class clazz = null; + Object obj = new Object(); Map<String, Object> result; // default test - } - - - @Test - public void testGetAllFields() throws Exception { - List<Field> fields = null; - Class<?> type = null; - List<Field> result; - - // default test + ToscaUtils.objectToMap(objectToConvert, obj.getClass()); } }
\ No newline at end of file diff --git a/common-app-api/src/main/java/org/openecomp/sdc/be/config/Configuration.java b/common-app-api/src/main/java/org/openecomp/sdc/be/config/Configuration.java index 14b02b4ff9..c4f221c875 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/be/config/Configuration.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/be/config/Configuration.java @@ -1336,7 +1336,9 @@ public class Configuration extends BasicConfiguration { .append(format("Service Api Artifacts: %s%n", serviceApiArtifacts)) .append(format("heat env artifact header: %s%n", heatEnvArtifactHeader)) .append(format("heat env artifact footer: %s%n", heatEnvArtifactFooter)) - .append(format("onboarding: %s%n", onboarding)).toString(); + .append(format("onboarding: %s%n", onboarding)) + .append(format("tosca conformance level: %s%n", toscaConformanceLevel)) + .toString(); } public List<String> getUnLoggedUrls() { diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/test/BaseConfDependent.java b/common-app-api/src/main/java/org/openecomp/sdc/common/test/BaseConfDependent.java index 2e31eebd23..df639c70e3 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/test/BaseConfDependent.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/test/BaseConfDependent.java @@ -37,6 +37,7 @@ public class BaseConfDependent { ExternalConfiguration.setAppName(componentName); ExternalConfiguration.setConfigDir(confPath); ExternalConfiguration.listenForChanges(); + ExternalConfiguration.setAppVersion("1806.666"); ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), ExternalConfiguration.getConfigDir() + File.separator + ExternalConfiguration.getAppName()); |