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;
26 import java.io.IOException;
27 import java.util.ArrayList;
28 import java.util.Arrays;
29 import java.util.EnumMap;
30 import java.util.HashMap;
31 import java.util.HashSet;
32 import java.util.LinkedList;
33 import java.util.List;
35 import java.util.Map.Entry;
36 import java.util.Objects;
38 import java.util.regex.Matcher;
39 import java.util.regex.Pattern;
40 import java.util.stream.Collectors;
41 import java.util.zip.ZipEntry;
42 import java.util.zip.ZipInputStream;
43 import java.util.zip.ZipOutputStream;
45 import org.apache.commons.codec.binary.Base64;
46 import org.apache.commons.codec.digest.DigestUtils;
47 import org.apache.commons.io.output.ByteArrayOutputStream;
48 import org.apache.commons.lang.WordUtils;
49 import org.apache.commons.lang3.tuple.ImmutablePair;
50 import org.apache.commons.lang3.tuple.ImmutableTriple;
51 import org.apache.commons.lang3.tuple.Triple;
52 import org.onap.sdc.generator.data.AdditionalParams;
53 import org.onap.sdc.generator.data.Artifact;
54 import org.onap.sdc.generator.data.ArtifactType;
55 import org.onap.sdc.generator.data.GenerationData;
56 import org.onap.sdc.generator.impl.ArtifactGenerationServiceImpl;
57 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
58 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum;
59 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationInfo;
60 import org.openecomp.sdc.be.components.impl.ImportUtils;
61 import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
62 import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig;
63 import org.openecomp.sdc.be.config.ConfigurationManager;
64 import org.openecomp.sdc.be.dao.api.ActionStatus;
65 import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao;
66 import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
67 import org.openecomp.sdc.be.dao.cassandra.SdcSchemaFilesCassandraDao;
68 import org.openecomp.sdc.be.datatypes.elements.OperationDataDefinition;
69 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
70 import org.openecomp.sdc.be.impl.ComponentsUtils;
71 import org.openecomp.sdc.be.model.ArtifactDefinition;
72 import org.openecomp.sdc.be.model.Component;
73 import org.openecomp.sdc.be.model.ComponentInstance;
74 import org.openecomp.sdc.be.model.InterfaceDefinition;
75 import org.openecomp.sdc.be.model.LifecycleStateEnum;
76 import org.openecomp.sdc.be.model.Operation;
77 import org.openecomp.sdc.be.model.Resource;
78 import org.openecomp.sdc.be.model.Service;
79 import org.openecomp.sdc.be.model.User;
80 import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOperation;
81 import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
82 import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
83 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
84 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
85 import org.openecomp.sdc.be.resources.data.ESArtifactData;
86 import org.openecomp.sdc.be.resources.data.SdcSchemaFilesData;
87 import org.openecomp.sdc.be.tosca.model.ToscaTemplate;
88 import org.openecomp.sdc.be.tosca.utils.OperationArtifactUtil;
89 import org.openecomp.sdc.be.utils.CommonBeUtils;
90 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
91 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
92 import org.openecomp.sdc.common.impl.ExternalConfiguration;
93 import org.openecomp.sdc.common.util.GeneralUtility;
94 import org.openecomp.sdc.common.util.ValidationUtils;
95 import org.openecomp.sdc.exception.ResponseFormat;
96 import org.slf4j.Logger;
97 import org.slf4j.LoggerFactory;
98 import org.springframework.beans.factory.annotation.Autowired;
100 import com.google.gson.Gson;
102 import fj.data.Either;
109 @org.springframework.stereotype.Component("csar-utils")
110 public class CsarUtils {
112 private static final Logger log = LoggerFactory.getLogger(CsarUtils.class);
115 private SdcSchemaFilesCassandraDao sdcSchemaFilesCassandraDao;
117 private ArtifactCassandraDao artifactCassandraDao;
119 private ComponentsUtils componentsUtils;
121 private ToscaExportHandler toscaExportUtils;
123 private ArtifactsBusinessLogic artifactsBusinessLogic;
125 protected ToscaOperationFacade toscaOperationFacade;
128 @javax.annotation.Resource
129 private ServiceBusinessLogic serviceBusinessLogic;
131 private Gson gson = new Gson();
133 public static final String CONFORMANCE_LEVEL = ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel();
134 public static final String SDC_VERSION = ExternalConfiguration.getAppVersion();
136 public static final Pattern UUID_NORMATIVE_NEW_VERSION = Pattern.compile("^\\d{1,}.0");
137 public static final String ARTIFACTS_PATH = "Artifacts/";
138 public static final String RESOURCES_PATH = "Resources/";
139 public static final String INFORMATIONAL_ARTIFACTS = "Informational/";
140 public static final String DEPLOYMENT_ARTIFACTS = "Deployment/";
141 public static final String WORKFLOW_ARTIFACT_DIR = "Workflows"+File.separator+"BPMN"+File.separator;
142 public static final String DEPLOYMENT_ARTIFACTS_DIR = "Deployment"+File.separator;
144 public static final String DEFINITIONS_PATH = "Definitions/";
145 private static final String CSAR_META_VERSION = "1.0";
146 private static final String CSAR_META_PATH_FILE_NAME = "csar.meta";
147 private static final String TOSCA_META_PATH_FILE_NAME = "TOSCA-Metadata/TOSCA.meta";
148 private static final String TOSCA_META_VERSION = "1.0";
149 private static final String CSAR_VERSION = "1.1";
150 public static final String ARTIFACTS = "Artifacts";
151 public static final String DEFINITION = "Definitions";
152 public static final String DEL_PATTERN = "([/\\\\]+)";
153 private static String versionFirstThreeOctates;
155 public static final String VFC_NODE_TYPE_ARTIFACTS_PATH_PATTERN = ARTIFACTS + DEL_PATTERN +
156 ImportUtils.Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX +
157 "([\\d\\w\\_\\-\\.\\s]+)" + DEL_PATTERN +
158 "([\\d\\w\\_\\-\\.\\s]+)" + DEL_PATTERN +
159 "([\\d\\w\\_\\-\\.\\s]+)" + DEL_PATTERN +
160 "([\\d\\w\\_\\-\\.\\s]+)";
162 public static final String VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN = ARTIFACTS + DEL_PATTERN+
163 // Artifact Group (i.e Deployment/Informational)
164 "([\\w\\_\\-\\.\\s]+)" + DEL_PATTERN +
166 "([\\w\\_\\-\\.\\s]+)" + DEL_PATTERN +
167 // Artifact Any File Name
169 public static final String VALID_ENGLISH_ARTIFACT_NAME = "([\\w\\_\\-\\.\\s]+)";
170 public static final String SERVICE_TEMPLATE_PATH_PATTERN = DEFINITION + DEL_PATTERN+
171 // Service Template File Name
172 "([\\w\\_\\-\\.\\s]+)";
174 public static final String ARTIFACT_CREATED_FROM_CSAR = "Artifact created from csar";
177 if(SDC_VERSION != null && !SDC_VERSION.isEmpty()){
178 Matcher matcher = Pattern.compile("(?!\\.)(\\d+(\\.\\d+)+)(?![\\d\\.])").matcher(SDC_VERSION);
180 versionFirstThreeOctates = matcher.group(0);
182 versionFirstThreeOctates = "";
190 * @param isInCertificationRequest
193 public Either<byte[], ResponseFormat> createCsar(Component component, boolean getFromCS, boolean isInCertificationRequest) {
194 return createCsar(component, getFromCS, isInCertificationRequest, false);
197 private Either<byte[], ResponseFormat> createCsar(Component component, boolean getFromCS, boolean isInCertificationRequest, boolean mockGenerator) {
198 final String createdBy = component.getCreatorFullName();
201 Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
202 ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
203 fileName = artifactDefinition.getArtifactName();
205 String toscaConformanceLevel = ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel();
206 String csarBlock0 = createCsarBlock0(CSAR_META_VERSION, toscaConformanceLevel);
207 byte[] csarBlock0Byte = csarBlock0.getBytes();
209 final String toscaBlock0 = createToscaBlock0(TOSCA_META_VERSION, CSAR_VERSION, createdBy, fileName);
210 byte[] toscaBlock0Byte = toscaBlock0.getBytes();
212 Either<byte[], ResponseFormat> generateCsarZipResponse = generateCsarZip(csarBlock0Byte, toscaBlock0Byte, component, getFromCS, isInCertificationRequest, mockGenerator);
214 if (generateCsarZipResponse.isRight()) {
215 return Either.right(generateCsarZipResponse.right().value());
218 return Either.left(generateCsarZipResponse.left().value());
221 private Either<byte[], ResponseFormat> generateCsarZip(byte[] csarBlock0Byte, byte[] toscaBlock0Byte, Component component, boolean getFromCS, boolean isInCertificationRequest, boolean mockGenerator) {
223 ByteArrayOutputStream out = new ByteArrayOutputStream();
224 ZipOutputStream zip = new ZipOutputStream(out);
226 zip.putNextEntry(new ZipEntry(CSAR_META_PATH_FILE_NAME));
227 zip.write(csarBlock0Byte);
228 zip.putNextEntry(new ZipEntry(TOSCA_META_PATH_FILE_NAME));
229 zip.write(toscaBlock0Byte);
230 Either<ZipOutputStream, ResponseFormat> populateZip = populateZip(component, getFromCS, zip, isInCertificationRequest, mockGenerator);
231 if (populateZip.isRight()) {
232 log.debug("Failed to populate CSAR zip file {}", populateZip.right().value());
233 return Either.right(populateZip.right().value());
237 byte[] byteArray = out.toByteArray();
239 return Either.left(byteArray);
240 } catch (IOException e) {
241 log.debug("Failed with IOexception to create CSAR zip for component {}", component.getUniqueId(), e);
243 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
244 return Either.right(responseFormat);
248 private Either<ZipOutputStream, ResponseFormat> populateZip(Component component, boolean getFromCS, ZipOutputStream zip, boolean isInCertificationRequest, boolean mockGenerator) throws IOException {
250 LifecycleStateEnum lifecycleState = component.getLifecycleState();
251 String componentYaml;
252 Either<ToscaRepresentation, ToscaError> exportComponent;
254 // <file name, cassandraId, component>
255 List<Triple<String, String, Component>> dependencies = null;
256 List<ImmutablePair<Component, byte[]>> generatorInputs = new LinkedList<>();
258 Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
259 ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
260 String fileName = artifactDefinition.getArtifactName();
262 if (getFromCS || !(lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) {
263 String cassandraId = artifactDefinition.getEsId();
264 Either<byte[], ActionStatus> fromCassandra = getFromCassandra(cassandraId);
265 if (fromCassandra.isRight()) {
266 log.debug("ArtifactName {}, unique ID {}", artifactDefinition.getArtifactName(), artifactDefinition.getUniqueId());
267 ResponseFormat responseFormat = componentsUtils.getResponseFormat(fromCassandra.right().value());
268 return Either.right(responseFormat);
270 mainYaml = fromCassandra.left().value();
273 exportComponent = toscaExportUtils.exportComponent(component);
274 if (exportComponent.isRight()) {
275 log.debug("exportComponent failed", exportComponent.right().value());
276 ActionStatus convertedFromToscaError = componentsUtils.convertFromToscaError(exportComponent.right().value());
277 ResponseFormat responseFormat = componentsUtils.getResponseFormat(convertedFromToscaError);
278 return Either.right(responseFormat);
280 ToscaRepresentation exportResult = exportComponent.left().value();
281 componentYaml = exportResult.getMainYaml();
282 mainYaml = componentYaml.getBytes();
283 dependencies = exportResult.getDependencies();
286 zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + fileName));
288 //US798487 - Abstraction of complex types
289 if (!ModelConverter.isAtomicComponent(component)){
290 log.debug("Component {} is complex - generating abstract type for it..", component.getName());
291 writeComponentInterface(component, zip, fileName);
294 generatorInputs.add(new ImmutablePair<Component, byte[]>(component, mainYaml));
296 if (dependencies == null) {
297 Either<ToscaTemplate, ToscaError> dependenciesRes = toscaExportUtils.getDependencies(component);
298 if (dependenciesRes.isRight()) {
299 log.debug("Failed to retrieve dependencies for component {}, error {}", component.getUniqueId(),
300 dependenciesRes.right().value());
301 ActionStatus convertFromToscaError = componentsUtils.convertFromToscaError(dependenciesRes.right().value());
302 ResponseFormat responseFormat = componentsUtils.getResponseFormat(convertFromToscaError);
303 return Either.right(responseFormat);
305 dependencies = dependenciesRes.left().value().getDependencies();
308 //UID <cassandraId,filename,component>
309 Map<String, ImmutableTriple<String,String, Component>> innerComponentsCache = new HashMap<>();
311 if (dependencies != null && !dependencies.isEmpty()) {
312 for (Triple<String, String, Component> d : dependencies) {
313 String cassandraId = d.getMiddle();
314 Component childComponent = d.getRight();
315 Either<byte[], ActionStatus> entryData = getEntryData(cassandraId, childComponent);
317 if (entryData.isRight()) {
318 ResponseFormat responseFormat = componentsUtils.getResponseFormat(entryData.right().value());
319 return Either.right(responseFormat);
322 //fill innerComponentsCache
323 fileName = d.getLeft();
324 addComponentToCache(innerComponentsCache, cassandraId, fileName, childComponent);
325 addInnerComponentsToCache(innerComponentsCache, childComponent);
327 byte[] content = entryData.left().value();
328 generatorInputs.add(new ImmutablePair<Component, byte[]>(childComponent, content));
331 //add inner components to CSAR
332 for (Entry<String, ImmutableTriple<String, String, Component>> innerComponentTripleEntry : innerComponentsCache.entrySet()) {
334 ImmutableTriple<String, String, Component> innerComponentTriple = innerComponentTripleEntry.getValue();
336 Component innerComponent = innerComponentTriple.getRight();
337 String icFileName = innerComponentTriple.getMiddle();
339 // add component to zip
340 Either<byte[], ActionStatus> entryData = getEntryData(innerComponentTriple.getLeft(), innerComponent);
341 if (entryData.isRight()) {
342 ResponseFormat responseFormat = componentsUtils.getResponseFormat(entryData.right().value());
343 log.debug("Failed adding to zip component {}, error {}", innerComponentTriple.getLeft(),
344 entryData.right().value());
345 return Either.right(responseFormat);
347 byte[] content = entryData.left().value();
348 zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + icFileName));
351 // add component interface to zip
352 if (!ModelConverter.isAtomicComponent(innerComponent)) {
353 writeComponentInterface(innerComponent, zip, icFileName);
358 //retrieve SDC.zip from Cassandra
359 Either<byte[], ResponseFormat> latestSchemaFilesFromCassandra = getLatestSchemaFilesFromCassandra();
361 if(latestSchemaFilesFromCassandra.isRight()){
362 log.error("Error retrieving SDC Schema files from cassandra" );
363 return Either.right(latestSchemaFilesFromCassandra.right().value());
366 //add files from retireved SDC.zip to Definitions folder in CSAR
367 Either<ZipOutputStream, ResponseFormat> addSchemaFilesFromCassandra = addSchemaFilesFromCassandra(zip, latestSchemaFilesFromCassandra.left().value());
369 if(addSchemaFilesFromCassandra.isRight()){
370 return addSchemaFilesFromCassandra;
373 // Artifact Generation
374 if (component.getComponentType() == ComponentTypeEnum.SERVICE
375 && isInCertificationRequest) {
377 List<ArtifactDefinition> aiiArtifactList;
379 Either<List<ArtifactDefinition>, ResponseFormat> handleAAIArtifacts = handleAAIArtifacts(component, mockGenerator, generatorInputs);
381 if (handleAAIArtifacts.isLeft()) {
382 aiiArtifactList = handleAAIArtifacts.left().value();
384 log.debug("AAI Artifacts handling failed");
385 return Either.right(handleAAIArtifacts.right().value());
388 if (isInCertificationRequest) {
389 Either<ActionStatus, ResponseFormat> handleAllAAIArtifactsInDataModel = handleAllAAIArtifactsInDataModel(
390 component, aiiArtifactList, false, true);
392 if (handleAllAAIArtifactsInDataModel.isRight()) {
393 log.debug("AAI Artifacts handling (create, update, delete) failed");
394 return Either.right(handleAllAAIArtifactsInDataModel.right().value());
400 Either<CsarDefinition, ResponseFormat> collectedComponentCsarDefinition = collectComponentCsarDefinition(component);
402 if (collectedComponentCsarDefinition.isRight()) {
403 return Either.right(collectedComponentCsarDefinition.right().value());
406 return writeAllFilesToCsar(component, collectedComponentCsarDefinition.left().value(), zip, isInCertificationRequest);
409 private Either<ZipOutputStream, ResponseFormat> addSchemaFilesFromCassandra(ZipOutputStream zip, byte[] schemaFileZip){
411 final int initSize = 2048;
413 log.debug("Starting copy from Schema file zip to CSAR zip");
415 try (ZipInputStream zipStream = new ZipInputStream(new ByteArrayInputStream(schemaFileZip));
416 ByteArrayOutputStream out = new ByteArrayOutputStream();
417 BufferedOutputStream bos = new BufferedOutputStream(out, initSize);) {
419 ZipEntry entry = null;
421 while ((entry = zipStream.getNextEntry()) != null) {
423 String entryName = entry.getName();
424 int readSize = initSize;
425 byte[] entryData = new byte[initSize];
427 while ((readSize = zipStream.read(entryData, 0, readSize)) != -1) {
428 bos.write(entryData, 0, readSize);
433 zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + entryName));
434 zip.write(out.toByteArray());
438 } catch (IOException e) {
439 log.error("Error while writing the SDC schema file to the CSAR {}", e);
440 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
443 log.debug("Finished coppy from Schema file zip to CSAR zip");
445 return Either.left(zip);
449 private void addInnerComponentsToCache(Map<String, ImmutableTriple<String, String, Component>> componentCache,
450 Component childComponent) {
452 List<ComponentInstance> instances = childComponent.getComponentInstances();
454 if(instances != null) {
455 instances.forEach(ci -> {
456 ImmutableTriple<String, String, Component> componentRecord = componentCache.get(ci.getComponentUid());
457 if (componentRecord == null) {
458 // all resource must be only once!
459 Either<Resource, StorageOperationStatus> resource = toscaOperationFacade.getToscaElement(ci.getComponentUid());
460 if (resource.isRight()) {
461 log.debug("Failed to fetch resource with id {} for instance {}");
463 Component componentRI = resource.left().value();
465 Map<String, ArtifactDefinition> childToscaArtifacts = componentRI.getToscaArtifacts();
466 ArtifactDefinition childArtifactDefinition = childToscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
467 if (childArtifactDefinition != null) {
469 addComponentToCache(componentCache, childArtifactDefinition.getEsId(), childArtifactDefinition.getArtifactName(), componentRI);
472 //if not atomic - insert inner components as well
473 if(!ModelConverter.isAtomicComponent(componentRI)) {
474 addInnerComponentsToCache(componentCache, componentRI);
481 private void addComponentToCache(Map<String, ImmutableTriple<String, String, Component>> componentCache,
482 String id, String fileName, Component component) {
484 ImmutableTriple<String, String, Component> cachedComponent = componentCache.get(component.getInvariantUUID());
485 if (cachedComponent == null || CommonBeUtils.compareAsdcComponentVersions(component.getVersion(), cachedComponent.getRight().getVersion())) {
486 componentCache.put(component.getInvariantUUID(),
487 new ImmutableTriple<String, String, Component>(id, fileName, component));
489 if(cachedComponent != null) {
490 //overwriting component with newer version
491 log.warn("Overwriting component invariantID {} of version {} with a newer version {}", id, cachedComponent.getRight().getVersion(), component.getVersion());
496 private Either<ZipOutputStream, ResponseFormat> writeComponentInterface(Component component, ZipOutputStream zip, String fileName) {
498 Either<ToscaRepresentation, ToscaError> componentInterface = toscaExportUtils.exportComponentInterface(component);
499 ToscaRepresentation componentInterfaceYaml = componentInterface.left().value();
500 String mainYaml = componentInterfaceYaml.getMainYaml();
501 String interfaceFileName = DEFINITIONS_PATH + ToscaExportHandler.getInterfaceFilename(fileName);
503 zip.putNextEntry(new ZipEntry(interfaceFileName));
504 zip.write(mainYaml.getBytes());
506 } catch (Exception e) {
507 log.error("#writeComponentInterface - zip writing failed with error: ", e);
508 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
511 return Either.left(zip);
514 private Either<List<ArtifactDefinition>, ResponseFormat> handleAAIArtifacts(Component component, boolean mockGenerator, List<ImmutablePair<Component, byte[]>> generatorInputs) {
516 ComponentTypeEnum componentType = component.getComponentType();
517 List<Artifact> generatedArtifacts;
518 List<ArtifactDefinition> aaiArtifacts = new LinkedList<>();
520 if (componentType == ComponentTypeEnum.SERVICE && !generatorInputs.isEmpty()) {
521 List<Artifact> convertedGeneratorInputs = convertToGeneratorArtifactsInput(generatorInputs);
523 Either<List<Artifact>, String> generatorResponse;
526 generatorResponse = artifactGenerator(convertedGeneratorInputs, ArtifactType.OTHER, component);
528 generatorResponse = artifactGenerator(convertedGeneratorInputs, ArtifactType.AAI, component);
531 if (generatorResponse.isRight()) {
532 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.AAI_ARTIFACT_GENERATION_FAILED, component.getComponentType().getValue(), component.getName(), generatorResponse.right().value());
533 return Either.right(responseFormat);
536 generatedArtifacts = generatorResponse.left().value();
538 aaiArtifacts = convertToArtifactDefinitionFromArtifactGeneratedData(generatedArtifacts);
542 return Either.left(aaiArtifacts);
545 private Either<ActionStatus, ResponseFormat> handleAllAAIArtifactsInDataModel(Component component, List<ArtifactDefinition> artifactsFromAAI, boolean shouldLock, boolean inTransaction) {
547 Either<ActionStatus, ResponseFormat> handleAAIArtifactsResponse;
548 User lastComponentUpdater;
550 List<ArtifactDefinition> aaiArtifatcsToCreate = getAAIArtifatcsForCreate(artifactsFromAAI, component);
551 List<ArtifactDefinition> aaiArtifatcsToDelete = getAAIArtifatcsForDelete(artifactsFromAAI, component);
552 List<ArtifactDefinition> aaiArtifatcsToUpdate = getAAIArtifatcsForUpdate(artifactsFromAAI, component);
554 String lastUpdaterUserId = component.getLastUpdaterUserId();
555 Either<User, ResponseFormat> validateUserExists = artifactsBusinessLogic.validateUserExists(lastUpdaterUserId, "CSAR creation util", true);
557 if (validateUserExists.isRight()) {
558 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.AAI_ARTIFACT_GENERATION_FAILED, component.getComponentType().getValue(), component.getName(), "User not found");
559 return Either.right(responseFormat);
562 lastComponentUpdater = validateUserExists.left().value();
564 handleAAIArtifactsResponse = handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToDelete, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.DELETE), lastComponentUpdater, shouldLock,
567 if (handleAAIArtifactsResponse.isRight()) {
568 return handleAAIArtifactsResponse;
571 handleAAIArtifactsResponse = handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToCreate, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.CREATE), lastComponentUpdater, shouldLock,
574 if (handleAAIArtifactsResponse.isRight()) {
575 return handleAAIArtifactsResponse;
578 return handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToUpdate, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.UPDATE), lastComponentUpdater, shouldLock, inTransaction);
581 private List<ArtifactDefinition> getAAIArtifatcsForUpdate(List<ArtifactDefinition> artifactsFromAAI, Component component) {
583 Set<String> componetDeploymentArtifactLables = component.getDeploymentArtifacts().keySet();
584 Set<String> componetInformationalArtifactLables = component.getArtifacts().keySet();
586 return artifactsFromAAI.stream()
587 .filter(e -> componetDeploymentArtifactLables.contains(e.getArtifactLabel()) || componetInformationalArtifactLables.contains(e.getArtifactLabel()))
588 .filter(e -> checkAaiForUpdate(component, e))
589 .collect(Collectors.toList());
592 private boolean checkAaiForUpdate(Component component, ArtifactDefinition artifactDefinition) {
593 ArtifactDefinition artifactDefinitionComp = component.getDeploymentArtifacts().get(artifactDefinition.getArtifactLabel());
595 if (artifactDefinitionComp == null) {
596 log.warn("Failed to get {} artifact", artifactDefinition.getArtifactLabel());
600 // Old Artifacts before the generated flag introduction if contains "aai" ignore case prefix updated
601 if (artifactDefinitionComp.getGenerated() == null) {
602 if (artifactDefinitionComp.getArtifactLabel().toLowerCase().startsWith("aai")) {
605 log.warn("The artifact {} flag is null but AAI prefix is abssent Not updated", artifactDefinition.getArtifactLabel());
608 if (artifactDefinition.getGenerated()) {
611 log.warn("Generated artifact {} was already uploaded manually", artifactDefinition.getArtifactLabel());
617 private List<ArtifactDefinition> getAAIArtifatcsForDelete(List<ArtifactDefinition> artifactsFromAAI, Component component) {
619 Set<String> aaiLabels = artifactsFromAAI.stream()
620 .map(ArtifactDefinition::getArtifactLabel)
621 .collect(Collectors.toSet());
623 List<ArtifactDefinition> artifactsForDeleteDeployment = component.getDeploymentArtifacts().values().stream()
624 // Filter Out Artifacts that are not contained in artifacts returned
626 .filter(e -> !aaiLabels.contains(e.getArtifactLabel()))
627 .collect(Collectors.toList());
629 List<ArtifactDefinition> artifactsForDeleteInformational = component.getArtifacts().values().stream()
630 // Filter Out Artifacts that are not contained in artifacts returned
632 .filter(e -> !aaiLabels.contains(e.getArtifactLabel()))
633 .collect(Collectors.toList());
635 artifactsForDeleteDeployment.addAll(artifactsForDeleteInformational);
637 return artifactsForDeleteDeployment.stream()
638 .filter(e -> (e.getGenerated() != null && e.getGenerated().equals(Boolean.TRUE)) || (e.getGenerated() == null && e.getArtifactLabel().toLowerCase().startsWith("aai")))
639 .collect(Collectors.toList());
642 private List<ArtifactDefinition> getAAIArtifatcsForCreate(List<ArtifactDefinition> artifactsFromAAI, Component component) {
644 Set<String> componentDeploymentLabels = component.getDeploymentArtifacts().keySet();
645 Set<String> componentInfoLabels = component.getArtifacts().keySet();
647 // If the artifact label does not exist in the service -
648 // store the artifact (generate uuid and version, "generated" flag is TRUE)
649 return artifactsFromAAI.stream()
650 .filter(e -> !componentDeploymentLabels.contains(e.getArtifactLabel()) && !componentInfoLabels.contains(e.getArtifactLabel()))
651 .collect(Collectors.toList());
654 private Either<ActionStatus, ResponseFormat> handleAAIArtifactsInDataModelByOperationType(Component component, List<ArtifactDefinition> generatedArtifactsDefinitions, ArtifactOperationInfo operationType, User user, boolean shouldLock,
655 boolean inTransaction) {
657 String componentUniqueId = component.getUniqueId();
658 ComponentTypeEnum componentType = component.getComponentType();
660 for (ArtifactDefinition artDef : generatedArtifactsDefinitions) {
661 String data = gson.toJson(artDef);
662 String dataMD5 = GeneralUtility.calculateMD5Base64EncodedByString(data);
663 String artifactUniqueId = null;
665 if ((operationType.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE) || (operationType.getArtifactOperationEnum() == ArtifactOperationEnum.DELETE)) {
666 String artifactLabel = artDef.getArtifactLabel();
667 ArtifactDefinition artifactDefinition = component.getDeploymentArtifacts().get(artifactLabel);
668 if (artifactDefinition != null) {
669 artifactUniqueId = artifactDefinition.getUniqueId();
673 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> validateAndHandleArtifact = artifactsBusinessLogic.validateAndHandleArtifact(componentUniqueId, componentType, operationType, artifactUniqueId, artDef, dataMD5, data, null,
674 null, user, component, shouldLock, inTransaction, false);
676 if (validateAndHandleArtifact.isRight()) {
677 if (ArtifactOperationEnum.isCreateOrLink(operationType.getArtifactOperationEnum()) || ArtifactOperationEnum.UPDATE == operationType.getArtifactOperationEnum()) {
678 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.AAI_ARTIFACT_GENERATION_FAILED, componentType.getValue(), component.getName(), validateAndHandleArtifact.right().value().toString());
680 Either.right(responseFormat);
682 log.warn("Generated artifact {} could not be deleted", artDef.getArtifactLabel());
687 return Either.left(ActionStatus.OK);
690 private List<ArtifactDefinition> convertToArtifactDefinitionFromArtifactGeneratedData(List<Artifact> generatorOutput) {
691 List<ArtifactDefinition> artifactDefList = new LinkedList<>();
693 for (Artifact artifact : generatorOutput) {
694 ArtifactDefinition newEntry = new ArtifactDefinition();
695 newEntry.setArtifactName(artifact.getName());
696 newEntry.setArtifactType(artifact.getType());
697 newEntry.setArtifactGroupType(ArtifactGroupTypeEnum.findType(artifact.getGroupType()));
698 newEntry.setDescription(artifact.getDescription());
700 // Normalizing the artifact label to match those stored in DB
701 String normalizeArtifactLabel = ValidationUtils.normalizeArtifactLabel(artifact.getLabel());
702 newEntry.setArtifactLabel(normalizeArtifactLabel);
703 newEntry.setPayload(Base64.decodeBase64(artifact.getPayload()));
704 newEntry.setArtifactChecksum(artifact.getChecksum());
705 // Flag that set to true in case that the artifact is generated by AI&I generator
706 newEntry.setGenerated(Boolean.TRUE);
708 artifactDefList.add(newEntry);
711 return artifactDefList;
714 // List<ImmutablePair<Component, byte[] artifactBytes>>
715 // artifact stored by label
716 private List<Artifact> convertToGeneratorArtifactsInput(List<ImmutablePair<Component, byte[]>> inputs) {
717 List<Artifact> listOfArtifactsInput = new LinkedList<>();
718 for (ImmutablePair<Component, byte[]> triple : inputs) {
719 Component component = triple.getLeft();
721 Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
722 ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
724 String artifactName = artifactDefinition.getArtifactName();
725 String artifactType = artifactDefinition.getArtifactType();
726 String artifactGroupType = artifactDefinition.getArtifactGroupType().getType();
727 String artifactDescription = artifactDefinition.getDescription();
728 String artifactLabel = artifactDefinition.getArtifactLabel();
729 byte[] right = triple.getRight();
730 // The md5 calculated on the uncoded data
731 String md5Hex = DigestUtils.md5Hex(right);
732 byte[] payload = Base64.encodeBase64(right);
733 String artifactVersion = artifactDefinition.getArtifactVersion();
735 Artifact convertedArtifact = new Artifact(artifactType, artifactGroupType, md5Hex, payload);
736 convertedArtifact.setName(artifactName);
737 convertedArtifact.setDescription(artifactDescription);
738 convertedArtifact.setLabel(artifactLabel);
739 convertedArtifact.setVersion(artifactVersion);
741 listOfArtifactsInput.add(convertedArtifact);
744 return listOfArtifactsInput;
747 private Either<byte[], ActionStatus> getEntryData(String cassandraId, Component childComponent) {
749 if (cassandraId == null || cassandraId.isEmpty()) {
750 Either<ToscaRepresentation, ToscaError> exportRes = toscaExportUtils.exportComponent(childComponent);
751 if (exportRes.isRight()) {
752 log.debug("Failed to export tosca template for child component {} error {}", childComponent.getUniqueId(), exportRes.right().value());
753 return Either.right(componentsUtils.convertFromToscaError(exportRes.right().value()));
755 content = exportRes.left().value().getMainYaml().getBytes();
757 Either<byte[], ActionStatus> fromCassandra = getFromCassandra(cassandraId);
758 if (fromCassandra.isRight()) {
759 return Either.right(fromCassandra.right().value());
761 content = fromCassandra.left().value();
764 return Either.left(content);
767 private Either<byte[], ResponseFormat> getLatestSchemaFilesFromCassandra() {
768 Either<List<SdcSchemaFilesData>, CassandraOperationStatus> specificSchemaFiles = sdcSchemaFilesCassandraDao.getSpecificSchemaFiles(versionFirstThreeOctates, CONFORMANCE_LEVEL);
770 if(specificSchemaFiles.isRight()){
771 log.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}", versionFirstThreeOctates, CONFORMANCE_LEVEL);
772 StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(specificSchemaFiles.right().value());
773 ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(storageStatus);
774 return Either.right(componentsUtils.getResponseFormat(convertedFromStorageResponse));
777 List<SdcSchemaFilesData> listOfSchemas = specificSchemaFiles.left().value();
779 if(listOfSchemas.isEmpty()){
780 log.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}", versionFirstThreeOctates, CONFORMANCE_LEVEL);
781 return Either.right(componentsUtils.getResponseFormat(ActionStatus.TOSCA_SCHEMA_FILES_NOT_FOUND, versionFirstThreeOctates, CONFORMANCE_LEVEL));
784 SdcSchemaFilesData schemaFile = listOfSchemas.iterator().next();
786 return Either.left(schemaFile.getPayloadAsArray());
789 private Either<byte[], ActionStatus> getFromCassandra(String cassandraId) {
790 Either<ESArtifactData, CassandraOperationStatus> artifactResponse = artifactCassandraDao.getArtifact(cassandraId);
792 if (artifactResponse.isRight()) {
793 log.debug("Failed to fetch artifact from Cassandra by id {} error {} ", cassandraId, artifactResponse.right().value());
795 StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactResponse.right().value());
796 ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(storageStatus);
797 return Either.right(convertedFromStorageResponse);
799 ESArtifactData artifactData = artifactResponse.left().value();
800 return Either.left(artifactData.getDataAsArray());
803 private String createCsarBlock0(String metaFileVersion, String toscaConformanceLevel) {
804 final String BLOCK_0_TEMPLATE =
805 "SDC-TOSCA-Meta-File-Version: %s\nSDC-TOSCA-Definitions-Version: %s\n";
806 String readyBlock = String.format(BLOCK_0_TEMPLATE, metaFileVersion, toscaConformanceLevel);
810 private String createToscaBlock0(String metaFileVersion, String csarVersion, String createdBy, String entryDef) {
811 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";
812 return String.format(block0template, metaFileVersion, csarVersion, createdBy, entryDef);
815 private Either<List<Artifact>, String> artifactGenerator(List<Artifact> artifactList, ArtifactType type, Component component) {
817 ArtifactGenerationServiceImpl artifactGenerationServiceImpl = new ArtifactGenerationServiceImpl();
818 ArtifactTypes artifactTypes = new ArtifactTypes();
819 List<ArtifactType> artifactTypesList = new LinkedList<>();
820 ArtifactType otherType;
823 otherType = ArtifactType.OTHER;
828 artifactTypesList.add(otherType);
829 artifactTypes.setArtifactTypes(artifactTypesList);
831 String configJson = gson.toJson(artifactTypes);
832 Map<String, String> additionalParams = new HashMap<>();
835 if (UUID_NORMATIVE_NEW_VERSION.matcher(component.getVersion()).matches() ) {
836 version = component.getVersion();
838 String[] versionParts = component.getVersion().split(ToscaElementLifecycleOperation.VERSION_DELIMETER_REGEXP);
839 Integer majorVersion = Integer.parseInt(versionParts[0]);
841 version = (majorVersion + 1) + ToscaElementLifecycleOperation.VERSION_DELIMETER + "0";
844 additionalParams.put(AdditionalParams.ServiceVersion.getName(), version);
845 GenerationData generatedArtifacts = artifactGenerationServiceImpl.generateArtifact(artifactList, configJson, additionalParams);
847 Map<String, List<String>> errorData = generatedArtifacts.getErrorData();
849 if (!errorData.isEmpty()) {
850 Set<String> keySet = errorData.keySet();
851 StringBuilder error = new StringBuilder();
853 for (String key : keySet) {
854 List<String> errorList = errorData.get(key);
855 log.debug("The Artifact Generator Failed - {} with following: {}", key, errorList);
856 error.append(key + errorList);
859 return Either.right(error.toString());
862 return Either.left(generatedArtifacts.getResultData());
866 * Extracts artifacts of VFCs from CSAR
869 * @return Map of <String, List<ArtifactDefinition>> the contains Lists of artifacts according vfcToscaNamespace
871 public static Map<String, List<ArtifactDefinition>> extractVfcsArtifactsFromCsar(Map<String, byte[]> csar) {
873 Map<String, List<ArtifactDefinition>> artifacts = new HashMap<>();
875 log.debug("************* Going to extract VFCs artifacts from Csar. ");
876 Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
877 csar.entrySet().stream()
878 // filter CSAR entry by node type artifact path
879 .filter(e -> Pattern.compile(VFC_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey()).matches())
880 // extract ArtifactDefinition from CSAR entry for each entry with matching artifact path
881 .forEach(e -> addExtractedVfcArtifact(extractVfcArtifact(e, collectedWarningMessages), artifacts));
882 // add counter suffix to artifact labels
883 handleWarningMessages(collectedWarningMessages);
890 * Print warnings to log
892 * @param collectedWarningMessages
894 public static void handleWarningMessages(Map<String, Set<List<String>>> collectedWarningMessages) {
895 collectedWarningMessages.entrySet().stream()
897 .forEach(e -> e.getValue().stream()
898 // add each warning message to log
899 .forEach(args -> log.warn(e.getKey(), args.toArray())));
903 private static void addExtractedVfcArtifact(ImmutablePair<String, ArtifactDefinition> extractedVfcArtifact, Map<String, List<ArtifactDefinition>> artifacts) {
904 if (extractedVfcArtifact != null) {
905 List<ArtifactDefinition> currArtifactsList;
906 String vfcToscaNamespace = extractedVfcArtifact.getKey();
907 if (artifacts.containsKey(vfcToscaNamespace)) {
908 currArtifactsList = artifacts.get(vfcToscaNamespace);
910 currArtifactsList = new ArrayList<>();
911 artifacts.put(vfcToscaNamespace, currArtifactsList);
913 currArtifactsList.add(extractedVfcArtifact.getValue());
917 private static ImmutablePair<String, ArtifactDefinition> extractVfcArtifact(Entry<String, byte[]> entry, Map<String, Set<List<String>>> collectedWarningMessages) {
918 ArtifactDefinition artifact;
919 String[] parsedCsarArtifactPath = entry.getKey().split("/");
920 Either<ArtifactGroupTypeEnum, Boolean> eitherArtifactGroupType = detectArtifactGroupType(parsedCsarArtifactPath[2].toUpperCase(), collectedWarningMessages);
921 if (eitherArtifactGroupType.isLeft()) {
922 artifact = buildArtifactDefinitionFromCsarArtifactPath(entry, collectedWarningMessages, parsedCsarArtifactPath, eitherArtifactGroupType.left().value());
926 return new ImmutablePair<>(parsedCsarArtifactPath[1], artifact);
929 private static Either<ArtifactGroupTypeEnum, Boolean> detectArtifactGroupType(String groupType, Map<String, Set<List<String>>> collectedWarningMessages) {
930 Either<ArtifactGroupTypeEnum, Boolean> result;
932 ArtifactGroupTypeEnum artifactGroupType = ArtifactGroupTypeEnum.findType(groupType.toUpperCase());
933 if (artifactGroupType == null || (artifactGroupType != ArtifactGroupTypeEnum.INFORMATIONAL && artifactGroupType != ArtifactGroupTypeEnum.DEPLOYMENT)) {
934 String warningMessage = "Warning - unrecognized artifact group type {} was received.";
935 List<String> messageArguments = new ArrayList<>();
936 messageArguments.add(groupType);
937 if (!collectedWarningMessages.containsKey(warningMessage)) {
938 Set<List<String>> messageArgumentLists = new HashSet<>();
939 messageArgumentLists.add(messageArguments);
940 collectedWarningMessages.put(warningMessage, messageArgumentLists);
942 collectedWarningMessages.get(warningMessage).add(messageArguments);
945 result = Either.right(false);
948 result = Either.left(artifactGroupType);
950 } catch (Exception e) {
951 log.debug("detectArtifactGroupType failed with exception", e);
952 result = Either.right(false);
957 private static ArtifactDefinition buildArtifactDefinitionFromCsarArtifactPath(Entry<String, byte[]> entry, Map<String, Set<List<String>>> collectedWarningMessages, String[] parsedCsarArtifactPath, ArtifactGroupTypeEnum artifactGroupType) {
958 ArtifactDefinition artifact;
959 artifact = new ArtifactDefinition();
960 artifact.setArtifactGroupType(artifactGroupType);
961 artifact.setArtifactType(detectArtifactTypeVFC(artifactGroupType, parsedCsarArtifactPath[3], parsedCsarArtifactPath[1], collectedWarningMessages));
962 artifact.setArtifactName(ValidationUtils.normalizeFileName(parsedCsarArtifactPath[parsedCsarArtifactPath.length - 1]));
963 artifact.setPayloadData(Base64.encodeBase64String(entry.getValue()));
964 artifact.setArtifactDisplayName(artifact.getArtifactName().lastIndexOf('.') > 0 ? artifact.getArtifactName().substring(0, artifact.getArtifactName().lastIndexOf('.')) : artifact.getArtifactName());
965 artifact.setArtifactLabel(ValidationUtils.normalizeArtifactLabel(artifact.getArtifactName()));
966 artifact.setDescription(ARTIFACT_CREATED_FROM_CSAR);
967 artifact.setIsFromCsar(true);
968 artifact.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(entry.getValue()));
972 public static final class NonMetaArtifactInfo {
973 private final String path;
974 private final String artifactName;
975 private final String displayName;
976 private final String artifactLabel;
977 private final ArtifactTypeEnum artifactType;
978 private final ArtifactGroupTypeEnum artifactGroupType;
979 private String payloadData;
980 private String artifactChecksum;
981 private String artifactUniqueId;
982 private final boolean isFromCsar;
984 public NonMetaArtifactInfo(String artifactName, String path, ArtifactTypeEnum artifactType, ArtifactGroupTypeEnum artifactGroupType, byte[] payloadData, String artifactUniqueId, boolean isFromCsar) {
987 this.isFromCsar = isFromCsar;
988 this.artifactName = ValidationUtils.normalizeFileName(artifactName);
989 this.artifactType = artifactType;
990 this.artifactGroupType = artifactGroupType;
991 final int pointIndex = artifactName.lastIndexOf('.');
992 if (pointIndex > 0) {
993 displayName = artifactName.substring(0, pointIndex);
995 displayName = artifactName;
997 this.artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactName);
998 if (payloadData != null) {
999 this.payloadData = Base64.encodeBase64String(payloadData);
1000 this.artifactChecksum = GeneralUtility.calculateMD5Base64EncodedByByteArray(payloadData);
1002 this.artifactUniqueId = artifactUniqueId;
1005 public String getPath() {
1009 public String getArtifactName() {
1010 return artifactName;
1013 public ArtifactTypeEnum getArtifactType() {
1014 return artifactType;
1017 public String getDisplayName() {
1021 public ArtifactGroupTypeEnum getArtifactGroupType() {
1022 return artifactGroupType;
1025 public String getArtifactLabel() {
1026 return artifactLabel;
1029 public boolean isFromCsar(){
1033 public String getPayloadData() {
1037 public String getArtifactChecksum() {
1038 return artifactChecksum;
1041 public String getArtifactUniqueId() {
1042 return artifactUniqueId;
1045 public void setArtifactUniqueId(String artifactUniqueId) {
1046 this.artifactUniqueId = artifactUniqueId;
1052 * This method checks the artifact GroupType & Artifact Type. <br>
1053 * if there is any problem warning messages are added to collectedWarningMessages
1055 * @param artifactPath
1056 * @param collectedWarningMessages
1059 public static Either<NonMetaArtifactInfo, Boolean> validateNonMetaArtifact(String artifactPath, byte[] payloadData, Map<String, Set<List<String>>> collectedWarningMessages) {
1060 Either<NonMetaArtifactInfo, Boolean> ret;
1062 String[] parsedArtifactPath = artifactPath.split("/");
1063 // Validate Artifact Group Type
1064 Either<ArtifactGroupTypeEnum, Boolean> eitherGroupType = detectArtifactGroupType(parsedArtifactPath[1], collectedWarningMessages);
1065 if (eitherGroupType.isLeft()) {
1066 final ArtifactGroupTypeEnum groupTypeEnum = eitherGroupType.left().value();
1068 // Validate Artifact Type
1069 String artifactType = parsedArtifactPath[2];
1070 artifactType = detectArtifactTypeVF(groupTypeEnum, artifactType, collectedWarningMessages);
1072 String artifactFileNameType = parsedArtifactPath[3];
1073 ret = Either.left(new NonMetaArtifactInfo(artifactFileNameType, artifactPath, ArtifactTypeEnum.findType(artifactType), groupTypeEnum, payloadData, null, true));
1076 ret = Either.right(eitherGroupType.right().value());
1078 } catch (Exception e) {
1079 log.debug("detectArtifactGroupType failed with exception", e);
1080 ret = Either.right(false);
1086 private static String detectArtifactTypeVFC(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, String parentVfName, Map<String, Set<List<String>>> collectedWarningMessages) {
1087 String warningMessage = "Warning - artifact type {} that was provided for VFC {} is not recognized.";
1088 return detectArtifactType(artifactGroupType, receivedTypeName, warningMessage, collectedWarningMessages, parentVfName);
1091 private static String detectArtifactTypeVF(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, Map<String, Set<List<String>>> collectedWarningMessages) {
1092 String warningMessage = "Warning - artifact type {} that was provided for VF is not recognized.";
1093 return detectArtifactType(artifactGroupType, receivedTypeName, warningMessage, collectedWarningMessages);
1096 private static String detectArtifactType(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, String warningMessage, Map<String, Set<List<String>>> collectedWarningMessages, String... arguments) {
1098 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(receivedTypeName);
1099 Map<String, ArtifactTypeConfig> resourceValidTypeArtifacts = null;
1101 if(artifactGroupType != null){
1102 switch (artifactGroupType) {
1104 resourceValidTypeArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration()
1105 .getResourceInformationalArtifacts();
1108 resourceValidTypeArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration()
1109 .getResourceDeploymentArtifacts();
1116 Set<String> validArtifactTypes = null;
1117 if(resourceValidTypeArtifacts != null){
1118 validArtifactTypes = resourceValidTypeArtifacts.keySet();
1121 if (validArtifactTypes == null || artifactType == null || !validArtifactTypes.contains(artifactType.getType())) {
1122 List<String> messageArguments = new ArrayList<>();
1123 messageArguments.add(receivedTypeName);
1124 messageArguments.addAll(Arrays.asList(arguments));
1125 if (!collectedWarningMessages.containsKey(warningMessage)) {
1126 Set<List<String>> messageArgumentLists = new HashSet<>();
1127 messageArgumentLists.add(messageArguments);
1128 collectedWarningMessages.put(warningMessage, messageArgumentLists);
1130 collectedWarningMessages.get(warningMessage).add(messageArguments);
1134 return artifactType == null ? ArtifactTypeEnum.OTHER.getType() : artifactType.getType();
1137 private Either<ZipOutputStream, ResponseFormat> writeAllFilesToCsar(Component mainComponent, CsarDefinition csarDefinition, ZipOutputStream zipstream, boolean isInCertificationRequest) throws IOException{
1138 ComponentArtifacts componentArtifacts = csarDefinition.getComponentArtifacts();
1140 Either<ZipOutputStream, ResponseFormat> writeComponentArtifactsToSpecifiedPath = writeComponentArtifactsToSpecifiedPath(mainComponent, componentArtifacts, zipstream, ARTIFACTS_PATH, isInCertificationRequest);
1142 if(writeComponentArtifactsToSpecifiedPath.isRight()){
1143 return Either.right(writeComponentArtifactsToSpecifiedPath.right().value());
1146 ComponentTypeArtifacts mainTypeAndCIArtifacts = componentArtifacts.getMainTypeAndCIArtifacts();
1147 writeComponentArtifactsToSpecifiedPath = writeArtifactsInfoToSpecifiedtPath(mainComponent, mainTypeAndCIArtifacts.getComponentArtifacts(), zipstream, ARTIFACTS_PATH, isInCertificationRequest);
1149 if(writeComponentArtifactsToSpecifiedPath.isRight()){
1150 return Either.right(writeComponentArtifactsToSpecifiedPath.right().value());
1153 Map<String, ArtifactsInfo> componentInstancesArtifacts = mainTypeAndCIArtifacts.getComponentInstancesArtifacts();
1154 Set<String> keySet = componentInstancesArtifacts.keySet();
1156 String currentPath = ARTIFACTS_PATH + RESOURCES_PATH;
1157 for (String keyAssetName : keySet) {
1158 ArtifactsInfo artifactsInfo = componentInstancesArtifacts.get(keyAssetName);
1159 String pathWithAssetName = currentPath + keyAssetName + "/";
1160 writeComponentArtifactsToSpecifiedPath = writeArtifactsInfoToSpecifiedtPath(mainComponent, artifactsInfo, zipstream, pathWithAssetName, isInCertificationRequest);
1162 if(writeComponentArtifactsToSpecifiedPath.isRight()){
1163 return Either.right(writeComponentArtifactsToSpecifiedPath.right().value());
1166 writeComponentArtifactsToSpecifiedPath = writeOperationsArtifactsToCsar(mainComponent, zipstream);
1168 if (writeComponentArtifactsToSpecifiedPath.isRight()) {
1169 return Either.right(writeComponentArtifactsToSpecifiedPath.right().value());
1171 return Either.left(zipstream);
1174 private Either<ZipOutputStream, ResponseFormat> writeOperationsArtifactsToCsar(Component component,
1175 ZipOutputStream zipstream) {
1176 if (component instanceof Service ) {
1177 return Either.left(zipstream);
1179 if (Objects.isNull(((Resource) component).getInterfaces())) {
1180 log.debug("Component Name {}- no interfaces found", component.getNormalizedName());
1181 return Either.left(zipstream);
1183 final Map<String, InterfaceDefinition> interfaces = ((Resource) component).getInterfaces();
1185 for (Map.Entry<String, InterfaceDefinition> interfaceEntry : interfaces.entrySet()) {
1186 for (OperationDataDefinition operation : interfaceEntry.getValue().getOperations().values()) {
1188 if (Objects.isNull(operation.getImplementation())) {
1189 log.debug("Component Name {}, Interface Id {}, Operation Name {} - no Operation Implementation found",
1190 component.getNormalizedName(), interfaceEntry.getValue().getUniqueId(),
1191 operation.getName());
1194 if (Objects.isNull(operation.getImplementation().getArtifactName())) {
1195 log.debug("Component Name {}, Interface Id {}, Operation Name {} - no artifact found",
1196 component.getNormalizedName(), interfaceEntry.getValue().getUniqueId(),
1197 operation.getName());
1201 final String artifactUUID = operation.getImplementation().getArtifactUUID();
1203 final Either<byte[], ActionStatus> artifactFromCassandra = getFromCassandra(artifactUUID);
1204 final String artifactName = operation.getImplementation().getArtifactName();
1205 if (artifactFromCassandra.isRight()) {
1206 log.error("ArtifactName {}, unique ID {}", artifactName, artifactUUID);
1207 log.error("Failed to get {} payload from DB reason: {}", artifactName,
1208 artifactFromCassandra.right().value());
1209 return Either.right(componentsUtils.getResponseFormat(
1210 ActionStatus.ARTIFACT_PAYLOAD_NOT_FOUND_DURING_CSAR_CREATION, "Resource",
1211 component.getUniqueId(), artifactName, artifactUUID));
1214 final byte[] payloadData = artifactFromCassandra.left().value();
1215 zipstream.putNextEntry(new ZipEntry(OperationArtifactUtil.createOperationArtifactPath(
1216 component.getNormalizedName(), interfaceEntry.getValue().getToscaResourceName(), operation)));
1217 zipstream.write(payloadData);
1219 } catch (IOException e) {
1220 log.error("Component Name {}, Interface Name {}, Operation Name {}", component.getNormalizedName(),
1221 interfaceEntry.getKey(), operation.getName());
1222 log.error("Error while writing the operation's artifacts to the CSAR " + "{}", e);
1223 return Either.right(componentsUtils
1224 .getResponseFormat(ActionStatus.ERROR_DURING_CSAR_CREATION, "Resource",
1225 component.getUniqueId()));
1229 return Either.left(zipstream);
1233 private Either<ZipOutputStream, ResponseFormat> writeComponentArtifactsToSpecifiedPath(Component mainComponent, ComponentArtifacts componentArtifacts, ZipOutputStream zipstream,
1234 String currentPath, boolean isInCertificationRequest) throws IOException {
1235 Map<String, ComponentTypeArtifacts> componentTypeArtifacts = componentArtifacts.getComponentTypeArtifacts();
1237 //<Inner Asset TOSCA name (e.g. VFC name)> folder name: <Inner Asset TOSCA name (e.g. VFC name)>_v<version>.
1238 //E.g. "org.openecomp.resource.vf.vipr_atm_v1.0"
1239 Set<String> componentTypeArtifactsKeys = componentTypeArtifacts.keySet();
1240 for (String keyAssetName : componentTypeArtifactsKeys) {
1241 ComponentTypeArtifacts componentInstanceArtifacts = componentTypeArtifacts.get(keyAssetName);
1242 ArtifactsInfo componentArtifacts2 = componentInstanceArtifacts.getComponentArtifacts();
1243 String pathWithAssetName = currentPath + keyAssetName + "/";
1244 Either<ZipOutputStream, ResponseFormat> writeArtifactsInfoToSpecifiedtPath = writeArtifactsInfoToSpecifiedtPath(mainComponent, componentArtifacts2, zipstream, pathWithAssetName, isInCertificationRequest);
1246 if(writeArtifactsInfoToSpecifiedtPath.isRight()){
1247 return writeArtifactsInfoToSpecifiedtPath;
1251 return Either.left(zipstream);
1254 private Either<ZipOutputStream, ResponseFormat> writeArtifactsInfoToSpecifiedtPath(Component mainComponent, ArtifactsInfo currArtifactsInfo, ZipOutputStream zip, String path, boolean isInCertificationRequest) throws IOException {
1255 Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> artifactsInfo = currArtifactsInfo
1256 .getArtifactsInfo();
1257 Set<ArtifactGroupTypeEnum> groupTypeEnumKeySet = artifactsInfo.keySet();
1259 for (ArtifactGroupTypeEnum artifactGroupTypeEnum : groupTypeEnumKeySet) {
1260 String groupTypeFolder = path + WordUtils.capitalizeFully(artifactGroupTypeEnum.getType()) + "/";
1262 Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactTypesMap = artifactsInfo.get(artifactGroupTypeEnum);
1263 Set<ArtifactTypeEnum> artifactTypeEnumKeySet = artifactTypesMap.keySet();
1265 for (ArtifactTypeEnum artifactTypeEnum : artifactTypeEnumKeySet) {
1266 List<ArtifactDefinition> artifactDefinitionList = artifactTypesMap.get(artifactTypeEnum);
1267 String artifactTypeFolder = groupTypeFolder + artifactTypeEnum.toString() + "/";
1269 Either<ZipOutputStream, ResponseFormat> writeArtifactDefinition = writeArtifactDefinition(mainComponent, zip, artifactDefinitionList, artifactTypeFolder, isInCertificationRequest);
1271 if(writeArtifactDefinition.isRight()){
1272 return writeArtifactDefinition;
1277 return Either.left(zip);
1280 private Either<ZipOutputStream, ResponseFormat> writeArtifactDefinition(Component mainComponent, ZipOutputStream zip, List<ArtifactDefinition> artifactDefinitionList,
1281 String artifactPathAndFolder, boolean isInCertificationRequest) throws IOException {
1283 ComponentTypeEnum componentType = mainComponent.getComponentType();
1284 String heatEnvType = ArtifactTypeEnum.HEAT_ENV.getType();
1286 for (ArtifactDefinition artifactDefinition : artifactDefinitionList) {
1287 if (!isInCertificationRequest && componentType == ComponentTypeEnum.SERVICE
1288 && artifactDefinition.getArtifactType().equals(heatEnvType) ||
1289 //this is placeholder
1290 (artifactDefinition.getEsId() == null && artifactDefinition.getMandatory())){
1294 byte[] payloadData = artifactDefinition.getPayloadData();
1295 String artifactFileName = artifactDefinition.getArtifactName();
1297 if (payloadData == null) {
1298 Either<byte[], ActionStatus> fromCassandra = getFromCassandra(artifactDefinition.getEsId());
1300 if (fromCassandra.isRight()) {
1301 log.debug("ArtifactName {}, unique ID {}", artifactDefinition.getArtifactName(), artifactDefinition.getUniqueId());
1302 log.debug("Failed to get {} payload from DB reason: {}", artifactFileName, fromCassandra.right().value());
1305 payloadData = fromCassandra.left().value();
1307 zip.putNextEntry(new ZipEntry(artifactPathAndFolder + artifactFileName));
1308 zip.write(payloadData);
1311 return Either.left(zip);
1314 /************************************ Artifacts Structure ******************************************************************/
1316 * The artifacts Definition saved by their structure
1318 private class ArtifactsInfo {
1319 //Key is the type of artifacts(Informational/Deployment)
1320 //Value is a map between an artifact type and a list of all artifacts of this type
1321 private Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> artifactsInfoField;
1323 public ArtifactsInfo() {
1324 this.artifactsInfoField = new EnumMap<>(ArtifactGroupTypeEnum.class);
1327 public Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> getArtifactsInfo() {
1328 return artifactsInfoField;
1331 public List<ArtifactDefinition> getFlatArtifactsListByType(ArtifactTypeEnum artifactType){
1332 List<ArtifactDefinition> artifacts = new ArrayList<>();
1333 for (List<ArtifactDefinition> artifactsByType:artifactsInfoField.get(artifactType).values()){
1334 artifacts.addAll(artifactsByType);
1339 public void addArtifactsToGroup(ArtifactGroupTypeEnum artifactGroup,Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactsDefinition){
1340 artifactsInfoField.put(artifactGroup, artifactsDefinition);
1343 public boolean isEmpty() {
1344 return artifactsInfoField.isEmpty();
1350 * The artifacts of the component and of all its composed instances
1353 private class ComponentTypeArtifacts {
1354 private ArtifactsInfo componentArtifacts; //component artifacts (describes the Informational Deployment folders)
1355 private Map<String, ArtifactsInfo> componentInstancesArtifacts; //artifacts of the composed instances mapped by the resourceInstance normalized name (describes the Resources folder)
1357 public ComponentTypeArtifacts() {
1358 componentArtifacts = new ArtifactsInfo();
1359 componentInstancesArtifacts = new HashMap<>();
1362 public ArtifactsInfo getComponentArtifacts() {
1363 return componentArtifacts;
1365 public void setComponentArtifacts(ArtifactsInfo artifactsInfo) {
1366 this.componentArtifacts = artifactsInfo;
1368 public Map<String, ArtifactsInfo> getComponentInstancesArtifacts() {
1369 return componentInstancesArtifacts;
1371 public void setComponentInstancesArtifacts(Map<String, ArtifactsInfo> componentInstancesArtifacts) {
1372 this.componentInstancesArtifacts = componentInstancesArtifacts;
1375 public void addComponentInstancesArtifacts(String normalizedName, ArtifactsInfo artifactsInfo) {
1376 componentInstancesArtifacts.put(normalizedName, artifactsInfo);
1381 private class ComponentArtifacts {
1382 //artifacts of the component and CI's artifacts contained in it's composition (represents Informational, Deployment & Resource folders of main component)
1383 private ComponentTypeArtifacts mainTypeAndCIArtifacts;
1384 //artifacts of all component types mapped by their tosca name
1385 private Map<String, ComponentTypeArtifacts> componentTypeArtifacts;
1387 public ComponentArtifacts(){
1388 mainTypeAndCIArtifacts = new ComponentTypeArtifacts();
1389 componentTypeArtifacts = new HashMap<>();
1392 public ComponentTypeArtifacts getMainTypeAndCIArtifacts() {
1393 return mainTypeAndCIArtifacts;
1396 public void setMainTypeAndCIArtifacts(ComponentTypeArtifacts componentInstanceArtifacts) {
1397 this.mainTypeAndCIArtifacts = componentInstanceArtifacts;
1400 public Map<String, ComponentTypeArtifacts> getComponentTypeArtifacts() {
1401 return componentTypeArtifacts;
1404 public void setComponentTypeArtifacts(Map<String, ComponentTypeArtifacts> componentTypeArtifacts) {
1405 this.componentTypeArtifacts = componentTypeArtifacts;
1409 private class CsarDefinition {
1410 private ComponentArtifacts componentArtifacts;
1412 // add list of tosca artifacts and meta describes CSAR zip root
1414 public CsarDefinition(ComponentArtifacts componentArtifacts) {
1415 this.componentArtifacts = componentArtifacts;
1418 public ComponentArtifacts getComponentArtifacts() {
1419 return componentArtifacts;
1423 /************************************ Artifacts Structure END******************************************************************/
1425 private Either<CsarDefinition,ResponseFormat> collectComponentCsarDefinition(Component component){
1426 ComponentArtifacts componentArtifacts = new ComponentArtifacts();
1427 Component updatedComponent = component;
1429 //get service to receive the AII artifacts uploaded to the service
1430 if (updatedComponent.getComponentType() == ComponentTypeEnum.SERVICE) {
1431 Either<Service, StorageOperationStatus> getServiceResponse = toscaOperationFacade.getToscaElement(updatedComponent.getUniqueId());
1433 if(getServiceResponse.isRight()){
1434 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getServiceResponse.right().value());
1435 return Either.right(componentsUtils.getResponseFormat(actionStatus));
1438 updatedComponent = getServiceResponse.left().value();
1441 //find the artifacts of the main component, it would have its composed instances artifacts in a separate folder
1442 ComponentTypeArtifacts componentInstanceArtifacts = new ComponentTypeArtifacts();
1443 ArtifactsInfo artifactsInfo = collectComponentArtifacts(updatedComponent);
1444 componentInstanceArtifacts.setComponentArtifacts(artifactsInfo);
1445 componentArtifacts.setMainTypeAndCIArtifacts(componentInstanceArtifacts);
1447 Map<String,ComponentTypeArtifacts> resourceTypeArtifacts = componentArtifacts.getComponentTypeArtifacts(); //artifacts mapped by the component type(tosca name+version)
1448 //get the component instances
1449 List<ComponentInstance> componentInstances = updatedComponent.getComponentInstances();
1450 if (componentInstances!=null){
1451 for (ComponentInstance componentInstance:componentInstances){
1452 //call recursive to find artifacts for all the path
1453 Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts = collectComponentInstanceArtifacts(
1454 updatedComponent, componentInstance, resourceTypeArtifacts, componentInstanceArtifacts);
1455 if (collectComponentInstanceArtifacts.isRight()){
1456 return Either.right(collectComponentInstanceArtifacts.right().value());
1461 if(log.isDebugEnabled()){
1462 printResult(componentArtifacts,updatedComponent.getName());
1465 return Either.left(new CsarDefinition(componentArtifacts));
1468 private void printResult(ComponentArtifacts componentArtifacts, String name) {
1469 StringBuilder result = new StringBuilder();
1470 result.append("Artifacts of main component " + name + "\n");
1471 ComponentTypeArtifacts componentInstanceArtifacts = componentArtifacts.getMainTypeAndCIArtifacts();
1472 printArtifacts(componentInstanceArtifacts);
1473 result.append("Type Artifacts\n");
1474 for (Map.Entry<String, ComponentTypeArtifacts> typeArtifacts:componentArtifacts.getComponentTypeArtifacts().entrySet()){
1475 result.append("Folder " + typeArtifacts.getKey() + "\n");
1476 result.append(printArtifacts(typeArtifacts.getValue()));
1479 if(log.isDebugEnabled()){
1480 log.debug(result.toString());
1484 private String printArtifacts(ComponentTypeArtifacts componentInstanceArtifacts) {
1485 StringBuilder result = new StringBuilder();
1486 ArtifactsInfo artifactsInfo = componentInstanceArtifacts.getComponentArtifacts();
1487 Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> componetArtifacts = artifactsInfo.getArtifactsInfo();
1488 printArtifacts(componetArtifacts);
1489 result = result.append("Resources\n");
1490 for (Map.Entry<String, ArtifactsInfo> resourceInstance:componentInstanceArtifacts.getComponentInstancesArtifacts().entrySet()){
1491 result.append("Folder" + resourceInstance.getKey() + "\n");
1492 result.append(printArtifacts(resourceInstance.getValue().getArtifactsInfo()));
1495 return result.toString();
1498 private String printArtifacts(Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> componetArtifacts) {
1499 StringBuilder result = new StringBuilder();
1500 for (Map.Entry<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> artifactGroup:componetArtifacts.entrySet()){
1501 result.append(" " + artifactGroup.getKey().getType());
1502 for (Map.Entry<ArtifactTypeEnum, List<ArtifactDefinition>> groupArtifacts:artifactGroup.getValue().entrySet()){
1503 result.append(" " + groupArtifacts.getKey().getType());
1504 for (ArtifactDefinition artifact:groupArtifacts.getValue()){
1505 result.append(" " + artifact.getArtifactDisplayName());
1510 return result.toString();
1513 private ComponentTypeArtifacts collectComponentTypeArtifacts(Map<String, ComponentTypeArtifacts> resourcesArtifacts, ComponentInstance componentInstance,
1514 Resource fetchedComponent) {
1515 String toscaComponentName = componentInstance.getToscaComponentName() + "_v" + componentInstance.getComponentVersion();
1517 ComponentTypeArtifacts componentArtifactsInfo = resourcesArtifacts.get(toscaComponentName);
1518 //if there are no artifacts for this component type we need to fetch and build them
1519 if (componentArtifactsInfo==null){
1520 ArtifactsInfo componentArtifacts = collectComponentArtifacts(fetchedComponent);
1521 componentArtifactsInfo = new ComponentTypeArtifacts();
1522 if (!componentArtifacts.isEmpty()){
1523 componentArtifactsInfo.setComponentArtifacts(componentArtifacts);
1524 resourcesArtifacts.put(toscaComponentName, componentArtifactsInfo);
1527 return componentArtifactsInfo;
1530 private Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts(Component parentComponent,ComponentInstance componentInstance,
1531 Map<String, ComponentTypeArtifacts> resourcesTypeArtifacts,ComponentTypeArtifacts instanceArtifactsLocation) {
1532 //1. get the component instance component
1533 String componentUid = componentInstance.getComponentUid();
1534 Either<Resource, StorageOperationStatus> resource = toscaOperationFacade.getToscaElement(componentUid);
1535 if (resource.isRight()) {
1536 log.error("Failed to fetch resource with id {} for instance {}",componentUid, parentComponent.getUUID());
1537 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ASSET_NOT_FOUND_DURING_CSAR_CREATION,
1538 parentComponent.getComponentType().getValue(), parentComponent.getUUID(),
1539 componentInstance.getOriginType().getComponentType().getValue(), componentUid));
1541 Resource fetchedComponent = resource.left().value();
1543 //2. fill the artifacts for the current component parent type
1544 ComponentTypeArtifacts componentParentArtifacts = collectComponentTypeArtifacts(resourcesTypeArtifacts, componentInstance, fetchedComponent);
1546 //3. find the artifacts specific to the instance
1547 Map<ArtifactTypeEnum, List<ArtifactDefinition>> componentInstanceSpecificInformationalArtifacts =
1548 getComponentInstanceSpecificArtifacts(componentInstance.getArtifacts(),
1549 componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), ArtifactGroupTypeEnum.INFORMATIONAL);
1550 Map<ArtifactTypeEnum, List<ArtifactDefinition>> componentInstanceSpecificDeploymentArtifacts =
1551 getComponentInstanceSpecificArtifacts(componentInstance.getDeploymentArtifacts(),
1552 componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), ArtifactGroupTypeEnum.DEPLOYMENT);
1554 //4. add the instances artifacts to the component type
1555 ArtifactsInfo artifactsInfo = new ArtifactsInfo();
1556 if (!componentInstanceSpecificInformationalArtifacts.isEmpty()){
1557 artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.INFORMATIONAL, componentInstanceSpecificInformationalArtifacts);
1559 if (!componentInstanceSpecificDeploymentArtifacts.isEmpty()){
1560 artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, componentInstanceSpecificDeploymentArtifacts);
1562 if (!artifactsInfo.isEmpty()){
1563 instanceArtifactsLocation.addComponentInstancesArtifacts(componentInstance.getNormalizedName(), artifactsInfo);
1566 //5. do the same for all the component instances
1567 List<ComponentInstance> componentInstances = fetchedComponent.getComponentInstances();
1568 if (componentInstances!=null){
1569 for (ComponentInstance childComponentInstance:componentInstances){
1570 Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts = collectComponentInstanceArtifacts(
1571 fetchedComponent, childComponentInstance, resourcesTypeArtifacts, componentParentArtifacts);
1572 if (collectComponentInstanceArtifacts.isRight()){
1573 return collectComponentInstanceArtifacts;
1578 return Either.left(true);
1581 private Map<ArtifactTypeEnum, List<ArtifactDefinition>> getComponentInstanceSpecificArtifacts(Map<String, ArtifactDefinition> componentArtifacts,
1582 Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> componentTypeArtifacts, ArtifactGroupTypeEnum artifactGroupTypeEnum) {
1583 Map<ArtifactTypeEnum, List<ArtifactDefinition>> parentArtifacts = componentTypeArtifacts.get(artifactGroupTypeEnum); //the artfiacts of the component itself and not the instance
1585 Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactsByTypeOfComponentInstance = new EnumMap<>(ArtifactTypeEnum.class);
1586 if (componentArtifacts!=null){
1587 for (ArtifactDefinition artifact:componentArtifacts.values()){
1588 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifact.getArtifactType());
1589 List<ArtifactDefinition> parentArtifactsByType = null;
1590 if (parentArtifacts!=null){
1591 parentArtifactsByType = parentArtifacts.get(artifactType);
1593 //the artifact is of instance
1594 if (parentArtifactsByType == null || !parentArtifactsByType.contains(artifact)){
1595 List<ArtifactDefinition> typeArtifacts = artifactsByTypeOfComponentInstance.get(artifactType);
1596 if (typeArtifacts == null){
1597 typeArtifacts = new ArrayList<>();
1598 artifactsByTypeOfComponentInstance.put(artifactType, typeArtifacts);
1600 typeArtifacts.add(artifact);
1605 return artifactsByTypeOfComponentInstance;
1608 private ArtifactsInfo collectComponentArtifacts(Component component) {
1609 Map<String, ArtifactDefinition> informationalArtifacts = component.getArtifacts();
1610 Map<ArtifactTypeEnum, List<ArtifactDefinition>> informationalArtifactsByType = collectGroupArtifacts(informationalArtifacts);
1611 Map<String, ArtifactDefinition> deploymentArtifacts = component.getDeploymentArtifacts();
1612 Map<ArtifactTypeEnum, List<ArtifactDefinition>> deploymentArtifactsByType = collectGroupArtifacts(deploymentArtifacts);
1613 ArtifactsInfo artifactsInfo = new ArtifactsInfo();
1614 if (!informationalArtifactsByType.isEmpty()){
1615 artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.INFORMATIONAL, informationalArtifactsByType);
1617 if (!deploymentArtifactsByType.isEmpty() ){
1618 artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, deploymentArtifactsByType);
1621 return artifactsInfo;
1624 private Map<ArtifactTypeEnum, List<ArtifactDefinition>> collectGroupArtifacts(Map<String, ArtifactDefinition> componentArtifacts) {
1625 Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactsByType = new EnumMap<>(ArtifactTypeEnum.class);
1626 for (ArtifactDefinition artifact:componentArtifacts.values()){
1627 if (artifact.getArtifactUUID()!=null){
1628 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifact.getArtifactType());
1629 List<ArtifactDefinition> typeArtifacts = artifactsByType.get(artifactType);
1630 if (typeArtifacts==null){
1631 typeArtifacts = new ArrayList<>();
1632 artifactsByType.put(artifactType, typeArtifacts);
1634 typeArtifacts.add(artifact);
1637 return artifactsByType;