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 Logger log = LoggerFactory.getLogger(CsarUtils.class.getName());
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 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
502 return Either.left(zip);
505 private Either<List<ArtifactDefinition>, ResponseFormat> handleAAIArtifacts(Component component, boolean mockGenerator, List<ImmutablePair<Component, byte[]>> generatorInputs) {
507 ComponentTypeEnum componentType = component.getComponentType();
508 List<Artifact> generatedArtifacts;
509 List<ArtifactDefinition> aaiArtifacts = new LinkedList<>();
511 if (componentType == ComponentTypeEnum.SERVICE && !generatorInputs.isEmpty()) {
512 List<Artifact> convertedGeneratorInputs = convertToGeneratorArtifactsInput(generatorInputs);
514 Either<List<Artifact>, String> generatorResponse;
517 generatorResponse = artifactGenerator(convertedGeneratorInputs, ArtifactType.OTHER, component);
519 generatorResponse = artifactGenerator(convertedGeneratorInputs, ArtifactType.AAI, component);
522 if (generatorResponse.isRight()) {
523 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.AAI_ARTIFACT_GENERATION_FAILED, component.getComponentType().getValue(), component.getName(), generatorResponse.right().value());
524 return Either.right(responseFormat);
527 generatedArtifacts = generatorResponse.left().value();
529 aaiArtifacts = convertToArtifactDefinitionFromArtifactGeneratedData(generatedArtifacts);
533 return Either.left(aaiArtifacts);
536 private Either<ActionStatus, ResponseFormat> handleAllAAIArtifactsInDataModel(Component component, List<ArtifactDefinition> artifactsFromAAI, boolean shouldLock, boolean inTransaction) {
538 Either<ActionStatus, ResponseFormat> handleAAIArtifactsResponse;
539 User lastComponentUpdater;
541 List<ArtifactDefinition> aaiArtifatcsToCreate = getAAIArtifatcsForCreate(artifactsFromAAI, component);
542 List<ArtifactDefinition> aaiArtifatcsToDelete = getAAIArtifatcsForDelete(artifactsFromAAI, component);
543 List<ArtifactDefinition> aaiArtifatcsToUpdate = getAAIArtifatcsForUpdate(artifactsFromAAI, component);
545 String lastUpdaterUserId = component.getLastUpdaterUserId();
546 Either<User, ResponseFormat> validateUserExists = artifactsBusinessLogic.validateUserExists(lastUpdaterUserId, "CSAR creation util", true);
548 if (validateUserExists.isRight()) {
549 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.AAI_ARTIFACT_GENERATION_FAILED, component.getComponentType().getValue(), component.getName(), "User not found");
550 return Either.right(responseFormat);
553 lastComponentUpdater = validateUserExists.left().value();
555 handleAAIArtifactsResponse = handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToDelete, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Delete), lastComponentUpdater, shouldLock,
558 if (handleAAIArtifactsResponse.isRight()) {
559 return handleAAIArtifactsResponse;
562 handleAAIArtifactsResponse = handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToCreate, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create), lastComponentUpdater, shouldLock,
565 if (handleAAIArtifactsResponse.isRight()) {
566 return handleAAIArtifactsResponse;
569 return handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToUpdate, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Update), lastComponentUpdater, shouldLock, inTransaction);
572 private List<ArtifactDefinition> getAAIArtifatcsForUpdate(List<ArtifactDefinition> artifactsFromAAI, Component component) {
574 Set<String> componetDeploymentArtifactLables = component.getDeploymentArtifacts().keySet();
575 Set<String> componetInformationalArtifactLables = component.getArtifacts().keySet();
577 return artifactsFromAAI.stream()
578 .filter(e -> componetDeploymentArtifactLables.contains(e.getArtifactLabel()) || componetInformationalArtifactLables.contains(e.getArtifactLabel()))
579 .filter(e -> checkAaiForUpdate(component, e))
580 .collect(Collectors.toList());
583 private boolean checkAaiForUpdate(Component component, ArtifactDefinition artifactDefinition) {
584 ArtifactDefinition artifactDefinitionComp = component.getDeploymentArtifacts().get(artifactDefinition.getArtifactLabel());
586 if (artifactDefinitionComp == null) {
587 log.warn("Failed to get {} artifact", artifactDefinition.getArtifactLabel());
591 // Old Artifacts before the generated flag introduction if contains "aai" ignore case prefix updated
592 if (artifactDefinitionComp.getGenerated() == null) {
593 if (artifactDefinitionComp.getArtifactLabel().toLowerCase().startsWith("aai")) {
596 log.warn("The artifact {} flag is null but AAI prefix is abssent Not updated", artifactDefinition.getArtifactLabel());
599 if (artifactDefinition.getGenerated()) {
602 log.warn("Generated artifact {} was already uploaded manually", artifactDefinition.getArtifactLabel());
608 private List<ArtifactDefinition> getAAIArtifatcsForDelete(List<ArtifactDefinition> artifactsFromAAI, Component component) {
610 Set<String> aaiLabels = artifactsFromAAI.stream()
611 .map(ArtifactDefinition::getArtifactLabel)
612 .collect(Collectors.toSet());
614 List<ArtifactDefinition> artifactsForDeleteDeployment = component.getDeploymentArtifacts().values().stream()
615 // Filter Out Artifacts that are not contained in artifacts returned
617 .filter(e -> !aaiLabels.contains(e.getArtifactLabel()))
618 .collect(Collectors.toList());
620 List<ArtifactDefinition> artifactsForDeleteInformational = component.getArtifacts().values().stream()
621 // Filter Out Artifacts that are not contained in artifacts returned
623 .filter(e -> !aaiLabels.contains(e.getArtifactLabel()))
624 .collect(Collectors.toList());
626 artifactsForDeleteDeployment.addAll(artifactsForDeleteInformational);
628 return artifactsForDeleteDeployment.stream()
629 .filter(e -> (e.getGenerated() != null && e.getGenerated().equals(Boolean.TRUE)) || (e.getGenerated() == null && e.getArtifactLabel().toLowerCase().startsWith("aai")))
630 .collect(Collectors.toList());
633 private List<ArtifactDefinition> getAAIArtifatcsForCreate(List<ArtifactDefinition> artifactsFromAAI, Component component) {
635 Set<String> componentDeploymentLabels = component.getDeploymentArtifacts().keySet();
636 Set<String> componentInfoLabels = component.getArtifacts().keySet();
638 // If the artifact label does not exist in the service -
639 // store the artifact (generate uuid and version, "generated" flag is TRUE)
640 return artifactsFromAAI.stream()
641 .filter(e -> !componentDeploymentLabels.contains(e.getArtifactLabel()) && !componentInfoLabels.contains(e.getArtifactLabel()))
642 .collect(Collectors.toList());
645 private Either<ActionStatus, ResponseFormat> handleAAIArtifactsInDataModelByOperationType(Component component, List<ArtifactDefinition> generatedArtifactsDefinitions, ArtifactOperationInfo operationType, User user, boolean shouldLock,
646 boolean inTransaction) {
648 String componentUniqueId = component.getUniqueId();
649 ComponentTypeEnum componentType = component.getComponentType();
651 for (ArtifactDefinition artDef : generatedArtifactsDefinitions) {
652 String data = gson.toJson(artDef);
653 String dataMD5 = GeneralUtility.calculateMD5Base64EncodedByString(data);
654 String artifactUniqueId = null;
656 if ((operationType.getArtifactOperationEnum() == ArtifactOperationEnum.Update) || (operationType.getArtifactOperationEnum() == ArtifactOperationEnum.Delete)) {
657 String artifactLabel = artDef.getArtifactLabel();
658 ArtifactDefinition artifactDefinition = component.getDeploymentArtifacts().get(artifactLabel);
659 if (artifactDefinition != null) {
660 artifactUniqueId = artifactDefinition.getUniqueId();
664 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> validateAndHandleArtifact = artifactsBusinessLogic.validateAndHandleArtifact(componentUniqueId, componentType, operationType, artifactUniqueId, artDef, dataMD5, data, null,
665 null, null, user, component, shouldLock, inTransaction, false);
667 if (validateAndHandleArtifact.isRight()) {
668 if (ArtifactOperationEnum.isCreateOrLink(operationType.getArtifactOperationEnum()) || ArtifactOperationEnum.Update == operationType.getArtifactOperationEnum()) {
669 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.AAI_ARTIFACT_GENERATION_FAILED, componentType.getValue(), component.getName(), validateAndHandleArtifact.right().value().toString());
671 Either.right(responseFormat);
673 log.warn("Generated artifact {} could not be deleted", artDef.getArtifactLabel());
678 return Either.left(ActionStatus.OK);
681 private List<ArtifactDefinition> convertToArtifactDefinitionFromArtifactGeneratedData(List<Artifact> generatorOutput) {
682 List<ArtifactDefinition> artifactDefList = new LinkedList<>();
684 for (Artifact artifact : generatorOutput) {
685 ArtifactDefinition newEntry = new ArtifactDefinition();
686 newEntry.setArtifactName(artifact.getName());
687 newEntry.setArtifactType(artifact.getType());
688 newEntry.setArtifactGroupType(ArtifactGroupTypeEnum.findType(artifact.getGroupType()));
689 newEntry.setDescription(artifact.getDescription());
691 // Normalizing the artifact label to match those stored in DB
692 String normalizeArtifactLabel = ValidationUtils.normalizeArtifactLabel(artifact.getLabel());
693 newEntry.setArtifactLabel(normalizeArtifactLabel);
694 newEntry.setPayload(Base64.decodeBase64(artifact.getPayload()));
695 newEntry.setArtifactChecksum(artifact.getChecksum());
696 // Flag that set to true in case that the artifact is generated by AI&I generator
697 newEntry.setGenerated(Boolean.TRUE);
699 artifactDefList.add(newEntry);
702 return artifactDefList;
705 // List<ImmutablePair<Component, byte[] artifactBytes>>
706 // artifact stored by label
707 private List<Artifact> convertToGeneratorArtifactsInput(List<ImmutablePair<Component, byte[]>> inputs) {
708 List<Artifact> listOfArtifactsInput = new LinkedList<>();
709 for (ImmutablePair<Component, byte[]> triple : inputs) {
710 Component component = triple.getLeft();
712 Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
713 ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
715 String artifactName = artifactDefinition.getArtifactName();
716 String artifactType = artifactDefinition.getArtifactType();
717 String artifactGroupType = artifactDefinition.getArtifactGroupType().getType();
718 String artifactDescription = artifactDefinition.getDescription();
719 String artifactLabel = artifactDefinition.getArtifactLabel();
720 byte[] right = triple.getRight();
721 // The md5 calculated on the uncoded data
722 String md5Hex = DigestUtils.md5Hex(right);
723 byte[] payload = Base64.encodeBase64(right);
724 String artifactVersion = artifactDefinition.getArtifactVersion();
726 Artifact convertedArtifact = new Artifact(artifactType, artifactGroupType, md5Hex, payload);
727 convertedArtifact.setName(artifactName);
728 convertedArtifact.setDescription(artifactDescription);
729 convertedArtifact.setLabel(artifactLabel);
730 convertedArtifact.setVersion(artifactVersion);
732 listOfArtifactsInput.add(convertedArtifact);
735 return listOfArtifactsInput;
738 private Either<byte[], ActionStatus> getEntryData(String cassandraId, Component childComponent) {
740 if (cassandraId == null || cassandraId.isEmpty()) {
741 Either<ToscaRepresentation, ToscaError> exportRes = toscaExportUtils.exportComponent(childComponent);
742 if (exportRes.isRight()) {
743 log.debug("Failed to export tosca template for child component {} error {}", childComponent.getUniqueId(), exportRes.right().value());
744 return Either.right(componentsUtils.convertFromToscaError(exportRes.right().value()));
746 content = exportRes.left().value().getMainYaml().getBytes();
748 Either<byte[], ActionStatus> fromCassandra = getFromCassandra(cassandraId);
749 if (fromCassandra.isRight()) {
750 return Either.right(fromCassandra.right().value());
752 content = fromCassandra.left().value();
755 return Either.left(content);
758 private Either<byte[], ResponseFormat> getLatestSchemaFilesFromCassandra() {
759 Either<List<SdcSchemaFilesData>, CassandraOperationStatus> specificSchemaFiles = sdcSchemaFilesCassandraDao.getSpecificSchemaFiles(versionFirstThreeOctates, CONFORMANCE_LEVEL);
761 if(specificSchemaFiles.isRight()){
762 log.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}", versionFirstThreeOctates, CONFORMANCE_LEVEL);
763 StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(specificSchemaFiles.right().value());
764 ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(storageStatus);
765 return Either.right(componentsUtils.getResponseFormat(convertedFromStorageResponse));
768 List<SdcSchemaFilesData> listOfSchemas = specificSchemaFiles.left().value();
770 if(listOfSchemas.isEmpty()){
771 log.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}", versionFirstThreeOctates, CONFORMANCE_LEVEL);
772 return Either.right(componentsUtils.getResponseFormat(ActionStatus.TOSCA_SCHEMA_FILES_NOT_FOUND, versionFirstThreeOctates, CONFORMANCE_LEVEL));
775 SdcSchemaFilesData schemaFile = listOfSchemas.iterator().next();
777 return Either.left(schemaFile.getPayloadAsArray());
780 private Either<byte[], ActionStatus> getFromCassandra(String cassandraId) {
781 Either<ESArtifactData, CassandraOperationStatus> artifactResponse = artifactCassandraDao.getArtifact(cassandraId);
783 if (artifactResponse.isRight()) {
784 log.debug("Failed to fetch artifact from Cassandra by id {} error {} ", cassandraId, artifactResponse.right().value());
786 StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactResponse.right().value());
787 ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(storageStatus);
788 return Either.right(convertedFromStorageResponse);
790 ESArtifactData artifactData = artifactResponse.left().value();
791 return Either.left(artifactData.getDataAsArray());
794 private String createCsarBlock0(String metaFileVersion, String toscaConformanceLevel) {
795 final String BLOCK_0_TEMPLATE =
796 "SDC-TOSCA-Meta-File-Version: %s\nSDC-TOSCA-Definitions-Version: %s\n";
797 String readyBlock = String.format(BLOCK_0_TEMPLATE, metaFileVersion, toscaConformanceLevel);
801 private String createToscaBlock0(String metaFileVersion, String csarVersion, String createdBy, String entryDef) {
802 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";
803 return String.format(block0template, metaFileVersion, csarVersion, createdBy, entryDef);
806 private Either<List<Artifact>, String> artifactGenerator(List<Artifact> artifactList, ArtifactType type, Component component) {
808 ArtifactGenerationServiceImpl artifactGenerationServiceImpl = new ArtifactGenerationServiceImpl();
809 ArtifactTypes artifactTypes = new ArtifactTypes();
810 List<ArtifactType> artifactTypesList = new LinkedList<>();
811 ArtifactType otherType;
814 otherType = ArtifactType.OTHER;
819 artifactTypesList.add(otherType);
820 artifactTypes.setArtifactTypes(artifactTypesList);
822 String configJson = gson.toJson(artifactTypes);
823 Map<String, String> additionalParams = new HashMap<>();
826 if (UUID_NORMATIVE_NEW_VERSION.matcher(component.getVersion()).matches() ) {
827 version = component.getVersion();
829 String[] versionParts = component.getVersion().split(ToscaElementLifecycleOperation.VERSION_DELIMETER_REGEXP);
830 Integer majorVersion = Integer.parseInt(versionParts[0]);
832 version = (majorVersion + 1) + ToscaElementLifecycleOperation.VERSION_DELIMETER + "0";
835 additionalParams.put(AdditionalParams.ServiceVersion.getName(), version);
836 GenerationData generatedArtifacts = artifactGenerationServiceImpl.generateArtifact(artifactList, configJson, additionalParams);
838 Map<String, List<String>> errorData = generatedArtifacts.getErrorData();
840 if (!errorData.isEmpty()) {
841 Set<String> keySet = errorData.keySet();
842 StringBuilder error = new StringBuilder();
844 for (String key : keySet) {
845 List<String> errorList = errorData.get(key);
846 log.debug("The Artifact Generator Failed - {} with following: {}", key, errorList);
847 error.append(key + errorList);
850 return Either.right(error.toString());
853 return Either.left(generatedArtifacts.getResultData());
857 * Extracts artifacts of VFCs from CSAR
860 * @return Map of <String, List<ArtifactDefinition>> the contains Lists of artifacts according vfcToscaNamespace
862 public static Map<String, List<ArtifactDefinition>> extractVfcsArtifactsFromCsar(Map<String, byte[]> csar) {
864 Map<String, List<ArtifactDefinition>> artifacts = new HashMap<>();
866 log.debug("************* Going to extract VFCs artifacts from Csar. ");
867 Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
868 csar.entrySet().stream()
869 // filter CSAR entry by node type artifact path
870 .filter(e -> Pattern.compile(VFC_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey()).matches())
871 // extract ArtifactDefinition from CSAR entry for each entry with matching artifact path
872 .forEach(e -> addExtractedVfcArtifact(extractVfcArtifact(e, collectedWarningMessages), artifacts));
873 // add counter suffix to artifact labels
874 handleWarningMessages(collectedWarningMessages);
881 * Print warnings to log
883 * @param collectedWarningMessages
885 public static void handleWarningMessages(Map<String, Set<List<String>>> collectedWarningMessages) {
886 collectedWarningMessages.entrySet().stream()
888 .forEach(e -> e.getValue().stream()
889 // add each warning message to log
890 .forEach(args -> log.warn(e.getKey(), args.toArray())));
894 private static void addExtractedVfcArtifact(ImmutablePair<String, ArtifactDefinition> extractedVfcArtifact, Map<String, List<ArtifactDefinition>> artifacts) {
895 if (extractedVfcArtifact != null) {
896 List<ArtifactDefinition> currArtifactsList;
897 String vfcToscaNamespace = extractedVfcArtifact.getKey();
898 if (artifacts.containsKey(vfcToscaNamespace)) {
899 currArtifactsList = artifacts.get(vfcToscaNamespace);
901 currArtifactsList = new ArrayList<>();
902 artifacts.put(vfcToscaNamespace, currArtifactsList);
904 currArtifactsList.add(extractedVfcArtifact.getValue());
908 private static ImmutablePair<String, ArtifactDefinition> extractVfcArtifact(Entry<String, byte[]> entry, Map<String, Set<List<String>>> collectedWarningMessages) {
909 ArtifactDefinition artifact;
910 String[] parsedCsarArtifactPath = entry.getKey().split("/");
911 Either<ArtifactGroupTypeEnum, Boolean> eitherArtifactGroupType = detectArtifactGroupType(parsedCsarArtifactPath[2].toUpperCase(), collectedWarningMessages);
912 if (eitherArtifactGroupType.isLeft()) {
913 artifact = buildArtifactDefinitionFromCsarArtifactPath(entry, collectedWarningMessages, parsedCsarArtifactPath, eitherArtifactGroupType.left().value());
917 return new ImmutablePair<>(parsedCsarArtifactPath[1], artifact);
920 private static Either<ArtifactGroupTypeEnum, Boolean> detectArtifactGroupType(String groupType, Map<String, Set<List<String>>> collectedWarningMessages) {
921 Either<ArtifactGroupTypeEnum, Boolean> result;
923 ArtifactGroupTypeEnum artifactGroupType = ArtifactGroupTypeEnum.findType(groupType.toUpperCase());
924 if (artifactGroupType == null || (artifactGroupType != ArtifactGroupTypeEnum.INFORMATIONAL && artifactGroupType != ArtifactGroupTypeEnum.DEPLOYMENT)) {
925 String warningMessage = "Warning - unrecognized artifact group type {} was received.";
926 List<String> messageArguments = new ArrayList<>();
927 messageArguments.add(groupType);
928 if (!collectedWarningMessages.containsKey(warningMessage)) {
929 Set<List<String>> messageArgumentLists = new HashSet<>();
930 messageArgumentLists.add(messageArguments);
931 collectedWarningMessages.put(warningMessage, messageArgumentLists);
933 collectedWarningMessages.get(warningMessage).add(messageArguments);
936 result = Either.right(false);
939 result = Either.left(artifactGroupType);
941 } catch (Exception e) {
942 log.debug("detectArtifactGroupType failed with exception", e);
943 result = Either.right(false);
948 private static ArtifactDefinition buildArtifactDefinitionFromCsarArtifactPath(Entry<String, byte[]> entry, Map<String, Set<List<String>>> collectedWarningMessages, String[] parsedCsarArtifactPath, ArtifactGroupTypeEnum artifactGroupType) {
949 ArtifactDefinition artifact;
950 artifact = new ArtifactDefinition();
951 artifact.setArtifactGroupType(artifactGroupType);
952 artifact.setArtifactType(detectArtifactTypeVFC(artifactGroupType, parsedCsarArtifactPath[3], parsedCsarArtifactPath[1], collectedWarningMessages));
953 artifact.setArtifactName(ValidationUtils.normalizeFileName(parsedCsarArtifactPath[parsedCsarArtifactPath.length - 1]));
954 artifact.setPayloadData(Base64.encodeBase64String(entry.getValue()));
955 artifact.setArtifactDisplayName(artifact.getArtifactName().lastIndexOf('.') > 0 ? artifact.getArtifactName().substring(0, artifact.getArtifactName().lastIndexOf('.')) : artifact.getArtifactName());
956 artifact.setArtifactLabel(ValidationUtils.normalizeArtifactLabel(artifact.getArtifactName()));
957 artifact.setDescription(ARTIFACT_CREATED_FROM_CSAR);
958 artifact.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(entry.getValue()));
962 public static final class NonMetaArtifactInfo {
963 private final String path;
964 private final String artifactName;
965 private final String displayName;
966 private final String artifactLabel;
967 private final ArtifactTypeEnum artifactType;
968 private final ArtifactGroupTypeEnum artifactGroupType;
969 private String payloadData;
970 private String artifactChecksum;
971 private String artifactUniqueId;
973 public NonMetaArtifactInfo(String artifactName, String path, ArtifactTypeEnum artifactType, ArtifactGroupTypeEnum artifactGroupType, byte[] payloadData, String artifactUniqueId) {
976 this.artifactName = ValidationUtils.normalizeFileName(artifactName);
977 this.artifactType = artifactType;
978 this.artifactGroupType = artifactGroupType;
979 final int pointIndex = artifactName.lastIndexOf('.');
980 if (pointIndex > 0) {
981 displayName = artifactName.substring(0, pointIndex);
983 displayName = artifactName;
985 this.artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactName);
986 if (payloadData != null) {
987 this.payloadData = Base64.encodeBase64String(payloadData);
988 this.artifactChecksum = GeneralUtility.calculateMD5Base64EncodedByByteArray(payloadData);
990 this.artifactUniqueId = artifactUniqueId;
993 public String getPath() {
997 public String getArtifactName() {
1001 public ArtifactTypeEnum getArtifactType() {
1002 return artifactType;
1005 public String getDisplayName() {
1009 public ArtifactGroupTypeEnum getArtifactGroupType() {
1010 return artifactGroupType;
1013 public String getArtifactLabel() {
1014 return artifactLabel;
1017 public String getPayloadData() {
1021 public String getArtifactChecksum() {
1022 return artifactChecksum;
1025 public String getArtifactUniqueId() {
1026 return artifactUniqueId;
1029 public void setArtifactUniqueId(String artifactUniqueId) {
1030 this.artifactUniqueId = artifactUniqueId;
1036 * This method checks the artifact GroupType & Artifact Type. <br>
1037 * if there is any problem warning messages are added to collectedWarningMessages
1039 * @param artifactPath
1040 * @param collectedWarningMessages
1043 public static Either<NonMetaArtifactInfo, Boolean> validateNonMetaArtifact(String artifactPath, byte[] payloadData, Map<String, Set<List<String>>> collectedWarningMessages) {
1044 Either<NonMetaArtifactInfo, Boolean> ret;
1046 String[] parsedArtifactPath = artifactPath.split("/");
1047 // Validate Artifact Group Type
1048 Either<ArtifactGroupTypeEnum, Boolean> eitherGroupType = detectArtifactGroupType(parsedArtifactPath[1], collectedWarningMessages);
1049 if (eitherGroupType.isLeft()) {
1050 final ArtifactGroupTypeEnum groupTypeEnum = eitherGroupType.left().value();
1052 // Validate Artifact Type
1053 String artifactType = parsedArtifactPath[2];
1054 artifactType = detectArtifactTypeVF(groupTypeEnum, artifactType, collectedWarningMessages);
1056 String artifactFileNameType = parsedArtifactPath[3];
1057 ret = Either.left(new NonMetaArtifactInfo(artifactFileNameType, artifactPath, ArtifactTypeEnum.findType(artifactType), groupTypeEnum, payloadData, null));
1060 ret = Either.right(eitherGroupType.right().value());
1062 } catch (Exception e) {
1063 log.debug("detectArtifactGroupType failed with exception", e);
1064 ret = Either.right(false);
1070 private static String detectArtifactTypeVFC(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, String parentVfName, Map<String, Set<List<String>>> collectedWarningMessages) {
1071 String warningMessage = "Warning - artifact type {} that was provided for VFC {} is not recognized.";
1072 return detectArtifactType(artifactGroupType, receivedTypeName, warningMessage, collectedWarningMessages, parentVfName);
1075 private static String detectArtifactTypeVF(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, Map<String, Set<List<String>>> collectedWarningMessages) {
1076 String warningMessage = "Warning - artifact type {} that was provided for VF is not recognized.";
1077 return detectArtifactType(artifactGroupType, receivedTypeName, warningMessage, collectedWarningMessages);
1080 private static String detectArtifactType(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, String warningMessage, Map<String, Set<List<String>>> collectedWarningMessages, String... arguments) {
1082 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(receivedTypeName);
1083 Map<String, ArtifactTypeConfig> resourceValidTypeArtifacts = null;
1085 if(artifactGroupType != null){
1086 switch (artifactGroupType) {
1088 resourceValidTypeArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration()
1089 .getResourceInformationalArtifacts();
1092 resourceValidTypeArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration()
1093 .getResourceDeploymentArtifacts();
1100 Set<String> validArtifactTypes = null;
1101 if(resourceValidTypeArtifacts != null){
1102 validArtifactTypes = resourceValidTypeArtifacts.keySet();
1105 if (validArtifactTypes == null || artifactType == null || !validArtifactTypes.contains(artifactType.getType())) {
1106 List<String> messageArguments = new ArrayList<>();
1107 messageArguments.add(receivedTypeName);
1108 messageArguments.addAll(Arrays.asList(arguments));
1109 if (!collectedWarningMessages.containsKey(warningMessage)) {
1110 Set<List<String>> messageArgumentLists = new HashSet<>();
1111 messageArgumentLists.add(messageArguments);
1112 collectedWarningMessages.put(warningMessage, messageArgumentLists);
1114 collectedWarningMessages.get(warningMessage).add(messageArguments);
1118 return artifactType == null ? ArtifactTypeEnum.OTHER.getType() : artifactType.getType();
1121 private Either<ZipOutputStream, ResponseFormat> writeAllFilesToScar(Component mainComponent, CsarDefinition csarDefinition, ZipOutputStream zipstream, boolean isInCertificationRequest) throws IOException{
1122 ComponentArtifacts componentArtifacts = csarDefinition.getComponentArtifacts();
1124 Either<ZipOutputStream, ResponseFormat> writeComponentArtifactsToSpecifiedtPath = writeComponentArtifactsToSpecifiedtPath(mainComponent, componentArtifacts, zipstream, ARTIFACTS_PATH, isInCertificationRequest);
1126 if(writeComponentArtifactsToSpecifiedtPath.isRight()){
1127 return Either.right(writeComponentArtifactsToSpecifiedtPath.right().value());
1130 ComponentTypeArtifacts mainTypeAndCIArtifacts = componentArtifacts.getMainTypeAndCIArtifacts();
1131 writeComponentArtifactsToSpecifiedtPath = writeArtifactsInfoToSpecifiedtPath(mainComponent, mainTypeAndCIArtifacts.getComponentArtifacts(), zipstream, ARTIFACTS_PATH, isInCertificationRequest);
1133 if(writeComponentArtifactsToSpecifiedtPath.isRight()){
1134 return Either.right(writeComponentArtifactsToSpecifiedtPath.right().value());
1137 Map<String, ArtifactsInfo> componentInstancesArtifacts = mainTypeAndCIArtifacts.getComponentInstancesArtifacts();
1138 Set<String> keySet = componentInstancesArtifacts.keySet();
1140 String currentPath = ARTIFACTS_PATH + RESOURCES_PATH;
1141 for (String keyAssetName : keySet) {
1142 ArtifactsInfo artifactsInfo = componentInstancesArtifacts.get(keyAssetName);
1143 String pathWithAssetName = currentPath + keyAssetName + "/";
1144 writeComponentArtifactsToSpecifiedtPath = writeArtifactsInfoToSpecifiedtPath(mainComponent, artifactsInfo, zipstream, pathWithAssetName, isInCertificationRequest);
1146 if(writeComponentArtifactsToSpecifiedtPath.isRight()){
1147 return Either.right(writeComponentArtifactsToSpecifiedtPath.right().value());
1151 return Either.left(zipstream);
1154 private Either<ZipOutputStream, ResponseFormat> writeComponentArtifactsToSpecifiedtPath(Component mainComponent, ComponentArtifacts componentArtifacts, ZipOutputStream zipstream,
1155 String currentPath, boolean isInCertificationRequest) throws IOException {
1156 Map<String, ComponentTypeArtifacts> componentTypeArtifacts = componentArtifacts.getComponentTypeArtifacts();
1158 //<Inner Asset TOSCA name (e.g. VFC name)> folder name: <Inner Asset TOSCA name (e.g. VFC name)>_v<version>.
1159 //E.g. "org.openecomp.resource.vf.vipr_atm_v1.0"
1160 Set<String> componentTypeArtifactsKeys = componentTypeArtifacts.keySet();
1161 for (String keyAssetName : componentTypeArtifactsKeys) {
1162 ComponentTypeArtifacts componentInstanceArtifacts = componentTypeArtifacts.get(keyAssetName);
1163 ArtifactsInfo componentArtifacts2 = componentInstanceArtifacts.getComponentArtifacts();
1164 String pathWithAssetName = currentPath + keyAssetName + "/";
1165 Either<ZipOutputStream, ResponseFormat> writeArtifactsInfoToSpecifiedtPath = writeArtifactsInfoToSpecifiedtPath(mainComponent, componentArtifacts2, zipstream, pathWithAssetName, isInCertificationRequest);
1167 if(writeArtifactsInfoToSpecifiedtPath.isRight()){
1168 return writeArtifactsInfoToSpecifiedtPath;
1172 return Either.left(zipstream);
1175 private Either<ZipOutputStream, ResponseFormat> writeArtifactsInfoToSpecifiedtPath(Component mainComponent, ArtifactsInfo currArtifactsInfo, ZipOutputStream zip, String path, boolean isInCertificationRequest) throws IOException {
1176 Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> artifactsInfo = currArtifactsInfo
1177 .getArtifactsInfo();
1178 Set<ArtifactGroupTypeEnum> groupTypeEnumKeySet = artifactsInfo.keySet();
1180 for (ArtifactGroupTypeEnum artifactGroupTypeEnum : groupTypeEnumKeySet) {
1181 String groupTypeFolder = path + WordUtils.capitalizeFully(artifactGroupTypeEnum.getType()) + "/";
1183 Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactTypesMap = artifactsInfo.get(artifactGroupTypeEnum);
1184 Set<ArtifactTypeEnum> artifactTypeEnumKeySet = artifactTypesMap.keySet();
1186 for (ArtifactTypeEnum artifactTypeEnum : artifactTypeEnumKeySet) {
1187 List<ArtifactDefinition> artifactDefinitionList = artifactTypesMap.get(artifactTypeEnum);
1188 String artifactTypeFolder = groupTypeFolder + artifactTypeEnum.toString() + "/";
1190 Either<ZipOutputStream, ResponseFormat> writeArtifactDefinition = writeArtifactDefinition(mainComponent, zip, artifactDefinitionList, artifactTypeFolder, isInCertificationRequest);
1192 if(writeArtifactDefinition.isRight()){
1193 return writeArtifactDefinition;
1198 return Either.left(zip);
1201 private Either<ZipOutputStream, ResponseFormat> writeArtifactDefinition(Component mainComponent, ZipOutputStream zip, List<ArtifactDefinition> artifactDefinitionList,
1202 String artifactPathAndFolder, boolean isInCertificationRequest) throws IOException {
1204 ComponentTypeEnum componentType = mainComponent.getComponentType();
1205 String heatEnvType = ArtifactTypeEnum.HEAT_ENV.getType();
1207 for (ArtifactDefinition artifactDefinition : artifactDefinitionList) {
1208 if (!isInCertificationRequest && componentType == ComponentTypeEnum.SERVICE
1209 && artifactDefinition.getArtifactType().equals(heatEnvType) ||
1210 //this is placeholder
1211 (artifactDefinition.getEsId() == null && artifactDefinition.getMandatory())){
1215 byte[] payloadData = artifactDefinition.getPayloadData();
1216 String artifactFileName = artifactDefinition.getArtifactName();
1218 if (payloadData == null) {
1219 Either<byte[], ActionStatus> fromCassandra = getFromCassandra(artifactDefinition.getEsId());
1221 if (fromCassandra.isRight()) {
1222 log.debug("ArtifactName {}, unique ID {}", artifactDefinition.getArtifactName(), artifactDefinition.getUniqueId());
1223 log.debug("Failed to get {} payload from DB reason: {}", artifactFileName, fromCassandra.right().value());
1226 payloadData = fromCassandra.left().value();
1228 zip.putNextEntry(new ZipEntry(artifactPathAndFolder + artifactFileName));
1229 zip.write(payloadData);
1232 return Either.left(zip);
1235 /************************************ Artifacts Structure ******************************************************************/
1237 * The artifacts Definition saved by their structure
1239 private class ArtifactsInfo {
1240 //Key is the type of artifacts(Informational/Deployment)
1241 //Value is a map between an artifact type and a list of all artifacts of this type
1242 private Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> artifactsInfoField;
1244 public ArtifactsInfo() {
1245 this.artifactsInfoField = new EnumMap<>(ArtifactGroupTypeEnum.class);
1248 public Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> getArtifactsInfo() {
1249 return artifactsInfoField;
1252 public List<ArtifactDefinition> getFlatArtifactsListByType(ArtifactTypeEnum artifactType){
1253 List<ArtifactDefinition> artifacts = new ArrayList<>();
1254 for (List<ArtifactDefinition> artifactsByType:artifactsInfoField.get(artifactType).values()){
1255 artifacts.addAll(artifactsByType);
1260 public void addArtifactsToGroup(ArtifactGroupTypeEnum artifactGroup,Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactsDefinition){
1261 artifactsInfoField.put(artifactGroup, artifactsDefinition);
1264 public boolean isEmpty() {
1265 return artifactsInfoField.isEmpty();
1271 * The artifacts of the component and of all its composed instances
1274 private class ComponentTypeArtifacts {
1275 private ArtifactsInfo componentArtifacts; //component artifacts (describes the Informational Deployment folders)
1276 private Map<String, ArtifactsInfo> componentInstancesArtifacts; //artifacts of the composed instances mapped by the resourceInstance normalized name (describes the Resources folder)
1278 public ComponentTypeArtifacts() {
1279 componentArtifacts = new ArtifactsInfo();
1280 componentInstancesArtifacts = new HashMap<>();
1283 public ArtifactsInfo getComponentArtifacts() {
1284 return componentArtifacts;
1286 public void setComponentArtifacts(ArtifactsInfo artifactsInfo) {
1287 this.componentArtifacts = artifactsInfo;
1289 public Map<String, ArtifactsInfo> getComponentInstancesArtifacts() {
1290 return componentInstancesArtifacts;
1292 public void setComponentInstancesArtifacts(Map<String, ArtifactsInfo> componentInstancesArtifacts) {
1293 this.componentInstancesArtifacts = componentInstancesArtifacts;
1296 public void addComponentInstancesArtifacts(String normalizedName, ArtifactsInfo artifactsInfo) {
1297 componentInstancesArtifacts.put(normalizedName, artifactsInfo);
1302 private class ComponentArtifacts {
1303 //artifacts of the component and CI's artifacts contained in it's composition (represents Informational, Deployment & Resource folders of main component)
1304 private ComponentTypeArtifacts mainTypeAndCIArtifacts;
1305 //artifacts of all component types mapped by their tosca name
1306 private Map<String, ComponentTypeArtifacts> componentTypeArtifacts;
1308 public ComponentArtifacts(){
1309 mainTypeAndCIArtifacts = new ComponentTypeArtifacts();
1310 componentTypeArtifacts = new HashMap<>();
1313 public ComponentTypeArtifacts getMainTypeAndCIArtifacts() {
1314 return mainTypeAndCIArtifacts;
1317 public void setMainTypeAndCIArtifacts(ComponentTypeArtifacts componentInstanceArtifacts) {
1318 this.mainTypeAndCIArtifacts = componentInstanceArtifacts;
1321 public Map<String, ComponentTypeArtifacts> getComponentTypeArtifacts() {
1322 return componentTypeArtifacts;
1325 public void setComponentTypeArtifacts(Map<String, ComponentTypeArtifacts> componentTypeArtifacts) {
1326 this.componentTypeArtifacts = componentTypeArtifacts;
1330 private class CsarDefinition {
1331 private ComponentArtifacts componentArtifacts;
1333 // add list of tosca artifacts and meta describes CSAR zip root
1335 public CsarDefinition(ComponentArtifacts componentArtifacts) {
1336 this.componentArtifacts = componentArtifacts;
1339 public ComponentArtifacts getComponentArtifacts() {
1340 return componentArtifacts;
1344 /************************************ Artifacts Structure END******************************************************************/
1346 private Either<CsarDefinition,ResponseFormat> collectComponentCsarDefinition(Component component){
1347 ComponentArtifacts componentArtifacts = new ComponentArtifacts();
1348 Component updatedComponent = component;
1350 //get service to receive the AII artifacts uploaded to the service
1351 if (updatedComponent.getComponentType() == ComponentTypeEnum.SERVICE) {
1352 Either<Service, StorageOperationStatus> getServiceResponse = toscaOperationFacade.getToscaElement(updatedComponent.getUniqueId());
1354 if(getServiceResponse.isRight()){
1355 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getServiceResponse.right().value());
1356 return Either.right(componentsUtils.getResponseFormat(actionStatus));
1359 updatedComponent = getServiceResponse.left().value();
1362 //find the artifacts of the main component, it would have its composed instances artifacts in a separate folder
1363 ComponentTypeArtifacts componentInstanceArtifacts = new ComponentTypeArtifacts();
1364 ArtifactsInfo artifactsInfo = collectComponentArtifacts(updatedComponent);
1365 componentInstanceArtifacts.setComponentArtifacts(artifactsInfo);
1366 componentArtifacts.setMainTypeAndCIArtifacts(componentInstanceArtifacts);
1368 Map<String,ComponentTypeArtifacts> resourceTypeArtifacts = componentArtifacts.getComponentTypeArtifacts(); //artifacts mapped by the component type(tosca name+version)
1369 //get the component instances
1370 List<ComponentInstance> componentInstances = updatedComponent.getComponentInstances();
1371 if (componentInstances!=null){
1372 for (ComponentInstance componentInstance:componentInstances){
1373 //call recursive to find artifacts for all the path
1374 Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts = collectComponentInstanceArtifacts(
1375 updatedComponent, componentInstance, resourceTypeArtifacts, componentInstanceArtifacts);
1376 if (collectComponentInstanceArtifacts.isRight()){
1377 return Either.right(collectComponentInstanceArtifacts.right().value());
1382 if(log.isDebugEnabled()){
1383 printResult(componentArtifacts,updatedComponent.getName());
1386 return Either.left(new CsarDefinition(componentArtifacts));
1389 private void printResult(ComponentArtifacts componentArtifacts, String name) {
1390 StringBuilder result = new StringBuilder();
1391 result.append("Artifacts of main component " + name + "\n");
1392 ComponentTypeArtifacts componentInstanceArtifacts = componentArtifacts.getMainTypeAndCIArtifacts();
1393 printArtifacts(componentInstanceArtifacts);
1394 result.append("Type Artifacts\n");
1395 for (Map.Entry<String, ComponentTypeArtifacts> typeArtifacts:componentArtifacts.getComponentTypeArtifacts().entrySet()){
1396 result.append("Folder " + typeArtifacts.getKey() + "\n");
1397 result.append(printArtifacts(typeArtifacts.getValue()));
1400 if(log.isDebugEnabled()){
1401 log.debug(result.toString());
1405 private String printArtifacts(ComponentTypeArtifacts componentInstanceArtifacts) {
1406 StringBuilder result = new StringBuilder();
1407 ArtifactsInfo artifactsInfo = componentInstanceArtifacts.getComponentArtifacts();
1408 Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> componetArtifacts = artifactsInfo.getArtifactsInfo();
1409 printArtifacts(componetArtifacts);
1410 result = result.append("Resources\n");
1411 for (Map.Entry<String, ArtifactsInfo> resourceInstance:componentInstanceArtifacts.getComponentInstancesArtifacts().entrySet()){
1412 result.append("Folder" + resourceInstance.getKey() + "\n");
1413 result.append(printArtifacts(resourceInstance.getValue().getArtifactsInfo()));
1416 return result.toString();
1419 private String printArtifacts(Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> componetArtifacts) {
1420 StringBuilder result = new StringBuilder();
1421 for (Map.Entry<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> artifactGroup:componetArtifacts.entrySet()){
1422 result.append(" " + artifactGroup.getKey().getType());
1423 for (Map.Entry<ArtifactTypeEnum, List<ArtifactDefinition>> groupArtifacts:artifactGroup.getValue().entrySet()){
1424 result.append(" " + groupArtifacts.getKey().getType());
1425 for (ArtifactDefinition artifact:groupArtifacts.getValue()){
1426 result.append(" " + artifact.getArtifactDisplayName());
1431 return result.toString();
1434 private ComponentTypeArtifacts collectComponentTypeArtifacts(Map<String, ComponentTypeArtifacts> resourcesArtifacts, ComponentInstance componentInstance,
1435 Resource fetchedComponent) {
1436 String toscaComponentName = componentInstance.getToscaComponentName() + "_v" + componentInstance.getComponentVersion();
1438 ComponentTypeArtifacts componentArtifactsInfo = resourcesArtifacts.get(toscaComponentName);
1439 //if there are no artifacts for this component type we need to fetch and build them
1440 if (componentArtifactsInfo==null){
1441 ArtifactsInfo componentArtifacts = collectComponentArtifacts(fetchedComponent);
1442 componentArtifactsInfo = new ComponentTypeArtifacts();
1443 if (!componentArtifacts.isEmpty()){
1444 componentArtifactsInfo.setComponentArtifacts(componentArtifacts);
1445 resourcesArtifacts.put(toscaComponentName, componentArtifactsInfo);
1448 return componentArtifactsInfo;
1451 private Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts(Component parentComponent,ComponentInstance componentInstance,
1452 Map<String, ComponentTypeArtifacts> resourcesTypeArtifacts,ComponentTypeArtifacts instanceArtifactsLocation) {
1453 //1. get the component instance component
1454 String componentUid = componentInstance.getComponentUid();
1455 Either<Resource, StorageOperationStatus> resource = toscaOperationFacade.getToscaElement(componentUid);
1456 if (resource.isRight()) {
1457 log.error("Failed to fetch resource with id {} for instance {}",componentUid, parentComponent.getUUID());
1458 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ASSET_NOT_FOUND_DURING_CSAR_CREATION,
1459 parentComponent.getComponentType().getValue(), parentComponent.getUUID(),
1460 componentInstance.getOriginType().getComponentType().getValue(), componentUid));
1462 Resource fetchedComponent = resource.left().value();
1464 //2. fill the artifacts for the current component parent type
1465 ComponentTypeArtifacts componentParentArtifacts = collectComponentTypeArtifacts(resourcesTypeArtifacts, componentInstance, fetchedComponent);
1467 //3. find the artifacts specific to the instance
1468 Map<ArtifactTypeEnum, List<ArtifactDefinition>> componentInstanceSpecificInformationalArtifacts =
1469 getComponentInstanceSpecificArtifacts(componentInstance.getArtifacts(),
1470 componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), ArtifactGroupTypeEnum.INFORMATIONAL);
1471 Map<ArtifactTypeEnum, List<ArtifactDefinition>> componentInstanceSpecificDeploymentArtifacts =
1472 getComponentInstanceSpecificArtifacts(componentInstance.getDeploymentArtifacts(),
1473 componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), ArtifactGroupTypeEnum.DEPLOYMENT);
1475 //4. add the instances artifacts to the component type
1476 ArtifactsInfo artifactsInfo = new ArtifactsInfo();
1477 if (!componentInstanceSpecificInformationalArtifacts.isEmpty()){
1478 artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.INFORMATIONAL, componentInstanceSpecificInformationalArtifacts);
1480 if (!componentInstanceSpecificDeploymentArtifacts.isEmpty()){
1481 artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, componentInstanceSpecificDeploymentArtifacts);
1483 if (!artifactsInfo.isEmpty()){
1484 instanceArtifactsLocation.addComponentInstancesArtifacts(componentInstance.getNormalizedName(), artifactsInfo);
1487 //5. do the same for all the component instances
1488 List<ComponentInstance> componentInstances = fetchedComponent.getComponentInstances();
1489 if (componentInstances!=null){
1490 for (ComponentInstance childComponentInstance:componentInstances){
1491 Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts = collectComponentInstanceArtifacts(
1492 fetchedComponent, childComponentInstance, resourcesTypeArtifacts, componentParentArtifacts);
1493 if (collectComponentInstanceArtifacts.isRight()){
1494 return collectComponentInstanceArtifacts;
1499 return Either.left(true);
1502 private Map<ArtifactTypeEnum, List<ArtifactDefinition>> getComponentInstanceSpecificArtifacts(Map<String, ArtifactDefinition> componentArtifacts,
1503 Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> componentTypeArtifacts, ArtifactGroupTypeEnum artifactGroupTypeEnum) {
1504 Map<ArtifactTypeEnum, List<ArtifactDefinition>> parentArtifacts = componentTypeArtifacts.get(artifactGroupTypeEnum); //the artfiacts of the component itself and not the instance
1506 Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactsByTypeOfComponentInstance = new EnumMap<>(ArtifactTypeEnum.class);
1507 if (componentArtifacts!=null){
1508 for (ArtifactDefinition artifact:componentArtifacts.values()){
1509 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifact.getArtifactType());
1510 List<ArtifactDefinition> parentArtifactsByType = null;
1511 if (parentArtifacts!=null){
1512 parentArtifactsByType = parentArtifacts.get(artifactType);
1514 //the artifact is of instance
1515 if (parentArtifactsByType == null || !parentArtifactsByType.contains(artifact)){
1516 List<ArtifactDefinition> typeArtifacts = artifactsByTypeOfComponentInstance.get(artifactType);
1517 if (typeArtifacts == null){
1518 typeArtifacts = new ArrayList<>();
1519 artifactsByTypeOfComponentInstance.put(artifactType, typeArtifacts);
1521 typeArtifacts.add(artifact);
1526 return artifactsByTypeOfComponentInstance;
1529 private ArtifactsInfo collectComponentArtifacts(Component component) {
1530 Map<String, ArtifactDefinition> informationalArtifacts = component.getArtifacts();
1531 Map<ArtifactTypeEnum, List<ArtifactDefinition>> informationalArtifactsByType = collectGroupArtifacts(informationalArtifacts);
1532 Map<String, ArtifactDefinition> deploymentArtifacts = component.getDeploymentArtifacts();
1533 Map<ArtifactTypeEnum, List<ArtifactDefinition>> deploymentArtifactsByType = collectGroupArtifacts(deploymentArtifacts);
1534 ArtifactsInfo artifactsInfo = new ArtifactsInfo();
1535 if (!informationalArtifactsByType.isEmpty()){
1536 artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.INFORMATIONAL, informationalArtifactsByType);
1538 if (!deploymentArtifactsByType.isEmpty() ){
1539 artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, deploymentArtifactsByType);
1542 return artifactsInfo;
1545 private Map<ArtifactTypeEnum, List<ArtifactDefinition>> collectGroupArtifacts(Map<String, ArtifactDefinition> componentArtifacts) {
1546 Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactsByType = new EnumMap<>(ArtifactTypeEnum.class);
1547 for (ArtifactDefinition artifact:componentArtifacts.values()){
1548 if (artifact.getArtifactUUID()!=null){
1549 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifact.getArtifactType());
1550 List<ArtifactDefinition> typeArtifacts = artifactsByType.get(artifactType);
1551 if (typeArtifacts==null){
1552 typeArtifacts = new ArrayList<>();
1553 artifactsByType.put(artifactType, typeArtifacts);
1555 typeArtifacts.add(artifact);
1558 return artifactsByType;