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;
24 import fj.data.Either;
25 import org.apache.commons.codec.binary.Base64;
26 import org.apache.commons.collections.MapUtils;
27 import org.apache.commons.io.output.ByteArrayOutputStream;
28 import org.apache.commons.lang.WordUtils;
29 import org.apache.commons.lang3.tuple.ImmutablePair;
30 import org.apache.commons.lang3.tuple.ImmutableTriple;
31 import org.apache.commons.lang3.tuple.Triple;
32 import org.openecomp.sdc.be.components.impl.ImportUtils;
33 import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig;
34 import org.openecomp.sdc.be.config.ConfigurationManager;
35 import org.openecomp.sdc.be.dao.api.ActionStatus;
36 import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao;
37 import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
38 import org.openecomp.sdc.be.dao.cassandra.SdcSchemaFilesCassandraDao;
39 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
40 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
41 import org.openecomp.sdc.be.impl.ComponentsUtils;
42 import org.openecomp.sdc.be.model.*;
43 import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
44 import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
45 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
46 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
47 import org.openecomp.sdc.be.resources.data.ESArtifactData;
48 import org.openecomp.sdc.be.resources.data.SdcSchemaFilesData;
49 import org.openecomp.sdc.be.tosca.model.ToscaTemplate;
50 import org.openecomp.sdc.be.tosca.utils.OperationArtifactUtil;
51 import org.openecomp.sdc.be.utils.CommonBeUtils;
52 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
53 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
54 import org.openecomp.sdc.common.impl.ExternalConfiguration;
55 import org.openecomp.sdc.common.log.wrappers.Logger;
56 import org.openecomp.sdc.common.util.GeneralUtility;
57 import org.openecomp.sdc.common.util.ValidationUtils;
58 import org.openecomp.sdc.exception.ResponseFormat;
59 import org.springframework.beans.factory.annotation.Autowired;
61 import java.io.BufferedOutputStream;
62 import java.io.ByteArrayInputStream;
64 import java.io.IOException;
66 import java.util.Map.Entry;
67 import java.util.regex.Matcher;
68 import java.util.regex.Pattern;
69 import java.util.zip.ZipEntry;
70 import java.util.zip.ZipInputStream;
71 import java.util.zip.ZipOutputStream;
76 @org.springframework.stereotype.Component("csar-utils")
77 public class CsarUtils {
78 private static final Logger log = Logger.getLogger(CsarUtils.class);
81 private SdcSchemaFilesCassandraDao sdcSchemaFilesCassandraDao;
83 private ArtifactCassandraDao artifactCassandraDao;
85 private ComponentsUtils componentsUtils;
87 private ToscaExportHandler toscaExportUtils;
89 protected ToscaOperationFacade toscaOperationFacade;
91 private String CONFORMANCE_LEVEL;
92 private String SDC_VERSION;
93 public static final Pattern UUID_NORMATIVE_NEW_VERSION = Pattern.compile("^\\d{1,}.0");
94 public static final String ARTIFACTS_PATH = "Artifacts/";
95 public static final String RESOURCES_PATH = "Resources/";
96 public static final String INFORMATIONAL_ARTIFACTS = "Informational/";
97 public static final String DEPLOYMENT_ARTIFACTS = "Deployment/";
99 public static final String DEFINITIONS_PATH = "Definitions/";
100 private static final String CSAR_META_VERSION = "1.0";
101 private static final String CSAR_META_PATH_FILE_NAME = "csar.meta";
102 private static final String TOSCA_META_PATH_FILE_NAME = "TOSCA-Metadata/TOSCA.meta";
103 private static final String TOSCA_META_VERSION = "1.0";
104 private static final String CSAR_VERSION = "1.1";
105 public static final String ARTIFACTS = "Artifacts";
106 private static final String DEFINITION = "Definitions";
107 private static final String DEL_PATTERN = "([/\\\\]+)";
108 private static String versionFirstThreeOctates;
110 public static final String VFC_NODE_TYPE_ARTIFACTS_PATH_PATTERN = ARTIFACTS + DEL_PATTERN
111 + ImportUtils.Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + "([\\d\\w\\_\\-\\.\\s]+)" + DEL_PATTERN
112 + "([\\d\\w\\_\\-\\.\\s]+)" + DEL_PATTERN + "([\\d\\w\\_\\-\\.\\s]+)" + DEL_PATTERN
113 + "([\\d\\w\\_\\-\\.\\s]+)";
115 public static final String VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN = ARTIFACTS + DEL_PATTERN +
116 // Artifact Group (i.e Deployment/Informational)
117 "([\\w\\_\\-\\.\\s]+)" + DEL_PATTERN +
119 "([\\w\\_\\-\\.\\s]+)" + DEL_PATTERN +
120 // Artifact Any File Name
122 public static final String VALID_ENGLISH_ARTIFACT_NAME = "([\\w\\_\\-\\.\\s]+)";
123 public static final String SERVICE_TEMPLATE_PATH_PATTERN = DEFINITION + DEL_PATTERN +
124 // Service Template File Name
125 "([\\w\\_\\-\\.\\s]+)";
127 public static final String ARTIFACT_CREATED_FROM_CSAR = "Artifact created from csar";
128 private static final String BLOCK_0_TEMPLATE = "SDC-TOSCA-Meta-File-Version: %s\nSDC-TOSCA-Definitions-Version: %s\n";
131 this.CONFORMANCE_LEVEL = ConfigurationManager.getConfigurationManager().getConfiguration()
132 .getToscaConformanceLevel();
133 this.SDC_VERSION = ExternalConfiguration.getAppVersion();
134 if (SDC_VERSION != null && !SDC_VERSION.isEmpty()) {
135 Matcher matcher = Pattern.compile("(?!\\.)(\\d+(\\.\\d+)+)(?![\\d\\.])").matcher(SDC_VERSION);
137 versionFirstThreeOctates = matcher.group(0);
139 versionFirstThreeOctates = "";
147 * @param isInCertificationRequest
150 public Either<byte[], ResponseFormat> createCsar(Component component, boolean getFromCS,
151 boolean isInCertificationRequest) {
152 return createCsar(component, getFromCS, isInCertificationRequest, false);
155 private Either<byte[], ResponseFormat> createCsar(Component component, boolean getFromCS,
156 boolean isInCertificationRequest, boolean mockGenerator) {
157 final String createdBy = component.getCreatorFullName();
160 Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
161 ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
162 fileName = artifactDefinition.getArtifactName();
164 String toscaConformanceLevel = ConfigurationManager.getConfigurationManager().getConfiguration()
165 .getToscaConformanceLevel();
166 String csarBlock0 = createCsarBlock0(CSAR_META_VERSION, toscaConformanceLevel);
167 byte[] csarBlock0Byte = csarBlock0.getBytes();
169 final String toscaBlock0 = createToscaBlock0(TOSCA_META_VERSION, CSAR_VERSION, createdBy, fileName);
170 byte[] toscaBlock0Byte = toscaBlock0.getBytes();
172 Either<byte[], ResponseFormat> generateCsarZipResponse = generateCsarZip(csarBlock0Byte, toscaBlock0Byte, component, getFromCS, isInCertificationRequest);
174 if (generateCsarZipResponse.isRight()) {
175 return Either.right(generateCsarZipResponse.right().value());
178 return Either.left(generateCsarZipResponse.left().value());
181 private Either<byte[], ResponseFormat> generateCsarZip(byte[] csarBlock0Byte, byte[] toscaBlock0Byte, Component component, boolean getFromCS, boolean isInCertificationRequest) {
182 try (ByteArrayOutputStream out = new ByteArrayOutputStream();
183 ZipOutputStream zip = new ZipOutputStream(out)) {
184 zip.putNextEntry(new ZipEntry(CSAR_META_PATH_FILE_NAME));
185 zip.write(csarBlock0Byte);
186 zip.putNextEntry(new ZipEntry(TOSCA_META_PATH_FILE_NAME));
187 zip.write(toscaBlock0Byte);
188 Either<ZipOutputStream, ResponseFormat> populateZip = populateZip(component, getFromCS, zip, isInCertificationRequest);
189 if (populateZip.isRight()) {
190 log.debug("Failed to populate CSAR zip file {}", populateZip.right().value());
191 return Either.right(populateZip.right().value());
195 byte[] byteArray = out.toByteArray();
197 return Either.left(byteArray);
198 } catch (IOException | NullPointerException e) {
199 log.debug("Failed with IOexception to create CSAR zip for component {}", component.getUniqueId(), e);
201 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
202 return Either.right(responseFormat);
206 private Either<ZipOutputStream, ResponseFormat> populateZip(Component component, boolean getFromCS, ZipOutputStream zip, boolean isInCertificationRequest) throws IOException {
208 LifecycleStateEnum lifecycleState = component.getLifecycleState();
209 String componentYaml;
210 Either<ToscaRepresentation, ToscaError> exportComponent;
212 // <file name, cassandraId, component>
213 List<Triple<String, String, Component>> dependencies = null;
215 Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
216 ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
217 String fileName = artifactDefinition.getArtifactName();
219 if (getFromCS || !(lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN
220 || lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) {
221 String cassandraId = artifactDefinition.getEsId();
222 Either<byte[], ActionStatus> fromCassandra = getFromCassandra(cassandraId);
223 if (fromCassandra.isRight()) {
224 log.debug("ArtifactName {}, unique ID {}", artifactDefinition.getArtifactName(),
225 artifactDefinition.getUniqueId());
226 ResponseFormat responseFormat = componentsUtils.getResponseFormat(fromCassandra.right().value());
227 return Either.right(responseFormat);
229 mainYaml = fromCassandra.left().value();
232 exportComponent = toscaExportUtils.exportComponent(component);
233 if (exportComponent.isRight()) {
234 log.debug("exportComponent failed", exportComponent.right().value());
235 ActionStatus convertedFromToscaError = componentsUtils
236 .convertFromToscaError(exportComponent.right().value());
237 ResponseFormat responseFormat = componentsUtils.getResponseFormat(convertedFromToscaError);
238 return Either.right(responseFormat);
240 ToscaRepresentation exportResult = exportComponent.left().value();
241 componentYaml = exportResult.getMainYaml();
242 mainYaml = componentYaml.getBytes();
243 dependencies = exportResult.getDependencies();
246 zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + fileName));
248 // US798487 - Abstraction of complex types
249 if (!ModelConverter.isAtomicComponent(component)) {
250 log.debug("Component {} is complex - generating abstract type for it..", component.getName());
251 writeComponentInterface(component, zip, fileName, false);
254 if (dependencies == null) {
255 Either<ToscaTemplate, ToscaError> dependenciesRes = toscaExportUtils.getDependencies(component);
256 if (dependenciesRes.isRight()) {
257 log.debug("Failed to retrieve dependencies for component {}, error {}", component.getUniqueId(),
258 dependenciesRes.right().value());
259 ActionStatus convertFromToscaError = componentsUtils
260 .convertFromToscaError(dependenciesRes.right().value());
261 ResponseFormat responseFormat = componentsUtils.getResponseFormat(convertFromToscaError);
262 return Either.right(responseFormat);
264 dependencies = dependenciesRes.left().value().getDependencies();
267 // UID <cassandraId,filename,component>
268 Map<String, ImmutableTriple<String, String, Component>> innerComponentsCache = new HashMap<>();
270 if (dependencies != null && !dependencies.isEmpty()) {
271 for (Triple<String, String, Component> d : dependencies) {
272 String cassandraId = d.getMiddle();
273 Component childComponent = d.getRight();
274 Either<byte[], ActionStatus> entryData = getEntryData(cassandraId, childComponent);
276 if (entryData.isRight()) {
277 ResponseFormat responseFormat = componentsUtils.getResponseFormat(entryData.right().value());
278 return Either.right(responseFormat);
281 // fill innerComponentsCache
282 fileName = d.getLeft();
283 addComponentToCache(innerComponentsCache, cassandraId, fileName, childComponent);
284 addInnerComponentsToCache(innerComponentsCache, childComponent);
287 // add inner components to CSAR
288 for (Entry<String, ImmutableTriple<String, String, Component>> innerComponentTripleEntry : innerComponentsCache
291 ImmutableTriple<String, String, Component> innerComponentTriple = innerComponentTripleEntry.getValue();
293 Component innerComponent = innerComponentTriple.getRight();
294 String icFileName = innerComponentTriple.getMiddle();
296 // add component to zip
297 Either<byte[], ActionStatus> entryData = getEntryData(innerComponentTriple.getLeft(), innerComponent);
298 if (entryData.isRight()) {
299 ResponseFormat responseFormat = componentsUtils.getResponseFormat(entryData.right().value());
300 log.debug("Failed adding to zip component {}, error {}", innerComponentTriple.getLeft(),
301 entryData.right().value());
302 return Either.right(responseFormat);
304 byte[] content = entryData.left().value();
305 zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + icFileName));
308 // add component interface to zip
309 if (!ModelConverter.isAtomicComponent(innerComponent)) {
310 writeComponentInterface(innerComponent, zip, icFileName, true);
315 // retrieve SDC.zip from Cassandra
316 Either<byte[], ResponseFormat> latestSchemaFilesFromCassandra = getLatestSchemaFilesFromCassandra();
318 if (latestSchemaFilesFromCassandra.isRight()) {
319 log.error("Error retrieving SDC Schema files from cassandra");
320 return Either.right(latestSchemaFilesFromCassandra.right().value());
323 // add files from retireved SDC.zip to Definitions folder in CSAR
324 Either<ZipOutputStream, ResponseFormat> addSchemaFilesFromCassandra = addSchemaFilesFromCassandra(zip,
325 latestSchemaFilesFromCassandra.left().value());
327 if (addSchemaFilesFromCassandra.isRight()) {
328 return addSchemaFilesFromCassandra;
331 Either<CsarDefinition, ResponseFormat> collectedComponentCsarDefinition = collectComponentCsarDefinition(
334 if (collectedComponentCsarDefinition.isRight()) {
335 return Either.right(collectedComponentCsarDefinition.right().value());
338 return writeAllFilesToCsar(component, collectedComponentCsarDefinition.left().value(), zip,
339 isInCertificationRequest);
342 private Either<ZipOutputStream, ResponseFormat> addSchemaFilesFromCassandra(ZipOutputStream zip,
343 byte[] schemaFileZip) {
345 final int initSize = 2048;
347 log.debug("Starting copy from Schema file zip to CSAR zip");
349 try (ZipInputStream zipStream = new ZipInputStream(new ByteArrayInputStream(schemaFileZip));
350 ByteArrayOutputStream out = new ByteArrayOutputStream();
351 BufferedOutputStream bos = new BufferedOutputStream(out, initSize)) {
354 while ((entry = zipStream.getNextEntry()) != null) {
356 String entryName = entry.getName();
357 int readSize = initSize;
358 byte[] entryData = new byte[initSize];
360 while ((readSize = zipStream.read(entryData, 0, readSize)) != -1) {
361 bos.write(entryData, 0, readSize);
366 zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + entryName));
367 zip.write(out.toByteArray());
371 } catch (IOException | NullPointerException e) {
372 log.error("Error while writing the SDC schema file to the CSAR {}", e);
373 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
376 log.debug("Finished coppy from Schema file zip to CSAR zip");
378 return Either.left(zip);
381 private void addInnerComponentsToCache(Map<String, ImmutableTriple<String, String, Component>> componentCache,
382 Component childComponent) {
384 List<ComponentInstance> instances = childComponent.getComponentInstances();
386 if (instances != null) {
387 instances.forEach(ci -> {
388 ImmutableTriple<String, String, Component> componentRecord = componentCache.get(ci.getComponentUid());
389 if (componentRecord == null) {
390 // all resource must be only once!
391 Either<Resource, StorageOperationStatus> resource = toscaOperationFacade
392 .getToscaElement(ci.getComponentUid());
393 if (resource == null || resource.isRight()) {
394 log.debug("Failed to fetch resource with id {} for instance {}", ci.getComponentUid(), ci.getName());
396 Component componentRI = resource.left().value();
398 Map<String, ArtifactDefinition> childToscaArtifacts = componentRI.getToscaArtifacts();
399 ArtifactDefinition childArtifactDefinition = childToscaArtifacts
400 .get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
401 if (childArtifactDefinition != null) {
403 addComponentToCache(componentCache, childArtifactDefinition.getEsId(),
404 childArtifactDefinition.getArtifactName(), componentRI);
407 // if not atomic - insert inner components as well
408 if (!ModelConverter.isAtomicComponent(componentRI)) {
409 addInnerComponentsToCache(componentCache, componentRI);
417 private void addComponentToCache(Map<String, ImmutableTriple<String, String, Component>> componentCache, String id,
418 String fileName, Component component) {
420 ImmutableTriple<String, String, Component> cachedComponent = componentCache.get(component.getInvariantUUID());
421 if (cachedComponent == null || CommonBeUtils.compareAsdcComponentVersions(component.getVersion(),
422 cachedComponent.getRight().getVersion())) {
423 componentCache.put(component.getInvariantUUID(),
424 new ImmutableTriple<>(id, fileName, component));
426 if (cachedComponent != null) {
427 // overwriting component with newer version
428 log.warn("Overwriting component invariantID {} of version {} with a newer version {}", id,
429 cachedComponent.getRight().getVersion(), component.getVersion());
434 private Either<ZipOutputStream, ResponseFormat> writeComponentInterface(Component component, ZipOutputStream zip,
435 String fileName, boolean isAssociatedComponent) {
437 Either<ToscaRepresentation, ToscaError> componentInterface = toscaExportUtils
438 .exportComponentInterface(component, isAssociatedComponent);
439 ToscaRepresentation componentInterfaceYaml = componentInterface.left().value();
440 String mainYaml = componentInterfaceYaml.getMainYaml();
441 String interfaceFileName = DEFINITIONS_PATH + ToscaExportHandler.getInterfaceFilename(fileName);
443 zip.putNextEntry(new ZipEntry(interfaceFileName));
444 zip.write(mainYaml.getBytes());
446 } catch (Exception e) {
447 log.error("#writeComponentInterface - zip writing failed with error: ", e);
448 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
451 return Either.left(zip);
454 private Either<byte[], ActionStatus> getEntryData(String cassandraId, Component childComponent) {
456 if (cassandraId == null || cassandraId.isEmpty()) {
457 Either<ToscaRepresentation, ToscaError> exportRes = toscaExportUtils.exportComponent(childComponent);
458 if (exportRes.isRight()) {
459 log.debug("Failed to export tosca template for child component {} error {}",
460 childComponent.getUniqueId(), exportRes.right().value());
461 return Either.right(componentsUtils.convertFromToscaError(exportRes.right().value()));
463 content = exportRes.left().value().getMainYaml().getBytes();
465 Either<byte[], ActionStatus> fromCassandra = getFromCassandra(cassandraId);
466 if (fromCassandra.isRight()) {
467 return Either.right(fromCassandra.right().value());
469 content = fromCassandra.left().value();
472 return Either.left(content);
475 private Either<byte[], ResponseFormat> getLatestSchemaFilesFromCassandra() {
476 Either<List<SdcSchemaFilesData>, CassandraOperationStatus> specificSchemaFiles = sdcSchemaFilesCassandraDao
477 .getSpecificSchemaFiles(versionFirstThreeOctates, CONFORMANCE_LEVEL);
479 if (specificSchemaFiles.isRight()) {
480 log.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}", versionFirstThreeOctates,
482 StorageOperationStatus storageStatus = DaoStatusConverter
483 .convertCassandraStatusToStorageStatus(specificSchemaFiles.right().value());
484 ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(storageStatus);
485 return Either.right(componentsUtils.getResponseFormat(convertedFromStorageResponse));
488 List<SdcSchemaFilesData> listOfSchemas = specificSchemaFiles.left().value();
490 if (listOfSchemas.isEmpty()) {
491 log.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}", versionFirstThreeOctates,
493 return Either.right(componentsUtils.getResponseFormat(ActionStatus.TOSCA_SCHEMA_FILES_NOT_FOUND,
494 versionFirstThreeOctates, CONFORMANCE_LEVEL));
497 SdcSchemaFilesData schemaFile = listOfSchemas.iterator().next();
499 return Either.left(schemaFile.getPayloadAsArray());
502 private Either<byte[], ActionStatus> getFromCassandra(String cassandraId) {
503 Either<ESArtifactData, CassandraOperationStatus> artifactResponse = artifactCassandraDao
504 .getArtifact(cassandraId);
506 if (artifactResponse.isRight()) {
507 log.debug("Failed to fetch artifact from Cassandra by id {} error {} ", cassandraId,
508 artifactResponse.right().value());
510 StorageOperationStatus storageStatus = DaoStatusConverter
511 .convertCassandraStatusToStorageStatus(artifactResponse.right().value());
512 ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(storageStatus);
513 return Either.right(convertedFromStorageResponse);
515 ESArtifactData artifactData = artifactResponse.left().value();
516 return Either.left(artifactData.getDataAsArray());
519 private String createCsarBlock0(String metaFileVersion, String toscaConformanceLevel) {
520 return String.format(BLOCK_0_TEMPLATE, metaFileVersion, toscaConformanceLevel);
523 private String createToscaBlock0(String metaFileVersion, String csarVersion, String createdBy, String entryDef) {
524 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";
525 return String.format(block0template, metaFileVersion, csarVersion, createdBy, entryDef);
529 * Extracts artifacts of VFCs from CSAR
532 * @return Map of <String, List<ArtifactDefinition>> the contains Lists of
533 * artifacts according vfcToscaNamespace
535 public static Map<String, List<ArtifactDefinition>> extractVfcsArtifactsFromCsar(Map<String, byte[]> csar) {
537 Map<String, List<ArtifactDefinition>> artifacts = new HashMap<>();
539 log.debug("************* Going to extract VFCs artifacts from Csar. ");
540 Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
541 csar.entrySet().stream()
542 // filter CSAR entry by node type artifact path
543 .filter(e -> Pattern.compile(VFC_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey()).matches())
544 // extract ArtifactDefinition from CSAR entry for each entry with matching
546 .forEach(e -> addExtractedVfcArtifact(extractVfcArtifact(e, collectedWarningMessages), artifacts));
547 // add counter suffix to artifact labels
548 handleWarningMessages(collectedWarningMessages);
555 * Print warnings to log
557 * @param collectedWarningMessages
559 public static void handleWarningMessages(Map<String, Set<List<String>>> collectedWarningMessages) {
560 collectedWarningMessages.entrySet().stream()
562 .forEach(e -> e.getValue().stream()
563 // add each warning message to log
564 .forEach(args -> log.warn(e.getKey(), args.toArray())));
568 private static void addExtractedVfcArtifact(ImmutablePair<String, ArtifactDefinition> extractedVfcArtifact,
569 Map<String, List<ArtifactDefinition>> artifacts) {
570 if (extractedVfcArtifact != null) {
571 List<ArtifactDefinition> currArtifactsList;
572 String vfcToscaNamespace = extractedVfcArtifact.getKey();
573 if (artifacts.containsKey(vfcToscaNamespace)) {
574 currArtifactsList = artifacts.get(vfcToscaNamespace);
576 currArtifactsList = new ArrayList<>();
577 artifacts.put(vfcToscaNamespace, currArtifactsList);
579 currArtifactsList.add(extractedVfcArtifact.getValue());
583 private static ImmutablePair<String, ArtifactDefinition> extractVfcArtifact(Entry<String, byte[]> entry,
584 Map<String, Set<List<String>>> collectedWarningMessages) {
585 ArtifactDefinition artifact;
586 String[] parsedCsarArtifactPath = entry.getKey().split("/");
587 Either<ArtifactGroupTypeEnum, Boolean> eitherArtifactGroupType = detectArtifactGroupType(
588 parsedCsarArtifactPath[2].toUpperCase(), collectedWarningMessages);
589 if (eitherArtifactGroupType.isLeft()) {
590 artifact = buildArtifactDefinitionFromCsarArtifactPath(entry, collectedWarningMessages,
591 parsedCsarArtifactPath, eitherArtifactGroupType.left().value());
595 return new ImmutablePair<>(parsedCsarArtifactPath[1], artifact);
598 private static Either<ArtifactGroupTypeEnum, Boolean> detectArtifactGroupType(String groupType,
599 Map<String, Set<List<String>>> collectedWarningMessages) {
600 Either<ArtifactGroupTypeEnum, Boolean> result;
602 ArtifactGroupTypeEnum artifactGroupType = ArtifactGroupTypeEnum.findType(groupType.toUpperCase());
603 if (artifactGroupType == null || (artifactGroupType != ArtifactGroupTypeEnum.INFORMATIONAL
604 && artifactGroupType != ArtifactGroupTypeEnum.DEPLOYMENT)) {
605 String warningMessage = "Warning - unrecognized artifact group type {} was received.";
606 List<String> messageArguments = new ArrayList<>();
607 messageArguments.add(groupType);
608 if (!collectedWarningMessages.containsKey(warningMessage)) {
609 Set<List<String>> messageArgumentLists = new HashSet<>();
610 messageArgumentLists.add(messageArguments);
611 collectedWarningMessages.put(warningMessage, messageArgumentLists);
613 collectedWarningMessages.get(warningMessage).add(messageArguments);
616 result = Either.right(false);
619 result = Either.left(artifactGroupType);
621 } catch (Exception e) {
622 log.debug("detectArtifactGroupType failed with exception", e);
623 result = Either.right(false);
628 private static ArtifactDefinition buildArtifactDefinitionFromCsarArtifactPath(Entry<String, byte[]> entry,
629 Map<String, Set<List<String>>> collectedWarningMessages, String[] parsedCsarArtifactPath,
630 ArtifactGroupTypeEnum artifactGroupType) {
631 ArtifactDefinition artifact;
632 artifact = new ArtifactDefinition();
633 artifact.setArtifactGroupType(artifactGroupType);
634 artifact.setArtifactType(detectArtifactTypeVFC(artifactGroupType, parsedCsarArtifactPath[3],
635 parsedCsarArtifactPath[1], collectedWarningMessages));
636 artifact.setArtifactName(
637 ValidationUtils.normalizeFileName(parsedCsarArtifactPath[parsedCsarArtifactPath.length - 1]));
638 artifact.setPayloadData(Base64.encodeBase64String(entry.getValue()));
639 artifact.setArtifactDisplayName(artifact.getArtifactName().lastIndexOf('.') > 0
640 ? artifact.getArtifactName().substring(0, artifact.getArtifactName().lastIndexOf('.'))
641 : artifact.getArtifactName());
642 artifact.setArtifactLabel(ValidationUtils.normalizeArtifactLabel(artifact.getArtifactName()));
643 artifact.setDescription(ARTIFACT_CREATED_FROM_CSAR);
644 artifact.setIsFromCsar(true);
645 artifact.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(entry.getValue()));
649 public static final class NonMetaArtifactInfo {
650 private final String path;
651 private final String artifactName;
652 private final String displayName;
653 private final String artifactLabel;
654 private final ArtifactTypeEnum artifactType;
655 private final ArtifactGroupTypeEnum artifactGroupType;
656 private String payloadData;
657 private String artifactChecksum;
658 private String artifactUniqueId;
659 private final boolean isFromCsar;
661 public NonMetaArtifactInfo(String artifactName, String path, ArtifactTypeEnum artifactType,
662 ArtifactGroupTypeEnum artifactGroupType, byte[] payloadData, String artifactUniqueId,
663 boolean isFromCsar) {
666 this.isFromCsar = isFromCsar;
667 this.artifactName = ValidationUtils.normalizeFileName(artifactName);
668 this.artifactType = artifactType;
669 this.artifactGroupType = artifactGroupType;
670 final int pointIndex = artifactName.lastIndexOf('.');
671 if (pointIndex > 0) {
672 displayName = artifactName.substring(0, pointIndex);
674 displayName = artifactName;
676 this.artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactName);
677 if (payloadData != null) {
678 this.payloadData = Base64.encodeBase64String(payloadData);
679 this.artifactChecksum = GeneralUtility.calculateMD5Base64EncodedByByteArray(payloadData);
681 this.artifactUniqueId = artifactUniqueId;
684 public String getPath() {
688 public String getArtifactName() {
692 public ArtifactTypeEnum getArtifactType() {
696 public String getDisplayName() {
700 public ArtifactGroupTypeEnum getArtifactGroupType() {
701 return artifactGroupType;
704 public String getArtifactLabel() {
705 return artifactLabel;
708 public boolean isFromCsar() {
712 public String getPayloadData() {
716 public String getArtifactChecksum() {
717 return artifactChecksum;
720 public String getArtifactUniqueId() {
721 return artifactUniqueId;
724 public void setArtifactUniqueId(String artifactUniqueId) {
725 this.artifactUniqueId = artifactUniqueId;
731 * This method checks the artifact GroupType & Artifact Type. <br>
732 * if there is any problem warning messages are added to
733 * collectedWarningMessages
735 * @param artifactPath
736 * @param collectedWarningMessages
739 public static Either<NonMetaArtifactInfo, Boolean> validateNonMetaArtifact(String artifactPath, byte[] payloadData,
740 Map<String, Set<List<String>>> collectedWarningMessages) {
741 Either<NonMetaArtifactInfo, Boolean> ret;
743 String[] parsedArtifactPath = artifactPath.split("/");
744 // Validate Artifact Group Type
745 Either<ArtifactGroupTypeEnum, Boolean> eitherGroupType = detectArtifactGroupType(parsedArtifactPath[1],
746 collectedWarningMessages);
747 if (eitherGroupType.isLeft()) {
748 final ArtifactGroupTypeEnum groupTypeEnum = eitherGroupType.left().value();
750 // Validate Artifact Type
751 String artifactType = parsedArtifactPath[2];
752 artifactType = detectArtifactTypeVF(groupTypeEnum, artifactType, collectedWarningMessages);
754 String artifactFileNameType = parsedArtifactPath[3];
755 ret = Either.left(new NonMetaArtifactInfo(artifactFileNameType, artifactPath,
756 ArtifactTypeEnum.findType(artifactType), groupTypeEnum, payloadData, null, true));
759 ret = Either.right(eitherGroupType.right().value());
761 } catch (Exception e) {
762 log.debug("detectArtifactGroupType failed with exception", e);
763 ret = Either.right(false);
769 private static String detectArtifactTypeVFC(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName,
770 String parentVfName, Map<String, Set<List<String>>> collectedWarningMessages) {
771 String warningMessage = "Warning - artifact type {} that was provided for VFC {} is not recognized.";
772 return detectArtifactType(artifactGroupType, receivedTypeName, warningMessage, collectedWarningMessages,
776 private static String detectArtifactTypeVF(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName,
777 Map<String, Set<List<String>>> collectedWarningMessages) {
778 String warningMessage = "Warning - artifact type {} that was provided for VF is not recognized.";
779 return detectArtifactType(artifactGroupType, receivedTypeName, warningMessage, collectedWarningMessages);
782 private static String detectArtifactType(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName,
783 String warningMessage, Map<String, Set<List<String>>> collectedWarningMessages, String... arguments) {
785 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(receivedTypeName);
786 Map<String, ArtifactTypeConfig> resourceValidTypeArtifacts = null;
788 if (artifactGroupType != null) {
789 switch (artifactGroupType) {
791 resourceValidTypeArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration()
792 .getResourceInformationalArtifacts();
795 resourceValidTypeArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration()
796 .getResourceDeploymentArtifacts();
803 Set<String> validArtifactTypes = null;
804 if (resourceValidTypeArtifacts != null) {
805 validArtifactTypes = resourceValidTypeArtifacts.keySet();
808 if (validArtifactTypes == null || artifactType == null
809 || !validArtifactTypes.contains(artifactType.getType())) {
810 List<String> messageArguments = new ArrayList<>();
811 messageArguments.add(receivedTypeName);
812 messageArguments.addAll(Arrays.asList(arguments));
813 if (!collectedWarningMessages.containsKey(warningMessage)) {
814 Set<List<String>> messageArgumentLists = new HashSet<>();
815 messageArgumentLists.add(messageArguments);
816 collectedWarningMessages.put(warningMessage, messageArgumentLists);
818 collectedWarningMessages.get(warningMessage).add(messageArguments);
822 return artifactType == null ? ArtifactTypeEnum.OTHER.getType() : artifactType.getType();
825 private Either<ZipOutputStream, ResponseFormat> writeAllFilesToCsar(Component mainComponent,
826 CsarDefinition csarDefinition, ZipOutputStream zipstream, boolean isInCertificationRequest)
828 ComponentArtifacts componentArtifacts = csarDefinition.getComponentArtifacts();
830 Either<ZipOutputStream, ResponseFormat> writeComponentArtifactsToSpecifiedPath = writeComponentArtifactsToSpecifiedPath(
831 mainComponent, componentArtifacts, zipstream, ARTIFACTS_PATH, isInCertificationRequest);
833 if (writeComponentArtifactsToSpecifiedPath.isRight()) {
834 return Either.right(writeComponentArtifactsToSpecifiedPath.right().value());
837 ComponentTypeArtifacts mainTypeAndCIArtifacts = componentArtifacts.getMainTypeAndCIArtifacts();
838 writeComponentArtifactsToSpecifiedPath = writeArtifactsInfoToSpecifiedPath(mainComponent,
839 mainTypeAndCIArtifacts.getComponentArtifacts(), zipstream, ARTIFACTS_PATH, isInCertificationRequest);
841 if (writeComponentArtifactsToSpecifiedPath.isRight()) {
842 return Either.right(writeComponentArtifactsToSpecifiedPath.right().value());
845 Map<String, ArtifactsInfo> componentInstancesArtifacts = mainTypeAndCIArtifacts
846 .getComponentInstancesArtifacts();
847 Set<String> keySet = componentInstancesArtifacts.keySet();
849 String currentPath = ARTIFACTS_PATH + RESOURCES_PATH;
850 for (String keyAssetName : keySet) {
851 ArtifactsInfo artifactsInfo = componentInstancesArtifacts.get(keyAssetName);
852 String pathWithAssetName = currentPath + keyAssetName + "/";
853 writeComponentArtifactsToSpecifiedPath = writeArtifactsInfoToSpecifiedPath(mainComponent, artifactsInfo,
854 zipstream, pathWithAssetName, isInCertificationRequest);
856 if (writeComponentArtifactsToSpecifiedPath.isRight()) {
857 return Either.right(writeComponentArtifactsToSpecifiedPath.right().value());
860 return Either.left(zipstream);
863 private Either<ZipOutputStream, ResponseFormat> writeComponentArtifactsToSpecifiedPath(Component mainComponent,
864 ComponentArtifacts componentArtifacts, ZipOutputStream zipstream, String currentPath,
865 boolean isInCertificationRequest) throws IOException {
866 Map<String, ComponentTypeArtifacts> componentTypeArtifacts = componentArtifacts.getComponentTypeArtifacts();
868 // <Inner Asset TOSCA name (e.g. VFC name)> folder name: <Inner Asset TOSCA name
869 // (e.g. VFC name)>_v<version>.
870 // E.g. "org.openecomp.resource.vf.vipr_atm_v1.0"
871 Set<String> componentTypeArtifactsKeys = componentTypeArtifacts.keySet();
872 for (String keyAssetName : componentTypeArtifactsKeys) {
873 ComponentTypeArtifacts componentInstanceArtifacts = componentTypeArtifacts.get(keyAssetName);
874 ArtifactsInfo componentArtifacts2 = componentInstanceArtifacts.getComponentArtifacts();
875 String pathWithAssetName = currentPath + keyAssetName + "/";
876 Either<ZipOutputStream, ResponseFormat> writeArtifactsInfoToSpecifiedPath = writeArtifactsInfoToSpecifiedPath(
877 mainComponent, componentArtifacts2, zipstream, pathWithAssetName, isInCertificationRequest);
879 if (writeArtifactsInfoToSpecifiedPath.isRight()) {
880 return writeArtifactsInfoToSpecifiedPath;
884 return Either.left(zipstream);
887 private Either<ZipOutputStream, ResponseFormat> writeArtifactsInfoToSpecifiedPath(Component mainComponent,
888 ArtifactsInfo currArtifactsInfo, ZipOutputStream zip, String path, boolean isInCertificationRequest)
890 Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> artifactsInfo = currArtifactsInfo
892 Set<ArtifactGroupTypeEnum> groupTypeEnumKeySet = artifactsInfo.keySet();
894 for (ArtifactGroupTypeEnum artifactGroupTypeEnum : groupTypeEnumKeySet) {
895 String groupTypeFolder = path + WordUtils.capitalizeFully(artifactGroupTypeEnum.getType()) + File.separator;
897 Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactTypesMap = artifactsInfo.get(artifactGroupTypeEnum);
898 Set<ArtifactTypeEnum> artifactTypeEnumKeySet = artifactTypesMap.keySet();
900 for (ArtifactTypeEnum artifactTypeEnum : artifactTypeEnumKeySet) {
901 List<ArtifactDefinition> artifactDefinitionList = artifactTypesMap.get(artifactTypeEnum);
902 String artifactTypeFolder = groupTypeFolder + artifactTypeEnum.toString() + File.separator;
904 if(artifactTypeEnum == ArtifactTypeEnum.WORKFLOW && path.contains(ARTIFACTS_PATH + RESOURCES_PATH)){
905 // Ignore this packaging as BPMN artifacts needs to be packaged in different manner
908 if (artifactTypeEnum == ArtifactTypeEnum.WORKFLOW) {
909 artifactTypeFolder += OperationArtifactUtil.BPMN_ARTIFACT_PATH + File.separator;
912 Either<ZipOutputStream, ResponseFormat> writeArtifactDefinition = writeArtifactDefinition(mainComponent,
913 zip, artifactDefinitionList, artifactTypeFolder, isInCertificationRequest);
915 if (writeArtifactDefinition.isRight()) {
916 return writeArtifactDefinition;
921 return Either.left(zip);
924 private Either<ZipOutputStream, ResponseFormat> writeArtifactDefinition(Component mainComponent,
925 ZipOutputStream zip, List<ArtifactDefinition> artifactDefinitionList, String artifactPathAndFolder,
926 boolean isInCertificationRequest) throws IOException {
928 ComponentTypeEnum componentType = mainComponent.getComponentType();
929 String heatEnvType = ArtifactTypeEnum.HEAT_ENV.getType();
931 for (ArtifactDefinition artifactDefinition : artifactDefinitionList) {
932 if (!isInCertificationRequest && componentType == ComponentTypeEnum.SERVICE
933 && artifactDefinition.getArtifactType().equals(heatEnvType) ||
934 // this is placeholder
935 (artifactDefinition.getEsId() == null && artifactDefinition.getMandatory())) {
939 byte[] payloadData = artifactDefinition.getPayloadData();
940 String artifactFileName = artifactDefinition.getArtifactName();
942 if (payloadData == null) {
943 Either<byte[], ActionStatus> fromCassandra = getFromCassandra(artifactDefinition.getEsId());
945 if (fromCassandra.isRight()) {
946 log.debug("ArtifactName {}, unique ID {}", artifactDefinition.getArtifactName(),
947 artifactDefinition.getUniqueId());
948 log.debug("Failed to get {} payload from DB reason: {}", artifactFileName,
949 fromCassandra.right().value());
952 payloadData = fromCassandra.left().value();
954 zip.putNextEntry(new ZipEntry(artifactPathAndFolder + artifactFileName));
955 zip.write(payloadData);
958 return Either.left(zip);
961 /************************************
962 * Artifacts Structure
963 ******************************************************************/
965 * The artifacts Definition saved by their structure
967 private class ArtifactsInfo {
968 // Key is the type of artifacts(Informational/Deployment)
969 // Value is a map between an artifact type and a list of all artifacts of this
971 private Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> artifactsInfoField;
973 public ArtifactsInfo() {
974 this.artifactsInfoField = new EnumMap<>(ArtifactGroupTypeEnum.class);
977 public Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> getArtifactsInfo() {
978 return artifactsInfoField;
981 public List<ArtifactDefinition> getFlatArtifactsListByType(ArtifactTypeEnum artifactType) {
982 List<ArtifactDefinition> artifacts = new ArrayList<>();
983 for (List<ArtifactDefinition> artifactsByType : artifactsInfoField.get(artifactType).values()) {
984 artifacts.addAll(artifactsByType);
989 public void addArtifactsToGroup(ArtifactGroupTypeEnum artifactGroup,
990 Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactsDefinition) {
991 if (artifactsInfoField.get(artifactGroup) == null) {
992 artifactsInfoField.put(artifactGroup, artifactsDefinition);
994 Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactTypeEnumListMap =
995 artifactsInfoField.get(artifactGroup);
996 artifactTypeEnumListMap.putAll(artifactsDefinition);
997 artifactsInfoField.put(artifactGroup, artifactTypeEnumListMap);
1002 public boolean isEmpty() {
1003 return artifactsInfoField.isEmpty();
1009 * The artifacts of the component and of all its composed instances
1012 private class ComponentTypeArtifacts {
1013 private ArtifactsInfo componentArtifacts; // component artifacts (describes the Informational Deployment
1015 private Map<String, ArtifactsInfo> componentInstancesArtifacts; // artifacts of the composed instances mapped by
1016 // the resourceInstance normalized name
1017 // (describes the Resources folder)
1019 public ComponentTypeArtifacts() {
1020 componentArtifacts = new ArtifactsInfo();
1021 componentInstancesArtifacts = new HashMap<>();
1024 public ArtifactsInfo getComponentArtifacts() {
1025 return componentArtifacts;
1028 public void setComponentArtifacts(ArtifactsInfo artifactsInfo) {
1029 this.componentArtifacts = artifactsInfo;
1032 public Map<String, ArtifactsInfo> getComponentInstancesArtifacts() {
1033 return componentInstancesArtifacts;
1036 public void setComponentInstancesArtifacts(Map<String, ArtifactsInfo> componentInstancesArtifacts) {
1037 this.componentInstancesArtifacts = componentInstancesArtifacts;
1040 public void addComponentInstancesArtifacts(String normalizedName, ArtifactsInfo artifactsInfo) {
1041 componentInstancesArtifacts.put(normalizedName, artifactsInfo);
1046 private class ComponentArtifacts {
1047 // artifacts of the component and CI's artifacts contained in it's composition
1048 // (represents Informational, Deployment & Resource folders of main component)
1049 private ComponentTypeArtifacts mainTypeAndCIArtifacts;
1050 // artifacts of all component types mapped by their tosca name
1051 private Map<String, ComponentTypeArtifacts> componentTypeArtifacts;
1053 public ComponentArtifacts() {
1054 mainTypeAndCIArtifacts = new ComponentTypeArtifacts();
1055 componentTypeArtifacts = new HashMap<>();
1058 public ComponentTypeArtifacts getMainTypeAndCIArtifacts() {
1059 return mainTypeAndCIArtifacts;
1062 public void setMainTypeAndCIArtifacts(ComponentTypeArtifacts componentInstanceArtifacts) {
1063 this.mainTypeAndCIArtifacts = componentInstanceArtifacts;
1066 public Map<String, ComponentTypeArtifacts> getComponentTypeArtifacts() {
1067 return componentTypeArtifacts;
1070 public void setComponentTypeArtifacts(Map<String, ComponentTypeArtifacts> componentTypeArtifacts) {
1071 this.componentTypeArtifacts = componentTypeArtifacts;
1075 private class CsarDefinition {
1076 private ComponentArtifacts componentArtifacts;
1078 // add list of tosca artifacts and meta describes CSAR zip root
1080 public CsarDefinition(ComponentArtifacts componentArtifacts) {
1081 this.componentArtifacts = componentArtifacts;
1084 public ComponentArtifacts getComponentArtifacts() {
1085 return componentArtifacts;
1089 /************************************
1090 * Artifacts Structure END
1091 ******************************************************************/
1093 private Either<CsarDefinition, ResponseFormat> collectComponentCsarDefinition(Component component) {
1094 ComponentArtifacts componentArtifacts = new ComponentArtifacts();
1095 Component updatedComponent = component;
1097 // get service to receive the AII artifacts uploaded to the service
1098 if (updatedComponent.getComponentType() == ComponentTypeEnum.SERVICE) {
1099 Either<Service, StorageOperationStatus> getServiceResponse = toscaOperationFacade
1100 .getToscaElement(updatedComponent.getUniqueId());
1102 if (getServiceResponse.isRight()) {
1103 ActionStatus actionStatus = componentsUtils
1104 .convertFromStorageResponse(getServiceResponse.right().value());
1105 return Either.right(componentsUtils.getResponseFormat(actionStatus));
1108 updatedComponent = getServiceResponse.left().value();
1111 // find the artifacts of the main component, it would have its composed
1112 // instances artifacts in a separate folder
1113 ComponentTypeArtifacts componentInstanceArtifacts = new ComponentTypeArtifacts();
1114 ArtifactsInfo artifactsInfo = collectComponentArtifacts(updatedComponent);
1115 componentInstanceArtifacts.setComponentArtifacts(artifactsInfo);
1116 componentArtifacts.setMainTypeAndCIArtifacts(componentInstanceArtifacts);
1118 Map<String, ComponentTypeArtifacts> resourceTypeArtifacts = componentArtifacts.getComponentTypeArtifacts(); // artifacts
1125 // get the component instances
1126 List<ComponentInstance> componentInstances = updatedComponent.getComponentInstances();
1127 if (componentInstances != null) {
1128 for (ComponentInstance componentInstance : componentInstances) {
1129 // call recursive to find artifacts for all the path
1130 Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts = collectComponentInstanceArtifacts(
1131 updatedComponent, componentInstance, resourceTypeArtifacts, componentInstanceArtifacts);
1132 if (collectComponentInstanceArtifacts.isRight()) {
1133 return Either.right(collectComponentInstanceArtifacts.right().value());
1138 if (log.isDebugEnabled()) {
1139 printResult(componentArtifacts, updatedComponent.getName());
1142 return Either.left(new CsarDefinition(componentArtifacts));
1145 private void printResult(ComponentArtifacts componentArtifacts, String name) {
1146 StringBuilder result = new StringBuilder();
1147 result.append("Artifacts of main component " + name + "\n");
1148 ComponentTypeArtifacts componentInstanceArtifacts = componentArtifacts.getMainTypeAndCIArtifacts();
1149 printArtifacts(componentInstanceArtifacts);
1150 result.append("Type Artifacts\n");
1151 for (Map.Entry<String, ComponentTypeArtifacts> typeArtifacts : componentArtifacts.getComponentTypeArtifacts()
1153 result.append("Folder " + typeArtifacts.getKey() + "\n");
1154 result.append(printArtifacts(typeArtifacts.getValue()));
1157 if (log.isDebugEnabled()) {
1158 log.debug(result.toString());
1162 private String printArtifacts(ComponentTypeArtifacts componentInstanceArtifacts) {
1163 StringBuilder result = new StringBuilder();
1164 ArtifactsInfo artifactsInfo = componentInstanceArtifacts.getComponentArtifacts();
1165 Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> componetArtifacts = artifactsInfo
1166 .getArtifactsInfo();
1167 printArtifacts(componetArtifacts);
1168 result = result.append("Resources\n");
1169 for (Map.Entry<String, ArtifactsInfo> resourceInstance : componentInstanceArtifacts
1170 .getComponentInstancesArtifacts().entrySet()) {
1171 result.append("Folder" + resourceInstance.getKey() + "\n");
1172 result.append(printArtifacts(resourceInstance.getValue().getArtifactsInfo()));
1175 return result.toString();
1178 private String printArtifacts(
1179 Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> componetArtifacts) {
1180 StringBuilder result = new StringBuilder();
1181 for (Map.Entry<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> artifactGroup : componetArtifacts
1183 result.append(" " + artifactGroup.getKey().getType());
1184 for (Map.Entry<ArtifactTypeEnum, List<ArtifactDefinition>> groupArtifacts : artifactGroup.getValue()
1186 result.append(" " + groupArtifacts.getKey().getType());
1187 for (ArtifactDefinition artifact : groupArtifacts.getValue()) {
1188 result.append(" " + artifact.getArtifactDisplayName());
1193 return result.toString();
1196 private ComponentTypeArtifacts collectComponentTypeArtifacts(Map<String, ComponentTypeArtifacts> resourcesArtifacts,
1197 ComponentInstance componentInstance, Component fetchedComponent) {
1198 String toscaComponentName = componentInstance.getToscaComponentName() + "_v"
1199 + componentInstance.getComponentVersion();
1201 ComponentTypeArtifacts componentArtifactsInfo = resourcesArtifacts.get(toscaComponentName);
1202 // if there are no artifacts for this component type we need to fetch and build
1204 if (componentArtifactsInfo == null) {
1205 ArtifactsInfo componentArtifacts = collectComponentArtifacts(fetchedComponent);
1206 componentArtifactsInfo = new ComponentTypeArtifacts();
1207 if (!componentArtifacts.isEmpty()) {
1208 componentArtifactsInfo.setComponentArtifacts(componentArtifacts);
1209 resourcesArtifacts.put(toscaComponentName, componentArtifactsInfo);
1212 return componentArtifactsInfo;
1215 private Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts(Component parentComponent,
1216 ComponentInstance componentInstance, Map<String, ComponentTypeArtifacts> resourcesTypeArtifacts,
1217 ComponentTypeArtifacts instanceArtifactsLocation) {
1218 // 1. get the component instance component
1219 String componentUid;
1220 if (componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy) {
1221 componentUid = componentInstance.getSourceModelUid();
1224 componentUid = componentInstance.getComponentUid();
1226 Either<Component, StorageOperationStatus> component = toscaOperationFacade.getToscaElement(componentUid);
1227 if (component.isRight()) {
1228 log.error("Failed to fetch resource with id {} for instance {}", componentUid, parentComponent.getUUID());
1229 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ASSET_NOT_FOUND_DURING_CSAR_CREATION,
1230 parentComponent.getComponentType().getValue(), parentComponent.getUUID(),
1231 componentInstance.getOriginType().getComponentType().getValue(), componentUid));
1233 Component fetchedComponent = component.left().value();
1235 // 2. fill the artifacts for the current component parent type
1236 ComponentTypeArtifacts componentParentArtifacts = collectComponentTypeArtifacts(resourcesTypeArtifacts,
1237 componentInstance, fetchedComponent);
1239 // 3. find the artifacts specific to the instance
1240 Map<ArtifactTypeEnum, List<ArtifactDefinition>> componentInstanceSpecificInformationalArtifacts = getComponentInstanceSpecificArtifacts(
1241 componentInstance.getArtifacts(), componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(),
1242 ArtifactGroupTypeEnum.INFORMATIONAL);
1243 Map<ArtifactTypeEnum, List<ArtifactDefinition>> componentInstanceSpecificDeploymentArtifacts = getComponentInstanceSpecificArtifacts(
1244 componentInstance.getDeploymentArtifacts(),
1245 componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), ArtifactGroupTypeEnum.DEPLOYMENT);
1247 // 4. add the instances artifacts to the component type
1248 ArtifactsInfo artifactsInfo = new ArtifactsInfo();
1249 if (!componentInstanceSpecificInformationalArtifacts.isEmpty()) {
1250 artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.INFORMATIONAL,
1251 componentInstanceSpecificInformationalArtifacts);
1253 if (!componentInstanceSpecificDeploymentArtifacts.isEmpty()) {
1254 artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT,
1255 componentInstanceSpecificDeploymentArtifacts);
1257 if (!artifactsInfo.isEmpty()) {
1258 instanceArtifactsLocation.addComponentInstancesArtifacts(componentInstance.getNormalizedName(),
1262 // 5. do the same for all the component instances
1263 List<ComponentInstance> componentInstances = fetchedComponent.getComponentInstances();
1264 if (componentInstances != null) {
1265 for (ComponentInstance childComponentInstance : componentInstances) {
1266 Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts = collectComponentInstanceArtifacts(
1267 fetchedComponent, childComponentInstance, resourcesTypeArtifacts, componentParentArtifacts);
1268 if (collectComponentInstanceArtifacts.isRight()) {
1269 return collectComponentInstanceArtifacts;
1274 return Either.left(true);
1277 private Map<ArtifactTypeEnum, List<ArtifactDefinition>> getComponentInstanceSpecificArtifacts(
1278 Map<String, ArtifactDefinition> componentArtifacts,
1279 Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> componentTypeArtifacts,
1280 ArtifactGroupTypeEnum artifactGroupTypeEnum) {
1281 Map<ArtifactTypeEnum, List<ArtifactDefinition>> parentArtifacts = componentTypeArtifacts
1282 .get(artifactGroupTypeEnum); // the artfiacts of the component itself and not the instance
1284 Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactsByTypeOfComponentInstance = new EnumMap<>(
1285 ArtifactTypeEnum.class);
1286 if (componentArtifacts != null) {
1287 for (ArtifactDefinition artifact : componentArtifacts.values()) {
1288 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifact.getArtifactType());
1289 List<ArtifactDefinition> parentArtifactsByType = null;
1290 if (parentArtifacts != null) {
1291 parentArtifactsByType = parentArtifacts.get(artifactType);
1293 // the artifact is of instance
1294 if (parentArtifactsByType == null || !parentArtifactsByType.contains(artifact)) {
1295 List<ArtifactDefinition> typeArtifacts = artifactsByTypeOfComponentInstance.get(artifactType);
1296 if (typeArtifacts == null) {
1297 typeArtifacts = new ArrayList<>();
1298 artifactsByTypeOfComponentInstance.put(artifactType, typeArtifacts);
1300 typeArtifacts.add(artifact);
1305 return artifactsByTypeOfComponentInstance;
1308 private ArtifactsInfo collectComponentArtifacts(Component component) {
1309 Map<String, ArtifactDefinition> informationalArtifacts = component.getArtifacts();
1310 Map<ArtifactTypeEnum, List<ArtifactDefinition>> informationalArtifactsByType = collectGroupArtifacts(
1311 informationalArtifacts);
1312 Map<String, ArtifactDefinition> deploymentArtifacts = component.getDeploymentArtifacts();
1313 Map<ArtifactTypeEnum, List<ArtifactDefinition>> deploymentArtifactsByType = collectGroupArtifacts(
1314 deploymentArtifacts);
1315 Map<String, ArtifactDefinition> interfaceOperationArtifacts =
1316 OperationArtifactUtil.getDistinctInterfaceOperationArtifactsByName(component);
1317 Map<ArtifactTypeEnum, List<ArtifactDefinition>> interfaceOperationArtifactsByType = collectGroupArtifacts(
1318 interfaceOperationArtifacts);
1319 ArtifactsInfo artifactsInfo = new ArtifactsInfo();
1320 if (!informationalArtifactsByType.isEmpty()) {
1321 artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.INFORMATIONAL, informationalArtifactsByType);
1323 if (!deploymentArtifactsByType.isEmpty()) {
1324 artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, deploymentArtifactsByType);
1326 //Add component interface operation artifacts
1327 if(MapUtils.isNotEmpty(interfaceOperationArtifacts)) {
1328 artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, interfaceOperationArtifactsByType);
1331 return artifactsInfo;
1334 private Map<ArtifactTypeEnum, List<ArtifactDefinition>> collectGroupArtifacts(
1335 Map<String, ArtifactDefinition> componentArtifacts) {
1336 Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactsByType = new EnumMap<>(ArtifactTypeEnum.class);
1337 for (ArtifactDefinition artifact : componentArtifacts.values()) {
1338 if (artifact.getArtifactUUID() != null) {
1339 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifact.getArtifactType());
1340 List<ArtifactDefinition> typeArtifacts = artifactsByType.get(artifactType);
1341 if (typeArtifacts == null) {
1342 typeArtifacts = new ArrayList<>();
1343 artifactsByType.put(artifactType, typeArtifacts);
1345 typeArtifacts.add(artifact);
1348 return artifactsByType;