2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.openecomp.sdc.be.tosca;
23 import java.io.BufferedOutputStream;
24 import java.io.ByteArrayInputStream;
25 import java.io.IOException;
26 import java.util.ArrayList;
27 import java.util.Arrays;
28 import java.util.EnumMap;
29 import java.util.HashMap;
30 import java.util.HashSet;
31 import java.util.LinkedList;
32 import java.util.List;
34 import java.util.Map.Entry;
36 import java.util.regex.Matcher;
37 import java.util.regex.Pattern;
38 import java.util.stream.Collectors;
39 import java.util.zip.ZipEntry;
40 import java.util.zip.ZipInputStream;
41 import java.util.zip.ZipOutputStream;
43 import org.apache.commons.codec.binary.Base64;
44 import org.apache.commons.codec.digest.DigestUtils;
45 import org.apache.commons.io.output.ByteArrayOutputStream;
46 import org.apache.commons.lang.WordUtils;
47 import org.apache.commons.lang3.tuple.ImmutablePair;
48 import org.apache.commons.lang3.tuple.ImmutableTriple;
49 import org.apache.commons.lang3.tuple.Triple;
50 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
51 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum;
52 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationInfo;
53 import org.openecomp.sdc.be.components.impl.ImportUtils;
54 import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
55 import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig;
56 import org.openecomp.sdc.be.config.ConfigurationManager;
57 import org.openecomp.sdc.be.dao.api.ActionStatus;
58 import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao;
59 import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
60 import org.openecomp.sdc.be.dao.cassandra.SdcSchemaFilesCassandraDao;
61 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
62 import org.openecomp.sdc.be.impl.ComponentsUtils;
63 import org.openecomp.sdc.be.model.ArtifactDefinition;
64 import org.openecomp.sdc.be.model.Component;
65 import org.openecomp.sdc.be.model.ComponentInstance;
66 import org.openecomp.sdc.be.model.LifecycleStateEnum;
67 import org.openecomp.sdc.be.model.Operation;
68 import org.openecomp.sdc.be.model.Resource;
69 import org.openecomp.sdc.be.model.Service;
70 import org.openecomp.sdc.be.model.User;
71 import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOperation;
72 import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
73 import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
74 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
75 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
76 import org.openecomp.sdc.be.resources.data.ESArtifactData;
77 import org.openecomp.sdc.be.resources.data.SdcSchemaFilesData;
78 import org.openecomp.sdc.be.tosca.model.ToscaTemplate;
79 import org.openecomp.sdc.be.utils.CommonBeUtils;
80 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
81 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
82 import org.openecomp.sdc.common.impl.ExternalConfiguration;
83 import org.openecomp.sdc.common.util.GeneralUtility;
84 import org.openecomp.sdc.common.util.ValidationUtils;
85 import org.openecomp.sdc.exception.ResponseFormat;
86 import org.openecomp.sdc.generator.data.AdditionalParams;
87 import org.openecomp.sdc.generator.data.Artifact;
88 import org.openecomp.sdc.generator.data.ArtifactType;
89 import org.openecomp.sdc.generator.data.GenerationData;
90 import org.openecomp.sdc.generator.impl.ArtifactGenerationServiceImpl;
91 import org.slf4j.Logger;
92 import org.slf4j.LoggerFactory;
93 import org.springframework.beans.factory.annotation.Autowired;
95 import com.google.gson.Gson;
97 import fj.data.Either;
104 @org.springframework.stereotype.Component("csar-utils")
105 public class CsarUtils {
106 private static final Logger log = LoggerFactory.getLogger(CsarUtils.class);
109 private SdcSchemaFilesCassandraDao sdcSchemaFilesCassandraDao;
111 private ArtifactCassandraDao artifactCassandraDao;
113 private ComponentsUtils componentsUtils;
115 private ToscaExportHandler toscaExportUtils;
117 private ArtifactsBusinessLogic artifactsBusinessLogic;
119 protected ToscaOperationFacade toscaOperationFacade;
122 @javax.annotation.Resource
123 private ServiceBusinessLogic serviceBusinessLogic;
125 private Gson gson = new Gson();
127 public static final String CONFORMANCE_LEVEL = ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel();
128 public static final String SDC_VERSION = ExternalConfiguration.getAppVersion();
130 public static final Pattern UUID_NORMATIVE_NEW_VERSION = Pattern.compile("^\\d{1,}.0");
131 public static final String ARTIFACTS_PATH = "Artifacts/";
132 public static final String RESOURCES_PATH = "Resources/";
133 public static final String INFORMATIONAL_ARTIFACTS = "Informational/";
134 public static final String DEPLOYMENT_ARTIFACTS = "Deployment/";
136 public static final String DEFINITIONS_PATH = "Definitions/";
137 private static final String CSAR_META_VERSION = "1.0";
138 private static final String CSAR_META_PATH_FILE_NAME = "csar.meta";
139 private static final String TOSCA_META_PATH_FILE_NAME = "TOSCA-Metadata/TOSCA.meta";
140 private static final String TOSCA_META_VERSION = "1.0";
141 private static final String CSAR_VERSION = "1.1";
142 public static final String ARTIFACTS = "Artifacts";
143 public static final String DEFINITION = "Definitions";
144 public static final String DEL_PATTERN = "([/\\\\]+)";
145 private static String versionFirstThreeOctates;
147 public static final String VFC_NODE_TYPE_ARTIFACTS_PATH_PATTERN = ARTIFACTS + DEL_PATTERN +
148 ImportUtils.Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX +
149 "([\\d\\w\\_\\-\\.\\s]+)" + DEL_PATTERN +
150 "([\\d\\w\\_\\-\\.\\s]+)" + DEL_PATTERN +
151 "([\\d\\w\\_\\-\\.\\s]+)" + DEL_PATTERN +
152 "([\\d\\w\\_\\-\\.\\s]+)";
154 public static final String VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN = ARTIFACTS + DEL_PATTERN+
155 // Artifact Group (i.e Deployment/Informational)
156 "([\\w\\_\\-\\.\\s]+)" + DEL_PATTERN +
158 "([\\w\\_\\-\\.\\s]+)" + DEL_PATTERN +
159 // Artifact Any File Name
161 public static final String VALID_ENGLISH_ARTIFACT_NAME = "([\\w\\_\\-\\.\\s]+)";
162 public static final String SERVICE_TEMPLATE_PATH_PATTERN = DEFINITION + DEL_PATTERN+
163 // Service Template File Name
164 "([\\w\\_\\-\\.\\s]+)";
166 public static final String ARTIFACT_CREATED_FROM_CSAR = "Artifact created from csar";
169 if(SDC_VERSION != null && !SDC_VERSION.isEmpty()){
170 Matcher matcher = Pattern.compile("(?!\\.)(\\d+(\\.\\d+)+)(?![\\d\\.])").matcher(SDC_VERSION);
172 versionFirstThreeOctates = matcher.group(0);
174 versionFirstThreeOctates = "";
182 * @param isInCertificationRequest
185 public Either<byte[], ResponseFormat> createCsar(Component component, boolean getFromCS, boolean isInCertificationRequest) {
186 return createCsar(component, getFromCS, isInCertificationRequest, false);
189 private Either<byte[], ResponseFormat> createCsar(Component component, boolean getFromCS, boolean isInCertificationRequest, boolean mockGenerator) {
190 final String createdBy = component.getCreatorFullName();
193 Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
194 ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
195 fileName = artifactDefinition.getArtifactName();
197 String toscaConformanceLevel = ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel();
198 String csarBlock0 = createCsarBlock0(CSAR_META_VERSION, toscaConformanceLevel);
199 byte[] csarBlock0Byte = csarBlock0.getBytes();
201 final String toscaBlock0 = createToscaBlock0(TOSCA_META_VERSION, CSAR_VERSION, createdBy, fileName);
202 byte[] toscaBlock0Byte = toscaBlock0.getBytes();
204 Either<byte[], ResponseFormat> generateCsarZipResponse = generateCsarZip(csarBlock0Byte, toscaBlock0Byte, component, getFromCS, isInCertificationRequest, mockGenerator);
206 if (generateCsarZipResponse.isRight()) {
207 return Either.right(generateCsarZipResponse.right().value());
210 return Either.left(generateCsarZipResponse.left().value());
213 private Either<byte[], ResponseFormat> generateCsarZip(byte[] csarBlock0Byte, byte[] toscaBlock0Byte, Component component, boolean getFromCS, boolean isInCertificationRequest, boolean mockGenerator) {
215 ByteArrayOutputStream out = new ByteArrayOutputStream();
216 ZipOutputStream zip = new ZipOutputStream(out);
218 zip.putNextEntry(new ZipEntry(CSAR_META_PATH_FILE_NAME));
219 zip.write(csarBlock0Byte);
220 zip.putNextEntry(new ZipEntry(TOSCA_META_PATH_FILE_NAME));
221 zip.write(toscaBlock0Byte);
222 Either<ZipOutputStream, ResponseFormat> populateZip = populateZip(component, getFromCS, zip, isInCertificationRequest, mockGenerator);
223 if (populateZip.isRight()) {
224 log.debug("Failed to populate CSAR zip file {}", populateZip.right().value());
225 return Either.right(populateZip.right().value());
229 byte[] byteArray = out.toByteArray();
231 return Either.left(byteArray);
232 } catch (IOException e) {
233 log.debug("Failed with IOexception to create CSAR zip for component {}", component.getUniqueId(), e);
235 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
236 return Either.right(responseFormat);
240 private Either<ZipOutputStream, ResponseFormat> populateZip(Component component, boolean getFromCS, ZipOutputStream zip, boolean isInCertificationRequest, boolean mockGenerator) throws IOException {
242 LifecycleStateEnum lifecycleState = component.getLifecycleState();
243 String componentYaml;
244 Either<ToscaRepresentation, ToscaError> exportComponent;
246 // <file name, cassandraId, component>
247 List<Triple<String, String, Component>> dependencies = null;
248 List<ImmutablePair<Component, byte[]>> generatorInputs = new LinkedList<>();
250 Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
251 ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
252 String fileName = artifactDefinition.getArtifactName();
254 if (getFromCS || !(lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) {
255 String cassandraId = artifactDefinition.getEsId();
256 Either<byte[], ActionStatus> fromCassandra = getFromCassandra(cassandraId);
257 if (fromCassandra.isRight()) {
258 log.debug("ArtifactName {}, unique ID {}", artifactDefinition.getArtifactName(), artifactDefinition.getUniqueId());
259 ResponseFormat responseFormat = componentsUtils.getResponseFormat(fromCassandra.right().value());
260 return Either.right(responseFormat);
262 mainYaml = fromCassandra.left().value();
265 exportComponent = toscaExportUtils.exportComponent(component);
266 if (exportComponent.isRight()) {
267 log.debug("exportComponent failed", exportComponent.right().value());
268 ActionStatus convertedFromToscaError = componentsUtils.convertFromToscaError(exportComponent.right().value());
269 ResponseFormat responseFormat = componentsUtils.getResponseFormat(convertedFromToscaError);
270 return Either.right(responseFormat);
272 ToscaRepresentation exportResult = exportComponent.left().value();
273 componentYaml = exportResult.getMainYaml();
274 mainYaml = componentYaml.getBytes();
275 dependencies = exportResult.getDependencies();
278 zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + fileName));
280 //US798487 - Abstraction of complex types
281 if (!ModelConverter.isAtomicComponent(component)){
282 log.debug("Component {} is complex - generating abstract type for it..", component.getName());
283 writeComponentInterface(component, zip, fileName);
286 generatorInputs.add(new ImmutablePair<Component, byte[]>(component, mainYaml));
288 if (dependencies == null) {
289 Either<ToscaTemplate, ToscaError> dependenciesRes = toscaExportUtils.getDependencies(component);
290 if (dependenciesRes.isRight()) {
291 log.debug("Failed to retrieve dependencies for component {}, error {}", component.getUniqueId(),
292 dependenciesRes.right().value());
293 ActionStatus convertFromToscaError = componentsUtils.convertFromToscaError(dependenciesRes.right().value());
294 ResponseFormat responseFormat = componentsUtils.getResponseFormat(convertFromToscaError);
295 return Either.right(responseFormat);
297 dependencies = dependenciesRes.left().value().getDependencies();
300 //UID <cassandraId,filename,component>
301 Map<String, ImmutableTriple<String,String, Component>> innerComponentsCache = new HashMap<>();
303 if (dependencies != null && !dependencies.isEmpty()) {
304 for (Triple<String, String, Component> d : dependencies) {
305 String cassandraId = d.getMiddle();
306 Component childComponent = d.getRight();
307 Either<byte[], ActionStatus> entryData = getEntryData(cassandraId, childComponent);
309 if (entryData.isRight()) {
310 ResponseFormat responseFormat = componentsUtils.getResponseFormat(entryData.right().value());
311 return Either.right(responseFormat);
314 //fill innerComponentsCache
315 fileName = d.getLeft();
316 addComponentToCache(innerComponentsCache, cassandraId, fileName, childComponent);
317 addInnerComponentsToCache(innerComponentsCache, childComponent);
319 byte[] content = entryData.left().value();
320 generatorInputs.add(new ImmutablePair<Component, byte[]>(childComponent, content));
323 //add inner components to CSAR
324 for (Entry<String, ImmutableTriple<String, String, Component>> innerComponentTripleEntry : innerComponentsCache.entrySet()) {
326 ImmutableTriple<String, String, Component> innerComponentTriple = innerComponentTripleEntry.getValue();
328 Component innerComponent = innerComponentTriple.getRight();
329 String icFileName = innerComponentTriple.getMiddle();
331 // add component to zip
332 Either<byte[], ActionStatus> entryData = getEntryData(innerComponentTriple.getLeft(), innerComponent);
333 if (entryData.isRight()) {
334 ResponseFormat responseFormat = componentsUtils.getResponseFormat(entryData.right().value());
335 log.debug("Failed adding to zip component {}, error {}", innerComponentTriple.getLeft(),
336 entryData.right().value());
337 return Either.right(responseFormat);
339 byte[] content = entryData.left().value();
340 zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + icFileName));
343 // add component interface to zip
344 if (!ModelConverter.isAtomicComponent(innerComponent)) {
345 writeComponentInterface(innerComponent, zip, icFileName);
350 //retrieve SDC.zip from Cassandra
351 Either<byte[], ResponseFormat> latestSchemaFilesFromCassandra = getLatestSchemaFilesFromCassandra();
353 if(latestSchemaFilesFromCassandra.isRight()){
354 log.error("Error retrieving SDC Schema files from cassandra" );
355 return Either.right(latestSchemaFilesFromCassandra.right().value());
358 //add files from retireved SDC.zip to Definitions folder in CSAR
359 Either<ZipOutputStream, ResponseFormat> addSchemaFilesFromCassandra = addSchemaFilesFromCassandra(zip, latestSchemaFilesFromCassandra.left().value());
361 if(addSchemaFilesFromCassandra.isRight()){
362 return addSchemaFilesFromCassandra;
365 // Artifact Generation
366 if (component.getComponentType() == ComponentTypeEnum.SERVICE
367 && isInCertificationRequest) {
369 List<ArtifactDefinition> aiiArtifactList;
371 Either<List<ArtifactDefinition>, ResponseFormat> handleAAIArtifacts = handleAAIArtifacts(component, mockGenerator, generatorInputs);
373 if (handleAAIArtifacts.isLeft()) {
374 aiiArtifactList = handleAAIArtifacts.left().value();
376 log.debug("AAI Artifacts handling failed");
377 return Either.right(handleAAIArtifacts.right().value());
380 if (isInCertificationRequest) {
381 Either<ActionStatus, ResponseFormat> handleAllAAIArtifactsInDataModel = handleAllAAIArtifactsInDataModel(
382 component, aiiArtifactList, false, true);
384 if (handleAllAAIArtifactsInDataModel.isRight()) {
385 log.debug("AAI Artifacts handling (create, update, delete) failed");
386 return Either.right(handleAllAAIArtifactsInDataModel.right().value());
392 Either<CsarDefinition, ResponseFormat> collectedComponentCsarDefinition = collectComponentCsarDefinition(component);
394 if (collectedComponentCsarDefinition.isRight()) {
395 return Either.right(collectedComponentCsarDefinition.right().value());
398 return writeAllFilesToScar(component, collectedComponentCsarDefinition.left().value(), zip, isInCertificationRequest);
401 private Either<ZipOutputStream, ResponseFormat> addSchemaFilesFromCassandra(ZipOutputStream zip, byte[] schemaFileZip){
403 final int initSize = 2048;
405 log.debug("Starting copy from Schema file zip to CSAR zip");
407 try (ZipInputStream zipStream = new ZipInputStream(new ByteArrayInputStream(schemaFileZip));
408 ByteArrayOutputStream out = new ByteArrayOutputStream();
409 BufferedOutputStream bos = new BufferedOutputStream(out, initSize);) {
411 ZipEntry entry = null;
413 while ((entry = zipStream.getNextEntry()) != null) {
415 String entryName = entry.getName();
416 int readSize = initSize;
417 byte[] entryData = new byte[initSize];
419 while ((readSize = zipStream.read(entryData, 0, readSize)) != -1) {
420 bos.write(entryData, 0, readSize);
425 zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + entryName));
426 zip.write(out.toByteArray());
430 } catch (IOException e) {
431 log.error("Error while writing the SDC schema file to the CSAR {}", e);
432 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
435 log.debug("Finished coppy from Schema file zip to CSAR zip");
437 return Either.left(zip);
441 private void addInnerComponentsToCache(Map<String, ImmutableTriple<String, String, Component>> componentCache,
442 Component childComponent) {
444 List<ComponentInstance> instances = childComponent.getComponentInstances();
446 if(instances != null) {
447 instances.forEach(ci -> {
448 ImmutableTriple<String, String, Component> componentRecord = componentCache.get(ci.getComponentUid());
449 if (componentRecord == null) {
450 // all resource must be only once!
451 Either<Resource, StorageOperationStatus> resource = toscaOperationFacade.getToscaElement(ci.getComponentUid());
452 if (resource.isRight()) {
453 log.debug("Failed to fetch resource with id {} for instance {}");
455 Component componentRI = resource.left().value();
457 Map<String, ArtifactDefinition> childToscaArtifacts = componentRI.getToscaArtifacts();
458 ArtifactDefinition childArtifactDefinition = childToscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
459 if (childArtifactDefinition != null) {
461 addComponentToCache(componentCache, childArtifactDefinition.getEsId(), childArtifactDefinition.getArtifactName(), componentRI);
464 //if not atomic - insert inner components as well
465 if(!ModelConverter.isAtomicComponent(componentRI)) {
466 addInnerComponentsToCache(componentCache, componentRI);
473 private void addComponentToCache(Map<String, ImmutableTriple<String, String, Component>> componentCache,
474 String id, String fileName, Component component) {
476 ImmutableTriple<String, String, Component> cachedComponent = componentCache.get(component.getInvariantUUID());
477 if (cachedComponent == null || CommonBeUtils.compareAsdcComponentVersions(component.getVersion(), cachedComponent.getRight().getVersion())) {
478 componentCache.put(component.getInvariantUUID(),
479 new ImmutableTriple<String, String, Component>(id, fileName, component));
481 if(cachedComponent != null) {
482 //overwriting component with newer version
483 log.warn("Overwriting component invariantID {} of version {} with a newer version {}", id, cachedComponent.getRight().getVersion(), component.getVersion());
488 private Either<ZipOutputStream, ResponseFormat> writeComponentInterface(Component component, ZipOutputStream zip, String fileName) {
490 Either<ToscaRepresentation, ToscaError> componentInterface = toscaExportUtils.exportComponentInterface(component);
491 ToscaRepresentation componentInterfaceYaml = componentInterface.left().value();
492 String mainYaml = componentInterfaceYaml.getMainYaml();
493 String interfaceFileName = DEFINITIONS_PATH + ToscaExportHandler.getInterfaceFilename(fileName);
495 zip.putNextEntry(new ZipEntry(interfaceFileName));
496 zip.write(mainYaml.getBytes());
498 } catch (Exception e) {
499 log.error("#writeComponentInterface - zip writing failed with error: ", e);
500 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
503 return Either.left(zip);
506 private Either<List<ArtifactDefinition>, ResponseFormat> handleAAIArtifacts(Component component, boolean mockGenerator, List<ImmutablePair<Component, byte[]>> generatorInputs) {
508 ComponentTypeEnum componentType = component.getComponentType();
509 List<Artifact> generatedArtifacts;
510 List<ArtifactDefinition> aaiArtifacts = new LinkedList<>();
512 if (componentType == ComponentTypeEnum.SERVICE && !generatorInputs.isEmpty()) {
513 List<Artifact> convertedGeneratorInputs = convertToGeneratorArtifactsInput(generatorInputs);
515 Either<List<Artifact>, String> generatorResponse;
518 generatorResponse = artifactGenerator(convertedGeneratorInputs, ArtifactType.OTHER, component);
520 generatorResponse = artifactGenerator(convertedGeneratorInputs, ArtifactType.AAI, component);
523 if (generatorResponse.isRight()) {
524 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.AAI_ARTIFACT_GENERATION_FAILED, component.getComponentType().getValue(), component.getName(), generatorResponse.right().value());
525 return Either.right(responseFormat);
528 generatedArtifacts = generatorResponse.left().value();
530 aaiArtifacts = convertToArtifactDefinitionFromArtifactGeneratedData(generatedArtifacts);
534 return Either.left(aaiArtifacts);
537 private Either<ActionStatus, ResponseFormat> handleAllAAIArtifactsInDataModel(Component component, List<ArtifactDefinition> artifactsFromAAI, boolean shouldLock, boolean inTransaction) {
539 Either<ActionStatus, ResponseFormat> handleAAIArtifactsResponse;
540 User lastComponentUpdater;
542 List<ArtifactDefinition> aaiArtifatcsToCreate = getAAIArtifatcsForCreate(artifactsFromAAI, component);
543 List<ArtifactDefinition> aaiArtifatcsToDelete = getAAIArtifatcsForDelete(artifactsFromAAI, component);
544 List<ArtifactDefinition> aaiArtifatcsToUpdate = getAAIArtifatcsForUpdate(artifactsFromAAI, component);
546 String lastUpdaterUserId = component.getLastUpdaterUserId();
547 Either<User, ResponseFormat> validateUserExists = artifactsBusinessLogic.validateUserExists(lastUpdaterUserId, "CSAR creation util", true);
549 if (validateUserExists.isRight()) {
550 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.AAI_ARTIFACT_GENERATION_FAILED, component.getComponentType().getValue(), component.getName(), "User not found");
551 return Either.right(responseFormat);
554 lastComponentUpdater = validateUserExists.left().value();
556 handleAAIArtifactsResponse = handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToDelete, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.DELETE), lastComponentUpdater, shouldLock,
559 if (handleAAIArtifactsResponse.isRight()) {
560 return handleAAIArtifactsResponse;
563 handleAAIArtifactsResponse = handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToCreate, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.CREATE), lastComponentUpdater, shouldLock,
566 if (handleAAIArtifactsResponse.isRight()) {
567 return handleAAIArtifactsResponse;
570 return handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToUpdate, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.UPDATE), lastComponentUpdater, shouldLock, inTransaction);
573 private List<ArtifactDefinition> getAAIArtifatcsForUpdate(List<ArtifactDefinition> artifactsFromAAI, Component component) {
575 Set<String> componetDeploymentArtifactLables = component.getDeploymentArtifacts().keySet();
576 Set<String> componetInformationalArtifactLables = component.getArtifacts().keySet();
578 return artifactsFromAAI.stream()
579 .filter(e -> componetDeploymentArtifactLables.contains(e.getArtifactLabel()) || componetInformationalArtifactLables.contains(e.getArtifactLabel()))
580 .filter(e -> checkAaiForUpdate(component, e))
581 .collect(Collectors.toList());
584 private boolean checkAaiForUpdate(Component component, ArtifactDefinition artifactDefinition) {
585 ArtifactDefinition artifactDefinitionComp = component.getDeploymentArtifacts().get(artifactDefinition.getArtifactLabel());
587 if (artifactDefinitionComp == null) {
588 log.warn("Failed to get {} artifact", artifactDefinition.getArtifactLabel());
592 // Old Artifacts before the generated flag introduction if contains "aai" ignore case prefix updated
593 if (artifactDefinitionComp.getGenerated() == null) {
594 if (artifactDefinitionComp.getArtifactLabel().toLowerCase().startsWith("aai")) {
597 log.warn("The artifact {} flag is null but AAI prefix is abssent Not updated", artifactDefinition.getArtifactLabel());
600 if (artifactDefinition.getGenerated()) {
603 log.warn("Generated artifact {} was already uploaded manually", artifactDefinition.getArtifactLabel());
609 private List<ArtifactDefinition> getAAIArtifatcsForDelete(List<ArtifactDefinition> artifactsFromAAI, Component component) {
611 Set<String> aaiLabels = artifactsFromAAI.stream()
612 .map(ArtifactDefinition::getArtifactLabel)
613 .collect(Collectors.toSet());
615 List<ArtifactDefinition> artifactsForDeleteDeployment = component.getDeploymentArtifacts().values().stream()
616 // Filter Out Artifacts that are not contained in artifacts returned
618 .filter(e -> !aaiLabels.contains(e.getArtifactLabel()))
619 .collect(Collectors.toList());
621 List<ArtifactDefinition> artifactsForDeleteInformational = component.getArtifacts().values().stream()
622 // Filter Out Artifacts that are not contained in artifacts returned
624 .filter(e -> !aaiLabels.contains(e.getArtifactLabel()))
625 .collect(Collectors.toList());
627 artifactsForDeleteDeployment.addAll(artifactsForDeleteInformational);
629 return artifactsForDeleteDeployment.stream()
630 .filter(e -> (e.getGenerated() != null && e.getGenerated().equals(Boolean.TRUE)) || (e.getGenerated() == null && e.getArtifactLabel().toLowerCase().startsWith("aai")))
631 .collect(Collectors.toList());
634 private List<ArtifactDefinition> getAAIArtifatcsForCreate(List<ArtifactDefinition> artifactsFromAAI, Component component) {
636 Set<String> componentDeploymentLabels = component.getDeploymentArtifacts().keySet();
637 Set<String> componentInfoLabels = component.getArtifacts().keySet();
639 // If the artifact label does not exist in the service -
640 // store the artifact (generate uuid and version, "generated" flag is TRUE)
641 return artifactsFromAAI.stream()
642 .filter(e -> !componentDeploymentLabels.contains(e.getArtifactLabel()) && !componentInfoLabels.contains(e.getArtifactLabel()))
643 .collect(Collectors.toList());
646 private Either<ActionStatus, ResponseFormat> handleAAIArtifactsInDataModelByOperationType(Component component, List<ArtifactDefinition> generatedArtifactsDefinitions, ArtifactOperationInfo operationType, User user, boolean shouldLock,
647 boolean inTransaction) {
649 String componentUniqueId = component.getUniqueId();
650 ComponentTypeEnum componentType = component.getComponentType();
652 for (ArtifactDefinition artDef : generatedArtifactsDefinitions) {
653 String data = gson.toJson(artDef);
654 String dataMD5 = GeneralUtility.calculateMD5Base64EncodedByString(data);
655 String artifactUniqueId = null;
657 if ((operationType.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE) || (operationType.getArtifactOperationEnum() == ArtifactOperationEnum.DELETE)) {
658 String artifactLabel = artDef.getArtifactLabel();
659 ArtifactDefinition artifactDefinition = component.getDeploymentArtifacts().get(artifactLabel);
660 if (artifactDefinition != null) {
661 artifactUniqueId = artifactDefinition.getUniqueId();
665 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> validateAndHandleArtifact = artifactsBusinessLogic.validateAndHandleArtifact(componentUniqueId, componentType, operationType, artifactUniqueId, artDef, dataMD5, data, null,
666 null, user, component, shouldLock, inTransaction, false);
668 if (validateAndHandleArtifact.isRight()) {
669 if (ArtifactOperationEnum.isCreateOrLink(operationType.getArtifactOperationEnum()) || ArtifactOperationEnum.UPDATE == operationType.getArtifactOperationEnum()) {
670 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.AAI_ARTIFACT_GENERATION_FAILED, componentType.getValue(), component.getName(), validateAndHandleArtifact.right().value().toString());
672 Either.right(responseFormat);
674 log.warn("Generated artifact {} could not be deleted", artDef.getArtifactLabel());
679 return Either.left(ActionStatus.OK);
682 private List<ArtifactDefinition> convertToArtifactDefinitionFromArtifactGeneratedData(List<Artifact> generatorOutput) {
683 List<ArtifactDefinition> artifactDefList = new LinkedList<>();
685 for (Artifact artifact : generatorOutput) {
686 ArtifactDefinition newEntry = new ArtifactDefinition();
687 newEntry.setArtifactName(artifact.getName());
688 newEntry.setArtifactType(artifact.getType());
689 newEntry.setArtifactGroupType(ArtifactGroupTypeEnum.findType(artifact.getGroupType()));
690 newEntry.setDescription(artifact.getDescription());
692 // Normalizing the artifact label to match those stored in DB
693 String normalizeArtifactLabel = ValidationUtils.normalizeArtifactLabel(artifact.getLabel());
694 newEntry.setArtifactLabel(normalizeArtifactLabel);
695 newEntry.setPayload(Base64.decodeBase64(artifact.getPayload()));
696 newEntry.setArtifactChecksum(artifact.getChecksum());
697 // Flag that set to true in case that the artifact is generated by AI&I generator
698 newEntry.setGenerated(Boolean.TRUE);
700 artifactDefList.add(newEntry);
703 return artifactDefList;
706 // List<ImmutablePair<Component, byte[] artifactBytes>>
707 // artifact stored by label
708 private List<Artifact> convertToGeneratorArtifactsInput(List<ImmutablePair<Component, byte[]>> inputs) {
709 List<Artifact> listOfArtifactsInput = new LinkedList<>();
710 for (ImmutablePair<Component, byte[]> triple : inputs) {
711 Component component = triple.getLeft();
713 Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
714 ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
716 String artifactName = artifactDefinition.getArtifactName();
717 String artifactType = artifactDefinition.getArtifactType();
718 String artifactGroupType = artifactDefinition.getArtifactGroupType().getType();
719 String artifactDescription = artifactDefinition.getDescription();
720 String artifactLabel = artifactDefinition.getArtifactLabel();
721 byte[] right = triple.getRight();
722 // The md5 calculated on the uncoded data
723 String md5Hex = DigestUtils.md5Hex(right);
724 byte[] payload = Base64.encodeBase64(right);
725 String artifactVersion = artifactDefinition.getArtifactVersion();
727 Artifact convertedArtifact = new Artifact(artifactType, artifactGroupType, md5Hex, payload);
728 convertedArtifact.setName(artifactName);
729 convertedArtifact.setDescription(artifactDescription);
730 convertedArtifact.setLabel(artifactLabel);
731 convertedArtifact.setVersion(artifactVersion);
733 listOfArtifactsInput.add(convertedArtifact);
736 return listOfArtifactsInput;
739 private Either<byte[], ActionStatus> getEntryData(String cassandraId, Component childComponent) {
741 if (cassandraId == null || cassandraId.isEmpty()) {
742 Either<ToscaRepresentation, ToscaError> exportRes = toscaExportUtils.exportComponent(childComponent);
743 if (exportRes.isRight()) {
744 log.debug("Failed to export tosca template for child component {} error {}", childComponent.getUniqueId(), exportRes.right().value());
745 return Either.right(componentsUtils.convertFromToscaError(exportRes.right().value()));
747 content = exportRes.left().value().getMainYaml().getBytes();
749 Either<byte[], ActionStatus> fromCassandra = getFromCassandra(cassandraId);
750 if (fromCassandra.isRight()) {
751 return Either.right(fromCassandra.right().value());
753 content = fromCassandra.left().value();
756 return Either.left(content);
759 private Either<byte[], ResponseFormat> getLatestSchemaFilesFromCassandra() {
760 Either<List<SdcSchemaFilesData>, CassandraOperationStatus> specificSchemaFiles = sdcSchemaFilesCassandraDao.getSpecificSchemaFiles(versionFirstThreeOctates, CONFORMANCE_LEVEL);
762 if(specificSchemaFiles.isRight()){
763 log.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}", versionFirstThreeOctates, CONFORMANCE_LEVEL);
764 StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(specificSchemaFiles.right().value());
765 ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(storageStatus);
766 return Either.right(componentsUtils.getResponseFormat(convertedFromStorageResponse));
769 List<SdcSchemaFilesData> listOfSchemas = specificSchemaFiles.left().value();
771 if(listOfSchemas.isEmpty()){
772 log.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}", versionFirstThreeOctates, CONFORMANCE_LEVEL);
773 return Either.right(componentsUtils.getResponseFormat(ActionStatus.TOSCA_SCHEMA_FILES_NOT_FOUND, versionFirstThreeOctates, CONFORMANCE_LEVEL));
776 SdcSchemaFilesData schemaFile = listOfSchemas.iterator().next();
778 return Either.left(schemaFile.getPayloadAsArray());
781 private Either<byte[], ActionStatus> getFromCassandra(String cassandraId) {
782 Either<ESArtifactData, CassandraOperationStatus> artifactResponse = artifactCassandraDao.getArtifact(cassandraId);
784 if (artifactResponse.isRight()) {
785 log.debug("Failed to fetch artifact from Cassandra by id {} error {} ", cassandraId, artifactResponse.right().value());
787 StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactResponse.right().value());
788 ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(storageStatus);
789 return Either.right(convertedFromStorageResponse);
791 ESArtifactData artifactData = artifactResponse.left().value();
792 return Either.left(artifactData.getDataAsArray());
795 private String createCsarBlock0(String metaFileVersion, String toscaConformanceLevel) {
796 final String BLOCK_0_TEMPLATE =
797 "SDC-TOSCA-Meta-File-Version: %s\nSDC-TOSCA-Definitions-Version: %s\n";
798 String readyBlock = String.format(BLOCK_0_TEMPLATE, metaFileVersion, toscaConformanceLevel);
802 private String createToscaBlock0(String metaFileVersion, String csarVersion, String createdBy, String entryDef) {
803 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";
804 return String.format(block0template, metaFileVersion, csarVersion, createdBy, entryDef);
807 private Either<List<Artifact>, String> artifactGenerator(List<Artifact> artifactList, ArtifactType type, Component component) {
809 ArtifactGenerationServiceImpl artifactGenerationServiceImpl = new ArtifactGenerationServiceImpl();
810 ArtifactTypes artifactTypes = new ArtifactTypes();
811 List<ArtifactType> artifactTypesList = new LinkedList<>();
812 ArtifactType otherType;
815 otherType = ArtifactType.OTHER;
820 artifactTypesList.add(otherType);
821 artifactTypes.setArtifactTypes(artifactTypesList);
823 String configJson = gson.toJson(artifactTypes);
824 Map<String, String> additionalParams = new HashMap<>();
827 if (UUID_NORMATIVE_NEW_VERSION.matcher(component.getVersion()).matches() ) {
828 version = component.getVersion();
830 String[] versionParts = component.getVersion().split(ToscaElementLifecycleOperation.VERSION_DELIMETER_REGEXP);
831 Integer majorVersion = Integer.parseInt(versionParts[0]);
833 version = (majorVersion + 1) + ToscaElementLifecycleOperation.VERSION_DELIMETER + "0";
836 additionalParams.put(AdditionalParams.ServiceVersion.getName(), version);
837 GenerationData generatedArtifacts = artifactGenerationServiceImpl.generateArtifact(artifactList, configJson, additionalParams);
839 Map<String, List<String>> errorData = generatedArtifacts.getErrorData();
841 if (!errorData.isEmpty()) {
842 Set<String> keySet = errorData.keySet();
843 StringBuilder error = new StringBuilder();
845 for (String key : keySet) {
846 List<String> errorList = errorData.get(key);
847 log.debug("The Artifact Generator Failed - {} with following: {}", key, errorList);
848 error.append(key + errorList);
851 return Either.right(error.toString());
854 return Either.left(generatedArtifacts.getResultData());
858 * Extracts artifacts of VFCs from CSAR
861 * @return Map of <String, List<ArtifactDefinition>> the contains Lists of artifacts according vfcToscaNamespace
863 public static Map<String, List<ArtifactDefinition>> extractVfcsArtifactsFromCsar(Map<String, byte[]> csar) {
865 Map<String, List<ArtifactDefinition>> artifacts = new HashMap<>();
867 log.debug("************* Going to extract VFCs artifacts from Csar. ");
868 Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
869 csar.entrySet().stream()
870 // filter CSAR entry by node type artifact path
871 .filter(e -> Pattern.compile(VFC_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey()).matches())
872 // extract ArtifactDefinition from CSAR entry for each entry with matching artifact path
873 .forEach(e -> addExtractedVfcArtifact(extractVfcArtifact(e, collectedWarningMessages), artifacts));
874 // add counter suffix to artifact labels
875 handleWarningMessages(collectedWarningMessages);
882 * Print warnings to log
884 * @param collectedWarningMessages
886 public static void handleWarningMessages(Map<String, Set<List<String>>> collectedWarningMessages) {
887 collectedWarningMessages.entrySet().stream()
889 .forEach(e -> e.getValue().stream()
890 // add each warning message to log
891 .forEach(args -> log.warn(e.getKey(), args.toArray())));
895 private static void addExtractedVfcArtifact(ImmutablePair<String, ArtifactDefinition> extractedVfcArtifact, Map<String, List<ArtifactDefinition>> artifacts) {
896 if (extractedVfcArtifact != null) {
897 List<ArtifactDefinition> currArtifactsList;
898 String vfcToscaNamespace = extractedVfcArtifact.getKey();
899 if (artifacts.containsKey(vfcToscaNamespace)) {
900 currArtifactsList = artifacts.get(vfcToscaNamespace);
902 currArtifactsList = new ArrayList<>();
903 artifacts.put(vfcToscaNamespace, currArtifactsList);
905 currArtifactsList.add(extractedVfcArtifact.getValue());
909 private static ImmutablePair<String, ArtifactDefinition> extractVfcArtifact(Entry<String, byte[]> entry, Map<String, Set<List<String>>> collectedWarningMessages) {
910 ArtifactDefinition artifact;
911 String[] parsedCsarArtifactPath = entry.getKey().split("/");
912 Either<ArtifactGroupTypeEnum, Boolean> eitherArtifactGroupType = detectArtifactGroupType(parsedCsarArtifactPath[2].toUpperCase(), collectedWarningMessages);
913 if (eitherArtifactGroupType.isLeft()) {
914 artifact = buildArtifactDefinitionFromCsarArtifactPath(entry, collectedWarningMessages, parsedCsarArtifactPath, eitherArtifactGroupType.left().value());
918 return new ImmutablePair<>(parsedCsarArtifactPath[1], artifact);
921 private static Either<ArtifactGroupTypeEnum, Boolean> detectArtifactGroupType(String groupType, Map<String, Set<List<String>>> collectedWarningMessages) {
922 Either<ArtifactGroupTypeEnum, Boolean> result;
924 ArtifactGroupTypeEnum artifactGroupType = ArtifactGroupTypeEnum.findType(groupType.toUpperCase());
925 if (artifactGroupType == null || (artifactGroupType != ArtifactGroupTypeEnum.INFORMATIONAL && artifactGroupType != ArtifactGroupTypeEnum.DEPLOYMENT)) {
926 String warningMessage = "Warning - unrecognized artifact group type {} was received.";
927 List<String> messageArguments = new ArrayList<>();
928 messageArguments.add(groupType);
929 if (!collectedWarningMessages.containsKey(warningMessage)) {
930 Set<List<String>> messageArgumentLists = new HashSet<>();
931 messageArgumentLists.add(messageArguments);
932 collectedWarningMessages.put(warningMessage, messageArgumentLists);
934 collectedWarningMessages.get(warningMessage).add(messageArguments);
937 result = Either.right(false);
940 result = Either.left(artifactGroupType);
942 } catch (Exception e) {
943 log.debug("detectArtifactGroupType failed with exception", e);
944 result = Either.right(false);
949 private static ArtifactDefinition buildArtifactDefinitionFromCsarArtifactPath(Entry<String, byte[]> entry, Map<String, Set<List<String>>> collectedWarningMessages, String[] parsedCsarArtifactPath, ArtifactGroupTypeEnum artifactGroupType) {
950 ArtifactDefinition artifact;
951 artifact = new ArtifactDefinition();
952 artifact.setArtifactGroupType(artifactGroupType);
953 artifact.setArtifactType(detectArtifactTypeVFC(artifactGroupType, parsedCsarArtifactPath[3], parsedCsarArtifactPath[1], collectedWarningMessages));
954 artifact.setArtifactName(ValidationUtils.normalizeFileName(parsedCsarArtifactPath[parsedCsarArtifactPath.length - 1]));
955 artifact.setPayloadData(Base64.encodeBase64String(entry.getValue()));
956 artifact.setArtifactDisplayName(artifact.getArtifactName().lastIndexOf('.') > 0 ? artifact.getArtifactName().substring(0, artifact.getArtifactName().lastIndexOf('.')) : artifact.getArtifactName());
957 artifact.setArtifactLabel(ValidationUtils.normalizeArtifactLabel(artifact.getArtifactName()));
958 artifact.setDescription(ARTIFACT_CREATED_FROM_CSAR);
959 artifact.setIsFromCsar(true);
960 artifact.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(entry.getValue()));
964 public static final class NonMetaArtifactInfo {
965 private final String path;
966 private final String artifactName;
967 private final String displayName;
968 private final String artifactLabel;
969 private final ArtifactTypeEnum artifactType;
970 private final ArtifactGroupTypeEnum artifactGroupType;
971 private String payloadData;
972 private String artifactChecksum;
973 private String artifactUniqueId;
974 private final boolean isFromCsar;
976 public NonMetaArtifactInfo(String artifactName, String path, ArtifactTypeEnum artifactType, ArtifactGroupTypeEnum artifactGroupType, byte[] payloadData, String artifactUniqueId, boolean isFromCsar) {
979 this.isFromCsar = isFromCsar;
980 this.artifactName = ValidationUtils.normalizeFileName(artifactName);
981 this.artifactType = artifactType;
982 this.artifactGroupType = artifactGroupType;
983 final int pointIndex = artifactName.lastIndexOf('.');
984 if (pointIndex > 0) {
985 displayName = artifactName.substring(0, pointIndex);
987 displayName = artifactName;
989 this.artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactName);
990 if (payloadData != null) {
991 this.payloadData = Base64.encodeBase64String(payloadData);
992 this.artifactChecksum = GeneralUtility.calculateMD5Base64EncodedByByteArray(payloadData);
994 this.artifactUniqueId = artifactUniqueId;
997 public String getPath() {
1001 public String getArtifactName() {
1002 return artifactName;
1005 public ArtifactTypeEnum getArtifactType() {
1006 return artifactType;
1009 public String getDisplayName() {
1013 public ArtifactGroupTypeEnum getArtifactGroupType() {
1014 return artifactGroupType;
1017 public String getArtifactLabel() {
1018 return artifactLabel;
1021 public boolean isFromCsar(){
1025 public String getPayloadData() {
1029 public String getArtifactChecksum() {
1030 return artifactChecksum;
1033 public String getArtifactUniqueId() {
1034 return artifactUniqueId;
1037 public void setArtifactUniqueId(String artifactUniqueId) {
1038 this.artifactUniqueId = artifactUniqueId;
1044 * This method checks the artifact GroupType & Artifact Type. <br>
1045 * if there is any problem warning messages are added to collectedWarningMessages
1047 * @param artifactPath
1048 * @param collectedWarningMessages
1051 public static Either<NonMetaArtifactInfo, Boolean> validateNonMetaArtifact(String artifactPath, byte[] payloadData, Map<String, Set<List<String>>> collectedWarningMessages) {
1052 Either<NonMetaArtifactInfo, Boolean> ret;
1054 String[] parsedArtifactPath = artifactPath.split("/");
1055 // Validate Artifact Group Type
1056 Either<ArtifactGroupTypeEnum, Boolean> eitherGroupType = detectArtifactGroupType(parsedArtifactPath[1], collectedWarningMessages);
1057 if (eitherGroupType.isLeft()) {
1058 final ArtifactGroupTypeEnum groupTypeEnum = eitherGroupType.left().value();
1060 // Validate Artifact Type
1061 String artifactType = parsedArtifactPath[2];
1062 artifactType = detectArtifactTypeVF(groupTypeEnum, artifactType, collectedWarningMessages);
1064 String artifactFileNameType = parsedArtifactPath[3];
1065 ret = Either.left(new NonMetaArtifactInfo(artifactFileNameType, artifactPath, ArtifactTypeEnum.findType(artifactType), groupTypeEnum, payloadData, null, true));
1068 ret = Either.right(eitherGroupType.right().value());
1070 } catch (Exception e) {
1071 log.debug("detectArtifactGroupType failed with exception", e);
1072 ret = Either.right(false);
1078 private static String detectArtifactTypeVFC(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, String parentVfName, Map<String, Set<List<String>>> collectedWarningMessages) {
1079 String warningMessage = "Warning - artifact type {} that was provided for VFC {} is not recognized.";
1080 return detectArtifactType(artifactGroupType, receivedTypeName, warningMessage, collectedWarningMessages, parentVfName);
1083 private static String detectArtifactTypeVF(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, Map<String, Set<List<String>>> collectedWarningMessages) {
1084 String warningMessage = "Warning - artifact type {} that was provided for VF is not recognized.";
1085 return detectArtifactType(artifactGroupType, receivedTypeName, warningMessage, collectedWarningMessages);
1088 private static String detectArtifactType(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, String warningMessage, Map<String, Set<List<String>>> collectedWarningMessages, String... arguments) {
1090 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(receivedTypeName);
1091 Map<String, ArtifactTypeConfig> resourceValidTypeArtifacts = null;
1093 if(artifactGroupType != null){
1094 switch (artifactGroupType) {
1096 resourceValidTypeArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration()
1097 .getResourceInformationalArtifacts();
1100 resourceValidTypeArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration()
1101 .getResourceDeploymentArtifacts();
1108 Set<String> validArtifactTypes = null;
1109 if(resourceValidTypeArtifacts != null){
1110 validArtifactTypes = resourceValidTypeArtifacts.keySet();
1113 if (validArtifactTypes == null || artifactType == null || !validArtifactTypes.contains(artifactType.getType())) {
1114 List<String> messageArguments = new ArrayList<>();
1115 messageArguments.add(receivedTypeName);
1116 messageArguments.addAll(Arrays.asList(arguments));
1117 if (!collectedWarningMessages.containsKey(warningMessage)) {
1118 Set<List<String>> messageArgumentLists = new HashSet<>();
1119 messageArgumentLists.add(messageArguments);
1120 collectedWarningMessages.put(warningMessage, messageArgumentLists);
1122 collectedWarningMessages.get(warningMessage).add(messageArguments);
1126 return artifactType == null ? ArtifactTypeEnum.OTHER.getType() : artifactType.getType();
1129 private Either<ZipOutputStream, ResponseFormat> writeAllFilesToScar(Component mainComponent, CsarDefinition csarDefinition, ZipOutputStream zipstream, boolean isInCertificationRequest) throws IOException{
1130 ComponentArtifacts componentArtifacts = csarDefinition.getComponentArtifacts();
1132 Either<ZipOutputStream, ResponseFormat> writeComponentArtifactsToSpecifiedtPath = writeComponentArtifactsToSpecifiedtPath(mainComponent, componentArtifacts, zipstream, ARTIFACTS_PATH, isInCertificationRequest);
1134 if(writeComponentArtifactsToSpecifiedtPath.isRight()){
1135 return Either.right(writeComponentArtifactsToSpecifiedtPath.right().value());
1138 ComponentTypeArtifacts mainTypeAndCIArtifacts = componentArtifacts.getMainTypeAndCIArtifacts();
1139 writeComponentArtifactsToSpecifiedtPath = writeArtifactsInfoToSpecifiedtPath(mainComponent, mainTypeAndCIArtifacts.getComponentArtifacts(), zipstream, ARTIFACTS_PATH, isInCertificationRequest);
1141 if(writeComponentArtifactsToSpecifiedtPath.isRight()){
1142 return Either.right(writeComponentArtifactsToSpecifiedtPath.right().value());
1145 Map<String, ArtifactsInfo> componentInstancesArtifacts = mainTypeAndCIArtifacts.getComponentInstancesArtifacts();
1146 Set<String> keySet = componentInstancesArtifacts.keySet();
1148 String currentPath = ARTIFACTS_PATH + RESOURCES_PATH;
1149 for (String keyAssetName : keySet) {
1150 ArtifactsInfo artifactsInfo = componentInstancesArtifacts.get(keyAssetName);
1151 String pathWithAssetName = currentPath + keyAssetName + "/";
1152 writeComponentArtifactsToSpecifiedtPath = writeArtifactsInfoToSpecifiedtPath(mainComponent, artifactsInfo, zipstream, pathWithAssetName, isInCertificationRequest);
1154 if(writeComponentArtifactsToSpecifiedtPath.isRight()){
1155 return Either.right(writeComponentArtifactsToSpecifiedtPath.right().value());
1159 return Either.left(zipstream);
1162 private Either<ZipOutputStream, ResponseFormat> writeComponentArtifactsToSpecifiedtPath(Component mainComponent, ComponentArtifacts componentArtifacts, ZipOutputStream zipstream,
1163 String currentPath, boolean isInCertificationRequest) throws IOException {
1164 Map<String, ComponentTypeArtifacts> componentTypeArtifacts = componentArtifacts.getComponentTypeArtifacts();
1166 //<Inner Asset TOSCA name (e.g. VFC name)> folder name: <Inner Asset TOSCA name (e.g. VFC name)>_v<version>.
1167 //E.g. "org.openecomp.resource.vf.vipr_atm_v1.0"
1168 Set<String> componentTypeArtifactsKeys = componentTypeArtifacts.keySet();
1169 for (String keyAssetName : componentTypeArtifactsKeys) {
1170 ComponentTypeArtifacts componentInstanceArtifacts = componentTypeArtifacts.get(keyAssetName);
1171 ArtifactsInfo componentArtifacts2 = componentInstanceArtifacts.getComponentArtifacts();
1172 String pathWithAssetName = currentPath + keyAssetName + "/";
1173 Either<ZipOutputStream, ResponseFormat> writeArtifactsInfoToSpecifiedtPath = writeArtifactsInfoToSpecifiedtPath(mainComponent, componentArtifacts2, zipstream, pathWithAssetName, isInCertificationRequest);
1175 if(writeArtifactsInfoToSpecifiedtPath.isRight()){
1176 return writeArtifactsInfoToSpecifiedtPath;
1180 return Either.left(zipstream);
1183 private Either<ZipOutputStream, ResponseFormat> writeArtifactsInfoToSpecifiedtPath(Component mainComponent, ArtifactsInfo currArtifactsInfo, ZipOutputStream zip, String path, boolean isInCertificationRequest) throws IOException {
1184 Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> artifactsInfo = currArtifactsInfo
1185 .getArtifactsInfo();
1186 Set<ArtifactGroupTypeEnum> groupTypeEnumKeySet = artifactsInfo.keySet();
1188 for (ArtifactGroupTypeEnum artifactGroupTypeEnum : groupTypeEnumKeySet) {
1189 String groupTypeFolder = path + WordUtils.capitalizeFully(artifactGroupTypeEnum.getType()) + "/";
1191 Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactTypesMap = artifactsInfo.get(artifactGroupTypeEnum);
1192 Set<ArtifactTypeEnum> artifactTypeEnumKeySet = artifactTypesMap.keySet();
1194 for (ArtifactTypeEnum artifactTypeEnum : artifactTypeEnumKeySet) {
1195 List<ArtifactDefinition> artifactDefinitionList = artifactTypesMap.get(artifactTypeEnum);
1196 String artifactTypeFolder = groupTypeFolder + artifactTypeEnum.toString() + "/";
1198 Either<ZipOutputStream, ResponseFormat> writeArtifactDefinition = writeArtifactDefinition(mainComponent, zip, artifactDefinitionList, artifactTypeFolder, isInCertificationRequest);
1200 if(writeArtifactDefinition.isRight()){
1201 return writeArtifactDefinition;
1206 return Either.left(zip);
1209 private Either<ZipOutputStream, ResponseFormat> writeArtifactDefinition(Component mainComponent, ZipOutputStream zip, List<ArtifactDefinition> artifactDefinitionList,
1210 String artifactPathAndFolder, boolean isInCertificationRequest) throws IOException {
1212 ComponentTypeEnum componentType = mainComponent.getComponentType();
1213 String heatEnvType = ArtifactTypeEnum.HEAT_ENV.getType();
1215 for (ArtifactDefinition artifactDefinition : artifactDefinitionList) {
1216 if (!isInCertificationRequest && componentType == ComponentTypeEnum.SERVICE
1217 && artifactDefinition.getArtifactType().equals(heatEnvType) ||
1218 //this is placeholder
1219 (artifactDefinition.getEsId() == null && artifactDefinition.getMandatory())){
1223 byte[] payloadData = artifactDefinition.getPayloadData();
1224 String artifactFileName = artifactDefinition.getArtifactName();
1226 if (payloadData == null) {
1227 Either<byte[], ActionStatus> fromCassandra = getFromCassandra(artifactDefinition.getEsId());
1229 if (fromCassandra.isRight()) {
1230 log.debug("ArtifactName {}, unique ID {}", artifactDefinition.getArtifactName(), artifactDefinition.getUniqueId());
1231 log.debug("Failed to get {} payload from DB reason: {}", artifactFileName, fromCassandra.right().value());
1234 payloadData = fromCassandra.left().value();
1236 zip.putNextEntry(new ZipEntry(artifactPathAndFolder + artifactFileName));
1237 zip.write(payloadData);
1240 return Either.left(zip);
1243 /************************************ Artifacts Structure ******************************************************************/
1245 * The artifacts Definition saved by their structure
1247 private class ArtifactsInfo {
1248 //Key is the type of artifacts(Informational/Deployment)
1249 //Value is a map between an artifact type and a list of all artifacts of this type
1250 private Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> artifactsInfoField;
1252 public ArtifactsInfo() {
1253 this.artifactsInfoField = new EnumMap<>(ArtifactGroupTypeEnum.class);
1256 public Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> getArtifactsInfo() {
1257 return artifactsInfoField;
1260 public List<ArtifactDefinition> getFlatArtifactsListByType(ArtifactTypeEnum artifactType){
1261 List<ArtifactDefinition> artifacts = new ArrayList<>();
1262 for (List<ArtifactDefinition> artifactsByType:artifactsInfoField.get(artifactType).values()){
1263 artifacts.addAll(artifactsByType);
1268 public void addArtifactsToGroup(ArtifactGroupTypeEnum artifactGroup,Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactsDefinition){
1269 artifactsInfoField.put(artifactGroup, artifactsDefinition);
1272 public boolean isEmpty() {
1273 return artifactsInfoField.isEmpty();
1279 * The artifacts of the component and of all its composed instances
1282 private class ComponentTypeArtifacts {
1283 private ArtifactsInfo componentArtifacts; //component artifacts (describes the Informational Deployment folders)
1284 private Map<String, ArtifactsInfo> componentInstancesArtifacts; //artifacts of the composed instances mapped by the resourceInstance normalized name (describes the Resources folder)
1286 public ComponentTypeArtifacts() {
1287 componentArtifacts = new ArtifactsInfo();
1288 componentInstancesArtifacts = new HashMap<>();
1291 public ArtifactsInfo getComponentArtifacts() {
1292 return componentArtifacts;
1294 public void setComponentArtifacts(ArtifactsInfo artifactsInfo) {
1295 this.componentArtifacts = artifactsInfo;
1297 public Map<String, ArtifactsInfo> getComponentInstancesArtifacts() {
1298 return componentInstancesArtifacts;
1300 public void setComponentInstancesArtifacts(Map<String, ArtifactsInfo> componentInstancesArtifacts) {
1301 this.componentInstancesArtifacts = componentInstancesArtifacts;
1304 public void addComponentInstancesArtifacts(String normalizedName, ArtifactsInfo artifactsInfo) {
1305 componentInstancesArtifacts.put(normalizedName, artifactsInfo);
1310 private class ComponentArtifacts {
1311 //artifacts of the component and CI's artifacts contained in it's composition (represents Informational, Deployment & Resource folders of main component)
1312 private ComponentTypeArtifacts mainTypeAndCIArtifacts;
1313 //artifacts of all component types mapped by their tosca name
1314 private Map<String, ComponentTypeArtifacts> componentTypeArtifacts;
1316 public ComponentArtifacts(){
1317 mainTypeAndCIArtifacts = new ComponentTypeArtifacts();
1318 componentTypeArtifacts = new HashMap<>();
1321 public ComponentTypeArtifacts getMainTypeAndCIArtifacts() {
1322 return mainTypeAndCIArtifacts;
1325 public void setMainTypeAndCIArtifacts(ComponentTypeArtifacts componentInstanceArtifacts) {
1326 this.mainTypeAndCIArtifacts = componentInstanceArtifacts;
1329 public Map<String, ComponentTypeArtifacts> getComponentTypeArtifacts() {
1330 return componentTypeArtifacts;
1333 public void setComponentTypeArtifacts(Map<String, ComponentTypeArtifacts> componentTypeArtifacts) {
1334 this.componentTypeArtifacts = componentTypeArtifacts;
1338 private class CsarDefinition {
1339 private ComponentArtifacts componentArtifacts;
1341 // add list of tosca artifacts and meta describes CSAR zip root
1343 public CsarDefinition(ComponentArtifacts componentArtifacts) {
1344 this.componentArtifacts = componentArtifacts;
1347 public ComponentArtifacts getComponentArtifacts() {
1348 return componentArtifacts;
1352 /************************************ Artifacts Structure END******************************************************************/
1354 private Either<CsarDefinition,ResponseFormat> collectComponentCsarDefinition(Component component){
1355 ComponentArtifacts componentArtifacts = new ComponentArtifacts();
1356 Component updatedComponent = component;
1358 //get service to receive the AII artifacts uploaded to the service
1359 if (updatedComponent.getComponentType() == ComponentTypeEnum.SERVICE) {
1360 Either<Service, StorageOperationStatus> getServiceResponse = toscaOperationFacade.getToscaElement(updatedComponent.getUniqueId());
1362 if(getServiceResponse.isRight()){
1363 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getServiceResponse.right().value());
1364 return Either.right(componentsUtils.getResponseFormat(actionStatus));
1367 updatedComponent = getServiceResponse.left().value();
1370 //find the artifacts of the main component, it would have its composed instances artifacts in a separate folder
1371 ComponentTypeArtifacts componentInstanceArtifacts = new ComponentTypeArtifacts();
1372 ArtifactsInfo artifactsInfo = collectComponentArtifacts(updatedComponent);
1373 componentInstanceArtifacts.setComponentArtifacts(artifactsInfo);
1374 componentArtifacts.setMainTypeAndCIArtifacts(componentInstanceArtifacts);
1376 Map<String,ComponentTypeArtifacts> resourceTypeArtifacts = componentArtifacts.getComponentTypeArtifacts(); //artifacts mapped by the component type(tosca name+version)
1377 //get the component instances
1378 List<ComponentInstance> componentInstances = updatedComponent.getComponentInstances();
1379 if (componentInstances!=null){
1380 for (ComponentInstance componentInstance:componentInstances){
1381 //call recursive to find artifacts for all the path
1382 Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts = collectComponentInstanceArtifacts(
1383 updatedComponent, componentInstance, resourceTypeArtifacts, componentInstanceArtifacts);
1384 if (collectComponentInstanceArtifacts.isRight()){
1385 return Either.right(collectComponentInstanceArtifacts.right().value());
1390 if(log.isDebugEnabled()){
1391 printResult(componentArtifacts,updatedComponent.getName());
1394 return Either.left(new CsarDefinition(componentArtifacts));
1397 private void printResult(ComponentArtifacts componentArtifacts, String name) {
1398 StringBuilder result = new StringBuilder();
1399 result.append("Artifacts of main component " + name + "\n");
1400 ComponentTypeArtifacts componentInstanceArtifacts = componentArtifacts.getMainTypeAndCIArtifacts();
1401 printArtifacts(componentInstanceArtifacts);
1402 result.append("Type Artifacts\n");
1403 for (Map.Entry<String, ComponentTypeArtifacts> typeArtifacts:componentArtifacts.getComponentTypeArtifacts().entrySet()){
1404 result.append("Folder " + typeArtifacts.getKey() + "\n");
1405 result.append(printArtifacts(typeArtifacts.getValue()));
1408 if(log.isDebugEnabled()){
1409 log.debug(result.toString());
1413 private String printArtifacts(ComponentTypeArtifacts componentInstanceArtifacts) {
1414 StringBuilder result = new StringBuilder();
1415 ArtifactsInfo artifactsInfo = componentInstanceArtifacts.getComponentArtifacts();
1416 Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> componetArtifacts = artifactsInfo.getArtifactsInfo();
1417 printArtifacts(componetArtifacts);
1418 result = result.append("Resources\n");
1419 for (Map.Entry<String, ArtifactsInfo> resourceInstance:componentInstanceArtifacts.getComponentInstancesArtifacts().entrySet()){
1420 result.append("Folder" + resourceInstance.getKey() + "\n");
1421 result.append(printArtifacts(resourceInstance.getValue().getArtifactsInfo()));
1424 return result.toString();
1427 private String printArtifacts(Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> componetArtifacts) {
1428 StringBuilder result = new StringBuilder();
1429 for (Map.Entry<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> artifactGroup:componetArtifacts.entrySet()){
1430 result.append(" " + artifactGroup.getKey().getType());
1431 for (Map.Entry<ArtifactTypeEnum, List<ArtifactDefinition>> groupArtifacts:artifactGroup.getValue().entrySet()){
1432 result.append(" " + groupArtifacts.getKey().getType());
1433 for (ArtifactDefinition artifact:groupArtifacts.getValue()){
1434 result.append(" " + artifact.getArtifactDisplayName());
1439 return result.toString();
1442 private ComponentTypeArtifacts collectComponentTypeArtifacts(Map<String, ComponentTypeArtifacts> resourcesArtifacts, ComponentInstance componentInstance,
1443 Resource fetchedComponent) {
1444 String toscaComponentName = componentInstance.getToscaComponentName() + "_v" + componentInstance.getComponentVersion();
1446 ComponentTypeArtifacts componentArtifactsInfo = resourcesArtifacts.get(toscaComponentName);
1447 //if there are no artifacts for this component type we need to fetch and build them
1448 if (componentArtifactsInfo==null){
1449 ArtifactsInfo componentArtifacts = collectComponentArtifacts(fetchedComponent);
1450 componentArtifactsInfo = new ComponentTypeArtifacts();
1451 if (!componentArtifacts.isEmpty()){
1452 componentArtifactsInfo.setComponentArtifacts(componentArtifacts);
1453 resourcesArtifacts.put(toscaComponentName, componentArtifactsInfo);
1456 return componentArtifactsInfo;
1459 private Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts(Component parentComponent,ComponentInstance componentInstance,
1460 Map<String, ComponentTypeArtifacts> resourcesTypeArtifacts,ComponentTypeArtifacts instanceArtifactsLocation) {
1461 //1. get the component instance component
1462 String componentUid = componentInstance.getComponentUid();
1463 Either<Resource, StorageOperationStatus> resource = toscaOperationFacade.getToscaElement(componentUid);
1464 if (resource.isRight()) {
1465 log.error("Failed to fetch resource with id {} for instance {}",componentUid, parentComponent.getUUID());
1466 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ASSET_NOT_FOUND_DURING_CSAR_CREATION,
1467 parentComponent.getComponentType().getValue(), parentComponent.getUUID(),
1468 componentInstance.getOriginType().getComponentType().getValue(), componentUid));
1470 Resource fetchedComponent = resource.left().value();
1472 //2. fill the artifacts for the current component parent type
1473 ComponentTypeArtifacts componentParentArtifacts = collectComponentTypeArtifacts(resourcesTypeArtifacts, componentInstance, fetchedComponent);
1475 //3. find the artifacts specific to the instance
1476 Map<ArtifactTypeEnum, List<ArtifactDefinition>> componentInstanceSpecificInformationalArtifacts =
1477 getComponentInstanceSpecificArtifacts(componentInstance.getArtifacts(),
1478 componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), ArtifactGroupTypeEnum.INFORMATIONAL);
1479 Map<ArtifactTypeEnum, List<ArtifactDefinition>> componentInstanceSpecificDeploymentArtifacts =
1480 getComponentInstanceSpecificArtifacts(componentInstance.getDeploymentArtifacts(),
1481 componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), ArtifactGroupTypeEnum.DEPLOYMENT);
1483 //4. add the instances artifacts to the component type
1484 ArtifactsInfo artifactsInfo = new ArtifactsInfo();
1485 if (!componentInstanceSpecificInformationalArtifacts.isEmpty()){
1486 artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.INFORMATIONAL, componentInstanceSpecificInformationalArtifacts);
1488 if (!componentInstanceSpecificDeploymentArtifacts.isEmpty()){
1489 artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, componentInstanceSpecificDeploymentArtifacts);
1491 if (!artifactsInfo.isEmpty()){
1492 instanceArtifactsLocation.addComponentInstancesArtifacts(componentInstance.getNormalizedName(), artifactsInfo);
1495 //5. do the same for all the component instances
1496 List<ComponentInstance> componentInstances = fetchedComponent.getComponentInstances();
1497 if (componentInstances!=null){
1498 for (ComponentInstance childComponentInstance:componentInstances){
1499 Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts = collectComponentInstanceArtifacts(
1500 fetchedComponent, childComponentInstance, resourcesTypeArtifacts, componentParentArtifacts);
1501 if (collectComponentInstanceArtifacts.isRight()){
1502 return collectComponentInstanceArtifacts;
1507 return Either.left(true);
1510 private Map<ArtifactTypeEnum, List<ArtifactDefinition>> getComponentInstanceSpecificArtifacts(Map<String, ArtifactDefinition> componentArtifacts,
1511 Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> componentTypeArtifacts, ArtifactGroupTypeEnum artifactGroupTypeEnum) {
1512 Map<ArtifactTypeEnum, List<ArtifactDefinition>> parentArtifacts = componentTypeArtifacts.get(artifactGroupTypeEnum); //the artfiacts of the component itself and not the instance
1514 Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactsByTypeOfComponentInstance = new EnumMap<>(ArtifactTypeEnum.class);
1515 if (componentArtifacts!=null){
1516 for (ArtifactDefinition artifact:componentArtifacts.values()){
1517 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifact.getArtifactType());
1518 List<ArtifactDefinition> parentArtifactsByType = null;
1519 if (parentArtifacts!=null){
1520 parentArtifactsByType = parentArtifacts.get(artifactType);
1522 //the artifact is of instance
1523 if (parentArtifactsByType == null || !parentArtifactsByType.contains(artifact)){
1524 List<ArtifactDefinition> typeArtifacts = artifactsByTypeOfComponentInstance.get(artifactType);
1525 if (typeArtifacts == null){
1526 typeArtifacts = new ArrayList<>();
1527 artifactsByTypeOfComponentInstance.put(artifactType, typeArtifacts);
1529 typeArtifacts.add(artifact);
1534 return artifactsByTypeOfComponentInstance;
1537 private ArtifactsInfo collectComponentArtifacts(Component component) {
1538 Map<String, ArtifactDefinition> informationalArtifacts = component.getArtifacts();
1539 Map<ArtifactTypeEnum, List<ArtifactDefinition>> informationalArtifactsByType = collectGroupArtifacts(informationalArtifacts);
1540 Map<String, ArtifactDefinition> deploymentArtifacts = component.getDeploymentArtifacts();
1541 Map<ArtifactTypeEnum, List<ArtifactDefinition>> deploymentArtifactsByType = collectGroupArtifacts(deploymentArtifacts);
1542 ArtifactsInfo artifactsInfo = new ArtifactsInfo();
1543 if (!informationalArtifactsByType.isEmpty()){
1544 artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.INFORMATIONAL, informationalArtifactsByType);
1546 if (!deploymentArtifactsByType.isEmpty() ){
1547 artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, deploymentArtifactsByType);
1550 return artifactsInfo;
1553 private Map<ArtifactTypeEnum, List<ArtifactDefinition>> collectGroupArtifacts(Map<String, ArtifactDefinition> componentArtifacts) {
1554 Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactsByType = new EnumMap<>(ArtifactTypeEnum.class);
1555 for (ArtifactDefinition artifact:componentArtifacts.values()){
1556 if (artifact.getArtifactUUID()!=null){
1557 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifact.getArtifactType());
1558 List<ArtifactDefinition> typeArtifacts = artifactsByType.get(artifactType);
1559 if (typeArtifacts==null){
1560 typeArtifacts = new ArrayList<>();
1561 artifactsByType.put(artifactType, typeArtifacts);
1563 typeArtifacts.add(artifact);
1566 return artifactsByType;