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=========================================================
20 package org.openecomp.sdc.be.tosca;
22 import static org.openecomp.sdc.be.tosca.ComponentCache.MergeStrategy.overwriteIfSameVersions;
23 import static org.openecomp.sdc.be.tosca.FJToVavrHelper.Try0.fromEither;
26 import fj.data.Either;
27 import io.vavr.Tuple2;
28 import io.vavr.control.Option;
29 import io.vavr.control.Try;
30 import java.io.BufferedOutputStream;
31 import java.io.ByteArrayInputStream;
33 import java.io.IOException;
34 import java.nio.charset.StandardCharsets;
35 import java.text.SimpleDateFormat;
36 import java.util.ArrayList;
37 import java.util.Arrays;
38 import java.util.Date;
39 import java.util.EnumMap;
40 import java.util.HashMap;
41 import java.util.HashSet;
42 import java.util.List;
44 import java.util.Map.Entry;
45 import java.util.Objects;
46 import java.util.Optional;
48 import java.util.TimeZone;
49 import java.util.function.Function;
50 import java.util.function.Predicate;
51 import java.util.function.Supplier;
52 import java.util.regex.Matcher;
53 import java.util.regex.Pattern;
54 import java.util.stream.Collectors;
55 import java.util.stream.Stream;
56 import java.util.zip.ZipEntry;
57 import java.util.zip.ZipInputStream;
58 import java.util.zip.ZipOutputStream;
61 import org.apache.commons.codec.binary.Base64;
62 import org.apache.commons.collections.CollectionUtils;
63 import org.apache.commons.collections.MapUtils;
64 import org.apache.commons.io.output.ByteArrayOutputStream;
65 import org.apache.commons.lang.StringUtils;
66 import org.apache.commons.lang3.tuple.ImmutablePair;
67 import org.apache.commons.lang3.tuple.ImmutableTriple;
68 import org.apache.commons.lang3.tuple.Triple;
69 import org.apache.commons.text.WordUtils;
70 import org.onap.sdc.tosca.services.YamlUtil;
71 import org.openecomp.sdc.be.components.impl.ImportUtils;
72 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
73 import org.openecomp.sdc.be.config.ArtifactConfigManager;
74 import org.openecomp.sdc.be.config.ArtifactConfiguration;
75 import org.openecomp.sdc.be.config.ComponentType;
76 import org.openecomp.sdc.be.config.ConfigurationManager;
77 import org.openecomp.sdc.be.dao.api.ActionStatus;
78 import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao;
79 import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
80 import org.openecomp.sdc.be.dao.cassandra.SdcSchemaFilesCassandraDao;
81 import org.openecomp.sdc.be.data.model.ToscaImportByModel;
82 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
83 import org.openecomp.sdc.be.datatypes.elements.OperationDataDefinition;
84 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
85 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
86 import org.openecomp.sdc.be.impl.ComponentsUtils;
87 import org.openecomp.sdc.be.model.ArtifactDefinition;
88 import org.openecomp.sdc.be.model.Component;
89 import org.openecomp.sdc.be.model.ComponentInstance;
90 import org.openecomp.sdc.be.model.InterfaceDefinition;
91 import org.openecomp.sdc.be.model.LifecycleStateEnum;
92 import org.openecomp.sdc.be.model.Resource;
93 import org.openecomp.sdc.be.model.Service;
94 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade;
95 import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter;
96 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
97 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
98 import org.openecomp.sdc.be.model.operations.impl.ModelOperation;
99 import org.openecomp.sdc.be.plugins.CsarEntryGenerator;
100 import org.openecomp.sdc.be.resources.data.DAOArtifactData;
101 import org.openecomp.sdc.be.tosca.utils.OperationArtifactUtil;
102 import org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum;
103 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
104 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
105 import org.openecomp.sdc.common.impl.ExternalConfiguration;
106 import org.openecomp.sdc.common.log.elements.LoggerSupportability;
107 import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode;
108 import org.openecomp.sdc.common.log.enums.LoggerSupportabilityActions;
109 import org.openecomp.sdc.common.log.enums.StatusCode;
110 import org.openecomp.sdc.common.log.wrappers.Logger;
111 import org.openecomp.sdc.common.util.GeneralUtility;
112 import org.openecomp.sdc.common.util.ValidationUtils;
113 import org.openecomp.sdc.common.zip.ZipUtils;
114 import org.openecomp.sdc.exception.ResponseFormat;
115 import org.springframework.beans.factory.annotation.Autowired;
116 import org.yaml.snakeyaml.Yaml;
121 @org.springframework.stereotype.Component("csar-utils")
122 public class CsarUtils {
124 public static final String NODES_YML = "nodes.yml";
125 public static final String ARTIFACTS_PATH = "Artifacts/";
126 public static final String ARTIFACTS = "Artifacts";
127 public static final String ARTIFACT_CREATED_FROM_CSAR = "Artifact created from csar";
128 private static final Logger log = Logger.getLogger(CsarUtils.class);
129 private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(CsarUtils.class.getName());
130 private static final String PATH_DELIMITER = "/";
131 private static final String CONFORMANCE_LEVEL = ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel();
132 private static final String SDC_VERSION = ExternalConfiguration.getAppVersion();
133 private static final String RESOURCES_PATH = "Resources/";
134 private static final String DEFINITIONS_PATH = "Definitions/";
135 private static final String CSAR_META_VERSION = "1.0";
136 private static final String CSAR_META_PATH_FILE_NAME = "csar.meta";
137 private static final String TOSCA_META_PATH_FILE_NAME = "TOSCA-Metadata/TOSCA.meta";
138 private static final String TOSCA_META_VERSION = "1.0";
139 private static final String CSAR_VERSION = "1.1";
141 private static final String SERVICE_MANIFEST = "NS.mf";
142 private static final String DEFINITION = "Definitions";
143 private static final String DEL_PATTERN = "([/\\\\]+)";
144 private static final String WORD_PATTERN = "\\w\\_\\@\\-\\.\\s]+)";
145 public static final String VALID_ENGLISH_ARTIFACT_NAME = "([" + WORD_PATTERN;
146 public static final String VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN = ARTIFACTS + DEL_PATTERN +
147 // Artifact Group (i.e Deployment/Informational)
148 VALID_ENGLISH_ARTIFACT_NAME + DEL_PATTERN +
150 VALID_ENGLISH_ARTIFACT_NAME + DEL_PATTERN +
151 // Artifact Any File Name
153 public static final String SERVICE_TEMPLATE_PATH_PATTERN = DEFINITION + DEL_PATTERN +
154 // Service Template File Name
155 VALID_ENGLISH_ARTIFACT_NAME;
156 private static final String VALID_ENGLISH_ARTIFACT_NAME_WITH_DIGITS = "([\\d" + WORD_PATTERN;
157 private static final String ARTIFACT_NAME_UNIQUE_ID = "ArtifactName {}, unique ID {}";
158 private static final String VFC_NODE_TYPE_ARTIFACTS_PATH_PATTERN =
159 ARTIFACTS + DEL_PATTERN + ImportUtils.Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + VALID_ENGLISH_ARTIFACT_NAME_WITH_DIGITS + DEL_PATTERN
160 + VALID_ENGLISH_ARTIFACT_NAME_WITH_DIGITS + DEL_PATTERN + VALID_ENGLISH_ARTIFACT_NAME_WITH_DIGITS + DEL_PATTERN
161 + VALID_ENGLISH_ARTIFACT_NAME_WITH_DIGITS;
162 private static final String BLOCK_0_TEMPLATE = "SDC-TOSCA-Meta-File-Version: %s\nSDC-TOSCA-Definitions-Version: %s\n";
164 private final ToscaOperationFacade toscaOperationFacade;
165 private final SdcSchemaFilesCassandraDao sdcSchemaFilesCassandraDao;
166 private final ArtifactCassandraDao artifactCassandraDao;
167 private final ComponentsUtils componentsUtils;
168 private final ToscaExportHandler toscaExportUtils;
169 private final List<CsarEntryGenerator> generators;
170 private final ModelOperation modelOperation;
171 private final String versionFirstThreeOctets;
174 public CsarUtils(final ToscaOperationFacade toscaOperationFacade, final SdcSchemaFilesCassandraDao sdcSchemaFilesCassandraDao,
175 final ArtifactCassandraDao artifactCassandraDao, final ComponentsUtils componentsUtils,
176 final ToscaExportHandler toscaExportUtils, final List<CsarEntryGenerator> generators, final ModelOperation modelOperation) {
177 this.toscaOperationFacade = toscaOperationFacade;
178 this.sdcSchemaFilesCassandraDao = sdcSchemaFilesCassandraDao;
179 this.artifactCassandraDao = artifactCassandraDao;
180 this.componentsUtils = componentsUtils;
181 this.toscaExportUtils = toscaExportUtils;
182 this.generators = generators;
183 this.modelOperation = modelOperation;
184 this.versionFirstThreeOctets = readVersionFirstThreeOctets();
187 private String readVersionFirstThreeOctets() {
188 if (StringUtils.isEmpty(SDC_VERSION)) {
191 // change regex to avoid DoS sonar issue
192 Matcher matcher = Pattern.compile("(?!\\.)(\\d{1,9}(\\.\\d{1,9}){1,9})(?![\\d\\.])").matcher(SDC_VERSION);
194 return matcher.group(0);
198 private static <L, R> F<L, Either<L, R>> iff(Predicate<L> p, Function<L, Either<L, R>> ifTrue) {
199 return l -> p.test(l) ? ifTrue.apply(l) : Either.left(l);
202 private static <A, B> F<A, B> iff(Predicate<A> p, Supplier<B> s, Function<A, B> orElse) {
203 return a -> p.test(a) ? s.get() : orElse.apply(a);
207 * Extracts artifacts of VFCs from CSAR
210 * @return Map of <String, List<ArtifactDefinition>> the contains Lists of artifacts according vfcToscaNamespace
212 public static Map<String, List<ArtifactDefinition>> extractVfcsArtifactsFromCsar(Map<String, byte[]> csar) {
213 Map<String, List<ArtifactDefinition>> artifacts = new HashMap<>();
215 log.debug("************* Going to extract VFCs artifacts from Csar. ");
216 Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
217 csar.entrySet().stream()
218 // filter CSAR entry by node type artifact path
219 .filter(e -> Pattern.compile(VFC_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey()).matches())
220 // extract ArtifactDefinition from CSAR entry for each entry with matching artifact path
221 .forEach(e -> extractVfcArtifact(e, collectedWarningMessages).ifPresent(ip -> addExtractedVfcArtifact(ip, artifacts)));
222 // add counter suffix to artifact labels
223 handleWarningMessages(collectedWarningMessages);
229 * Print warnings to log
231 * @param collectedWarningMessages
233 public static void handleWarningMessages(Map<String, Set<List<String>>> collectedWarningMessages) {
234 collectedWarningMessages.entrySet().stream()
236 .forEach(e -> e.getValue().stream()
237 // add each warning message to log
238 .forEach(args -> log.warn(e.getKey(), args.toArray())));
241 private static void addExtractedVfcArtifact(ImmutablePair<String, ArtifactDefinition> extractedVfcArtifact,
242 Map<String, List<ArtifactDefinition>> artifacts) {
243 String vfcToscaNamespace = extractedVfcArtifact.getKey();
244 artifacts.computeIfAbsent(vfcToscaNamespace, k -> new ArrayList<>());
245 artifacts.get(vfcToscaNamespace).add(extractedVfcArtifact.getValue());
248 private static Optional<ImmutablePair<String, ArtifactDefinition>> extractVfcArtifact(Entry<String, byte[]> entry,
249 Map<String, Set<List<String>>> collectedWarningMessages) {
250 String[] parsedCsarArtifactPath = entry.getKey().split(PATH_DELIMITER);
251 String groupType = parsedCsarArtifactPath[2].toUpperCase();
252 return detectArtifactGroupType(groupType, collectedWarningMessages).left()
253 .map(buildArtifactDefinitionFromCsarArtifactPath(entry, collectedWarningMessages, parsedCsarArtifactPath))
254 .either(ad -> Optional.of(new ImmutablePair<>(parsedCsarArtifactPath[1], ad)), b -> Optional.empty());
257 private static Either<ArtifactGroupTypeEnum, Boolean> detectArtifactGroupType(String groupType,
258 Map<String, Set<List<String>>> collectedWarningMessages) {
259 Either<ArtifactGroupTypeEnum, Boolean> result;
261 ArtifactGroupTypeEnum artifactGroupType = ArtifactGroupTypeEnum.findType(groupType.toUpperCase());
262 if (artifactGroupType == null || (artifactGroupType != ArtifactGroupTypeEnum.INFORMATIONAL
263 && artifactGroupType != ArtifactGroupTypeEnum.DEPLOYMENT)) {
264 String warningMessage = "Warning - unrecognized artifact group type {} was received.";
265 List<String> messageArguments = new ArrayList<>();
266 messageArguments.add(groupType);
267 if (!collectedWarningMessages.containsKey(warningMessage)) {
268 Set<List<String>> messageArgumentLists = new HashSet<>();
269 messageArgumentLists.add(messageArguments);
270 collectedWarningMessages.put(warningMessage, messageArgumentLists);
272 collectedWarningMessages.get(warningMessage).add(messageArguments);
274 result = Either.right(false);
276 result = Either.left(artifactGroupType);
278 } catch (Exception e) {
279 log.debug("detectArtifactGroupType failed with exception", e);
280 result = Either.right(false);
285 private static F<ArtifactGroupTypeEnum, ArtifactDefinition> buildArtifactDefinitionFromCsarArtifactPath(Entry<String, byte[]> entry,
286 Map<String, Set<List<String>>> collectedWarningMessages,
287 String[] parsedCsarArtifactPath) {
288 return artifactGroupType -> {
289 ArtifactDefinition artifact;
290 artifact = new ArtifactDefinition();
291 artifact.setArtifactGroupType(artifactGroupType);
292 artifact.setArtifactType(
293 detectArtifactTypeVFC(artifactGroupType, parsedCsarArtifactPath[3], parsedCsarArtifactPath[1], collectedWarningMessages));
294 artifact.setArtifactName(ValidationUtils.normalizeFileName(parsedCsarArtifactPath[parsedCsarArtifactPath.length - 1]));
295 artifact.setPayloadData(Base64.encodeBase64String(entry.getValue()));
296 artifact.setArtifactDisplayName(
297 artifact.getArtifactName().lastIndexOf('.') > 0 ? artifact.getArtifactName().substring(0, artifact.getArtifactName().lastIndexOf('.'))
298 : artifact.getArtifactName());
299 artifact.setArtifactLabel(ValidationUtils.normalizeArtifactLabel(artifact.getArtifactName()));
300 artifact.setDescription(ARTIFACT_CREATED_FROM_CSAR);
301 artifact.setIsFromCsar(true);
302 artifact.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(entry.getValue()));
308 * This method checks the artifact GroupType & Artifact Type. <br> if there is any problem warning messages are added to collectedWarningMessages
310 * @param artifactPath
311 * @param collectedWarningMessages
314 public static Either<NonMetaArtifactInfo, Boolean> validateNonMetaArtifact(String artifactPath, byte[] payloadData,
315 Map<String, Set<List<String>>> collectedWarningMessages) {
317 String[] parsedArtifactPath = artifactPath.split(PATH_DELIMITER);
318 String groupType = parsedArtifactPath[1];
319 String receivedTypeName = parsedArtifactPath[2];
320 String artifactFileNameType = parsedArtifactPath[3];
321 return detectArtifactGroupType(groupType, collectedWarningMessages).left().bind(artifactGroupType -> {
322 String artifactType = detectArtifactTypeVF(artifactGroupType, receivedTypeName, collectedWarningMessages);
324 .left(new NonMetaArtifactInfo(artifactFileNameType, artifactPath, artifactType, artifactGroupType, payloadData, null, true));
326 } catch (Exception e) {
327 log.debug("detectArtifactGroupType failed with exception", e);
328 return Either.right(false);
332 private static String detectArtifactTypeVFC(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, String parentVfName,
333 Map<String, Set<List<String>>> collectedWarningMessages) {
334 String warningMessage = "Warning - artifact type {} that was provided for VFC {} is not recognized.";
335 return detectArtifactType(artifactGroupType, receivedTypeName, warningMessage, collectedWarningMessages, parentVfName);
338 private static String detectArtifactTypeVF(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName,
339 Map<String, Set<List<String>>> collectedWarningMessages) {
340 String warningMessage = "Warning - artifact type {} that was provided for VF is not recognized.";
341 return detectArtifactType(artifactGroupType, receivedTypeName, warningMessage, collectedWarningMessages);
344 private static String detectArtifactType(final ArtifactGroupTypeEnum artifactGroupType, final String receivedTypeName,
345 final String warningMessage, final Map<String, Set<List<String>>> collectedWarningMessages,
346 final String... arguments) {
347 final ArtifactConfiguration artifactConfiguration = ArtifactConfigManager.getInstance()
348 .find(receivedTypeName, artifactGroupType, ComponentType.RESOURCE).orElse(null);
349 if (artifactConfiguration == null) {
350 final List<String> messageArguments = new ArrayList<>();
351 messageArguments.add(receivedTypeName);
352 messageArguments.addAll(Arrays.asList(arguments));
353 if (!collectedWarningMessages.containsKey(warningMessage)) {
354 final Set<List<String>> messageArgumentLists = new HashSet<>();
355 messageArgumentLists.add(messageArguments);
356 collectedWarningMessages.put(warningMessage, messageArgumentLists);
358 collectedWarningMessages.get(warningMessage).add(messageArguments);
361 return artifactConfiguration == null ? ArtifactTypeEnum.OTHER.getType() : receivedTypeName;
367 * @param isInCertificationRequest
370 public Either<byte[], ResponseFormat> createCsar(Component component, boolean getFromCS, boolean isInCertificationRequest) {
372 .log(LoggerSupportabilityActions.GENERATE_CSAR, StatusCode.STARTED, "Starting to create Csar for component {} ", component.getName());
373 final String createdBy = component.getCreatorFullName();
375 Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
376 ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
377 fileName = artifactDefinition.getArtifactName();
378 String toscaConformanceLevel = ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel();
379 String csarBlock0 = createCsarBlock0(CSAR_META_VERSION, toscaConformanceLevel);
380 byte[] csarBlock0Byte = csarBlock0.getBytes();
381 final String toscaBlock0 = createToscaBlock0(TOSCA_META_VERSION, CSAR_VERSION, createdBy, fileName);
382 byte[] toscaBlock0Byte = toscaBlock0.getBytes();
383 return generateCsarZip(csarBlock0Byte, toscaBlock0Byte, component, getFromCS, isInCertificationRequest).left().map(responseFormat -> {
385 .log(LoggerSupportabilityActions.GENERATE_CSAR, StatusCode.COMPLETE, "Ended create Csar for component {} ", component.getName());
386 return responseFormat;
390 private Either<byte[], ResponseFormat> generateCsarZip(byte[] csarBlock0Byte, byte[] toscaBlock0Byte, Component component, boolean getFromCS,
391 boolean isInCertificationRequest) {
392 try (ByteArrayOutputStream out = new ByteArrayOutputStream(); ZipOutputStream zip = new ZipOutputStream(out)) {
393 zip.putNextEntry(new ZipEntry(CSAR_META_PATH_FILE_NAME));
394 zip.write(csarBlock0Byte);
395 zip.putNextEntry(new ZipEntry(TOSCA_META_PATH_FILE_NAME));
396 zip.write(toscaBlock0Byte);
397 Either<ZipOutputStream, ResponseFormat> populateZip = populateZip(component, getFromCS, zip, isInCertificationRequest);
398 if (populateZip.isRight()) {
399 log.debug("Failed to populate CSAR zip file {}. Please fix DB table accordingly ", populateZip.right().value());
400 return Either.right(populateZip.right().value());
403 byte[] byteArray = out.toByteArray();
404 return Either.left(byteArray);
405 } catch (IOException e) {
406 log.debug("Failed with IOexception to create CSAR zip for component {}. Please fix DB table accordingly ", component.getUniqueId(), e);
407 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
408 return Either.right(responseFormat);
412 private Either<ZipOutputStream, ResponseFormat> populateZip(Component component, boolean getFromCS, ZipOutputStream zip,
413 boolean isInCertificationRequest) throws IOException {
414 ArtifactDefinition artifactDef = component.getToscaArtifacts().get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
415 Either<ToscaRepresentation, ResponseFormat> toscaRepresentation = fetchToscaRepresentation(component, getFromCS, artifactDef);
416 // This should not be done but in order to keep the refactoring small enough we stop here.
418 // TODO: Refactor the rest of this function
420 List<Triple<String, String, Component>> dependencies;
421 if (toscaRepresentation.isLeft()) {
422 mainYaml = toscaRepresentation.left().value().getMainYaml();
423 dependencies = toscaRepresentation.left().value().getDependencies().getOrElse(new ArrayList<>());
425 return Either.right(toscaRepresentation.right().value());
427 String fileName = artifactDef.getArtifactName();
428 zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + fileName));
430 LifecycleStateEnum lifecycleState = component.getLifecycleState();
431 addServiceMf(component, zip, lifecycleState, isInCertificationRequest, fileName, mainYaml);
432 //US798487 - Abstraction of complex types
433 if (!ModelConverter.isAtomicComponent(component)) {
434 log.debug("Component {} is complex - generating abstract type for it..", component.getName());
435 dependencies.addAll(writeComponentInterface(component, zip, fileName, false));
437 //UID <cassandraId,filename,component>
438 Either<ZipOutputStream, ResponseFormat> zipOutputStreamOrResponseFormat = getZipOutputStreamResponseFormatEither(zip, dependencies);
439 if (zipOutputStreamOrResponseFormat != null && zipOutputStreamOrResponseFormat.isRight()) {
440 return zipOutputStreamOrResponseFormat;
442 if (component.getModel() == null) {
443 //retrieve SDC.zip from Cassandra
444 Either<byte[], ResponseFormat> latestSchemaFiles = getLatestSchemaFilesFromCassandra();
445 if (latestSchemaFiles.isRight()) {
446 log.error("Error retrieving SDC Schema files from cassandra");
447 return Either.right(latestSchemaFiles.right().value());
449 final byte[] schemaFileZip = latestSchemaFiles.left().value();
450 final List<String> nodesFromPackage = findNonRootNodesFromPackage(dependencies);
451 //add files from retrieved SDC.zip to Definitions folder in CSAR
452 addSchemaFilesFromCassandra(zip, schemaFileZip, nodesFromPackage);
454 //retrieve schema files by model from Cassandra
455 addSchemaFilesByModel(zip, component.getModel());
457 Either<CsarDefinition, ResponseFormat> collectedComponentCsarDefinition = collectComponentCsarDefinition(component);
458 if (collectedComponentCsarDefinition.isRight()) {
459 return Either.right(collectedComponentCsarDefinition.right().value());
461 if (generators != null) {
462 for (CsarEntryGenerator generator : generators) {
463 log.debug("Invoking CsarEntryGenerator: {}", generator.getClass().getName());
464 for (Entry<String, byte[]> pluginGeneratedFile : generator.generateCsarEntries(component).entrySet()) {
465 zip.putNextEntry(new ZipEntry(pluginGeneratedFile.getKey()));
466 zip.write(pluginGeneratedFile.getValue());
470 return writeAllFilesToCsar(component, collectedComponentCsarDefinition.left().value(), zip, isInCertificationRequest);
473 private void addServiceMf(Component component, ZipOutputStream zip, LifecycleStateEnum lifecycleState, boolean isInCertificationRequest,
474 String fileName, byte[] mainYaml) throws IOException {
476 if ((component.getComponentType() == ComponentTypeEnum.SERVICE) && (lifecycleState != LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) {
477 String serviceName = component.getName();
478 String createdBy = component.getCreatorUserId();
479 String serviceVersion;
480 if (isInCertificationRequest) {
481 int tmp = Integer.valueOf(component.getVersion().split("\\.")[0]) + 1;
482 serviceVersion = String.valueOf(tmp) + ".0";
484 serviceVersion = component.getVersion();
486 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'");
487 format.setTimeZone(TimeZone.getTimeZone("UTC"));
488 Date date = new Date();
489 String releaseTime = format.format(date);
490 if (component.getCategories() == null || component.getCategories().get(0) == null) {
493 String serviceType = component.getCategories().get(0).getName();
494 String description = component.getDescription();
495 String serviceTemplate = DEFINITIONS_PATH + fileName;
496 String hash = GeneralUtility.calculateMD5Base64EncodedByByteArray(mainYaml);
497 String nsMfBlock0 = createNsMfBlock0(serviceName, createdBy, serviceVersion, releaseTime, serviceType, description, serviceTemplate,
499 byte[] nsMfBlock0Byte = nsMfBlock0.getBytes();
500 zip.putNextEntry(new ZipEntry(SERVICE_MANIFEST));
501 zip.write(nsMfBlock0Byte);
505 private Either<ToscaRepresentation, ResponseFormat> fetchToscaRepresentation(Component component, boolean getFromCS,
506 ArtifactDefinition artifactDef) {
507 LifecycleStateEnum lifecycleState = component.getLifecycleState();
508 boolean shouldBeFetchedFromCassandra =
509 getFromCS || !(lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
510 Either<ToscaRepresentation, ResponseFormat> toscaRepresentation =
511 shouldBeFetchedFromCassandra ? fetchToscaRepresentation(artifactDef) : generateToscaRepresentation(component);
512 return toscaRepresentation.left()
513 .bind(iff(myd -> !myd.getDependencies().isDefined(), myd -> fetchToscaTemplateDependencies(myd.getMainYaml(), component)));
516 private Either<ToscaRepresentation, ResponseFormat> fetchToscaTemplateDependencies(byte[] mainYml, Component component) {
517 return toscaExportUtils.getDependencies(component).right().map(toscaError -> {
518 log.debug("Failed to retrieve dependencies for component {}, error {}", component.getUniqueId(), toscaError);
519 return componentsUtils.getResponseFormat(componentsUtils.convertFromToscaError(toscaError));
520 }).left().map(tt -> ToscaRepresentation.make(mainYml, tt));
523 private Either<ToscaRepresentation, ResponseFormat> generateToscaRepresentation(Component component) {
524 return toscaExportUtils.exportComponent(component).right().map(toscaError -> {
525 log.debug("exportComponent failed {}", toscaError);
526 return componentsUtils.getResponseFormat(componentsUtils.convertFromToscaError(toscaError));
530 private Either<ToscaRepresentation, ResponseFormat> fetchToscaRepresentation(ArtifactDefinition artifactDef) {
531 return getFromCassandra(artifactDef.getEsId()).right().map(as -> {
532 log.debug(ARTIFACT_NAME_UNIQUE_ID, artifactDef.getArtifactName(), artifactDef.getUniqueId());
533 return componentsUtils.getResponseFormat(as);
534 }).left().map(ToscaRepresentation::make);
538 * Create a list of all derived nodes found on the package
540 * @param dependencies all node dependencies
541 * @return a list of nodes
543 private List<String> findNonRootNodesFromPackage(final List<Triple<String, String, Component>> dependencies) {
544 final List<String> nodes = new ArrayList<>();
545 if (CollectionUtils.isNotEmpty(dependencies)) {
546 final String NATIVE_ROOT = "tosca.nodes.Root";
547 dependencies.forEach(dependency -> {
548 if (dependency.getRight() instanceof Resource) {
549 final Resource resource = (Resource) dependency.getRight();
550 if (CollectionUtils.isNotEmpty(resource.getDerivedList())) {
551 resource.getDerivedList().stream().filter(node -> !nodes.contains(node) && !NATIVE_ROOT.equalsIgnoreCase(node))
552 .forEach(node -> nodes.add(node));
561 * Writes a new zip entry
563 * @param zipInputStream the zip entry to be read
564 * @return a map of the given zip entry
566 private Map<String, Object> readYamlZipEntry(final ZipInputStream zipInputStream) throws IOException {
567 final int initSize = 2048;
568 final StringBuilder zipEntry = new StringBuilder();
569 final byte[] buffer = new byte[initSize];
571 while ((read = zipInputStream.read(buffer, 0, initSize)) >= 0) {
572 zipEntry.append(new String(buffer, 0, read));
574 return (Map<String, Object>) new Yaml().load(zipEntry.toString());
578 * Filters and removes all duplicated nodes found
580 * @param nodesFromPackage a List of all derived nodes found on the given package
581 * @param nodesFromArtifactFile represents the nodes.yml file stored in Cassandra
582 * @return a nodes Map updated
584 private Map<String, Object> updateNodeYml(final List<String> nodesFromPackage, final Map<String, Object> nodesFromArtifactFile) {
585 if (MapUtils.isNotEmpty(nodesFromArtifactFile)) {
586 final String nodeTypeBlock = ToscaTagNamesEnum.NODE_TYPES.getElementName();
587 final Map<String, Object> nodeTypes = (Map<String, Object>) nodesFromArtifactFile.get(nodeTypeBlock);
588 nodesFromPackage.stream().filter(nodeTypes::containsKey).forEach(nodeTypes::remove);
589 nodesFromArtifactFile.replace(nodeTypeBlock, nodeTypes);
591 return nodesFromArtifactFile;
595 * Updates the zip entry from the given parameters
597 * @param byteArrayOutputStream an output stream in which the data is written into a byte array.
598 * @param nodesYaml a Map of nodes to be written
600 private void updateZipEntry(final ByteArrayOutputStream byteArrayOutputStream, final Map<String, Object> nodesYaml) throws IOException {
601 if (MapUtils.isNotEmpty(nodesYaml)) {
602 byteArrayOutputStream.write(new YamlUtil().objectToYaml(nodesYaml).getBytes());
606 private Either<ZipOutputStream, ResponseFormat> getZipOutputStreamResponseFormatEither(ZipOutputStream zip,
607 List<Triple<String, String, Component>> dependencies)
609 ComponentCache innerComponentsCache = ComponentCache.overwritable(overwriteIfSameVersions()).onMerge((oldValue, newValue) -> {
610 log.warn("Overwriting component invariantID {} of version {} with a newer version {}", oldValue.id, oldValue.getComponentVersion(),
611 newValue.getComponentVersion());
613 if (dependencies != null && !dependencies.isEmpty()) {
614 for (Triple<String, String, Component> d : dependencies) {
615 String cassandraId = d.getMiddle();
616 Component childComponent = d.getRight();
617 Either<byte[], ResponseFormat> entryData = getEntryData(cassandraId, childComponent).right()
618 .map(x -> componentsUtils.getResponseFormat(x));
619 if (entryData.isRight()) {
620 return Either.right(entryData.right().value());
622 //fill innerComponentsCache
623 String fileName = d.getLeft();
624 innerComponentsCache.put(cassandraId, fileName, childComponent);
625 addInnerComponentsToCache(innerComponentsCache, childComponent);
627 //add inner components to CSAR
628 return addInnerComponentsToCSAR(zip, innerComponentsCache);
633 private Either<ZipOutputStream, ResponseFormat> addInnerComponentsToCSAR(ZipOutputStream zip, ComponentCache innerComponentsCache)
635 for (ImmutableTriple<String, String, Component> ict : innerComponentsCache.iterable()) {
636 Component innerComponent = ict.getRight();
637 String icFileName = ict.getMiddle();
638 // add component to zip
639 Either<Tuple2<byte[], ZipEntry>, ResponseFormat> zipEntry = toZipEntry(ict);
640 // TODO: this should not be done, we should instead compose this either further,
642 // but in order to keep this refactoring small, we'll stop here.
643 if (zipEntry.isRight()) {
644 return Either.right(zipEntry.right().value());
646 Tuple2<byte[], ZipEntry> value = zipEntry.left().value();
647 zip.putNextEntry(value._2);
649 // add component interface to zip
650 if (!ModelConverter.isAtomicComponent(innerComponent)) {
651 writeComponentInterface(innerComponent, zip, icFileName, true);
657 private Either<Tuple2<byte[], ZipEntry>, ResponseFormat> toZipEntry(ImmutableTriple<String, String, Component> cachedEntry) {
658 String cassandraId = cachedEntry.getLeft();
659 String fileName = cachedEntry.getMiddle();
660 Component innerComponent = cachedEntry.getRight();
661 return getEntryData(cassandraId, innerComponent).right().map(status -> {
662 log.debug("Failed adding to zip component {}, error {}", cassandraId, status);
663 return componentsUtils.getResponseFormat(status);
664 }).left().map(content -> new Tuple2<>(content, new ZipEntry(DEFINITIONS_PATH + fileName)));
668 * Writes to a CSAR zip from casandra schema data
670 * @param zipOutputStream stores the input stream content
671 * @param schemaFileZip zip data from Cassandra
672 * @param nodesFromPackage list of all nodes found on the onboarded package
674 private void addSchemaFilesFromCassandra(final ZipOutputStream zipOutputStream, final byte[] schemaFileZip, final List<String> nodesFromPackage) {
675 final int initSize = 2048;
676 log.debug("Starting copy from Schema file zip to CSAR zip");
677 try (final ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(
678 schemaFileZip)); final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); final BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(
679 byteArrayOutputStream, initSize)) {
681 while ((entry = zipInputStream.getNextEntry()) != null) {
682 ZipUtils.checkForZipSlipInRead(entry);
683 final String entryName = entry.getName();
684 int readSize = initSize;
685 final byte[] entryData = new byte[initSize];
686 if (shouldZipEntryBeHandled(entryName)) {
687 if (NODES_YML.equalsIgnoreCase(entryName)) {
688 handleNode(zipInputStream, byteArrayOutputStream, nodesFromPackage);
690 while ((readSize = zipInputStream.read(entryData, 0, readSize)) != -1) {
691 bufferedOutputStream.write(entryData, 0, readSize);
693 bufferedOutputStream.flush();
695 byteArrayOutputStream.flush();
696 zipOutputStream.putNextEntry(new ZipEntry(DEFINITIONS_PATH + entryName));
697 zipOutputStream.write(byteArrayOutputStream.toByteArray());
698 zipOutputStream.flush();
699 byteArrayOutputStream.reset();
702 } catch (final Exception e) {
703 log.error("Error while writing the SDC schema file to the CSAR", e);
704 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
706 log.debug("Finished copy from Schema file zip to CSAR zip");
710 * Checks if the zip entry should or should not be added to the CSAR based on the given global type list
712 * @param entryName the zip entry name
713 * @return true if the zip entry should be handled
715 private boolean shouldZipEntryBeHandled(final String entryName) {
716 return ConfigurationManager.getConfigurationManager().getConfiguration().getGlobalCsarImports().stream()
717 .anyMatch(entry -> entry.contains(entryName));
721 * Handles the nodes.yml zip entry, updating the nodes.yml to avoid duplicated nodes on it.
723 * @param zipInputStream the zip entry to be read
724 * @param byteArrayOutputStream an output stream in which the data is written into a byte array.
725 * @param nodesFromPackage list of all nodes found on the onboarded package
727 private void handleNode(final ZipInputStream zipInputStream, final ByteArrayOutputStream byteArrayOutputStream,
728 final List<String> nodesFromPackage) throws IOException {
729 final Map<String, Object> nodesFromArtifactFile = readYamlZipEntry(zipInputStream);
730 final Map<String, Object> nodesYaml = updateNodeYml(nodesFromPackage, nodesFromArtifactFile);
731 updateZipEntry(byteArrayOutputStream, nodesYaml);
734 private void addInnerComponentsToCache(ComponentCache componentCache, Component childComponent) {
735 javaListToVavrList(childComponent.getComponentInstances()).filter(ci -> componentCache.notCached(ci.getComponentUid())).forEach(ci -> {
736 // all resource must be only once!
737 Either<Resource, StorageOperationStatus> resource = toscaOperationFacade.getToscaElement(ci.getComponentUid());
738 Component componentRI = checkAndAddComponent(componentCache, ci, resource);
739 //if not atomic - insert inner components as well
741 // TODO: This could potentially create a StackOverflowException if the call stack
743 // happens to be too large. Tail-recursive optimization should be used here.
744 if (!ModelConverter.isAtomicComponent(componentRI)) {
745 addInnerComponentsToCache(componentCache, componentRI);
750 // TODO: Move this function in FJToVavrHelper.java once Change 108540 is merged
751 private io.vavr.collection.List<ComponentInstance> javaListToVavrList(List<ComponentInstance> componentInstances) {
752 return Option.of(componentInstances).map(io.vavr.collection.List::ofAll).getOrElse(io.vavr.collection.List::empty);
755 private Component checkAndAddComponent(ComponentCache componentCache, ComponentInstance ci, Either<Resource, StorageOperationStatus> resource) {
756 if (resource.isRight()) {
757 log.debug("Failed to fetch resource with id {} for instance {}", ci.getComponentUid(), ci.getName());
759 Component componentRI = resource.left().value();
760 Map<String, ArtifactDefinition> childToscaArtifacts = componentRI.getToscaArtifacts();
761 ArtifactDefinition childArtifactDefinition = childToscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
762 if (childArtifactDefinition != null) {
764 componentCache.put(childArtifactDefinition.getEsId(), childArtifactDefinition.getArtifactName(), componentRI);
769 private List<Triple<String, String, Component>> writeComponentInterface(Component component,
772 boolean isAssociatedComponent
774 final Either<ToscaRepresentation, ToscaError> interfaceRepresentation = toscaExportUtils.exportComponentInterface(component, false);
775 writeComponentInterface(interfaceRepresentation, zip, fileName, false);
776 return interfaceRepresentation.left().value().getDependencies().getOrElse(new ArrayList<>());
780 private Either<ZipOutputStream, ResponseFormat> writeComponentInterface(
781 Either<ToscaRepresentation,ToscaError> interfaceRepresentation, ZipOutputStream zip, String fileName,
782 boolean isAssociatedComponent) {
783 // TODO: This should not be done but we need this to keep the refactoring small enough to be easily reviewable
784 return writeComponentInterface(interfaceRepresentation, fileName, isAssociatedComponent, ZipWriter.live(zip))
785 .map(void0 -> Either.<ZipOutputStream, ResponseFormat>left(zip)).recover(th -> {
786 log.error("#writeComponentInterface - zip writing failed with error: ", th);
787 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
791 private Try<Void> writeComponentInterface(
792 Either<ToscaRepresentation,ToscaError> interfaceRepresentation, String fileName, boolean isAssociatedComponent, ZipWriter zw) {
793 Either<byte[], ToscaError> yml = interfaceRepresentation.left()
794 .map(ToscaRepresentation::getMainYaml);
795 return fromEither(yml, ToscaErrorException::new).flatMap(zw.write(DEFINITIONS_PATH + ToscaExportHandler.getInterfaceFilename(fileName)));
798 private Either<byte[], ActionStatus> getEntryData(String cassandraId, Component childComponent) {
799 if (cassandraId == null || cassandraId.isEmpty()) {
800 return toscaExportUtils.exportComponent(childComponent).right().map(toscaErrorToActionStatus(childComponent)).left()
801 .map(ToscaRepresentation::getMainYaml);
803 return getFromCassandra(cassandraId);
807 private F<ToscaError, ActionStatus> toscaErrorToActionStatus(Component childComponent) {
808 return toscaError -> {
809 log.debug("Failed to export tosca template for child component {} error {}", childComponent.getUniqueId(), toscaError);
810 return componentsUtils.convertFromToscaError(toscaError);
814 private Either<byte[], ResponseFormat> getLatestSchemaFilesFromCassandra() {
815 String fto = getVersionFirstThreeOctets();
816 return sdcSchemaFilesCassandraDao.getSpecificSchemaFiles(fto, CONFORMANCE_LEVEL).right().map(schemaFilesFetchDBError(fto)).left()
817 .bind(iff(List::isEmpty, () -> schemaFileFetchError(fto), s -> Either.left(s.iterator().next().getPayloadAsArray())));
820 private void addSchemaFilesByModel(final ZipOutputStream zipOutputStream, final String modelName) {
822 final List<ToscaImportByModel> modelDefaultImportList = modelOperation.findAllModelImports(modelName, true);
823 for (final ToscaImportByModel toscaImportByModel : modelDefaultImportList) {
824 final var zipEntry = new ZipEntry(DEFINITIONS_PATH + toscaImportByModel.getFullPath());
825 zipOutputStream.putNextEntry(zipEntry);
826 final byte[] content = toscaImportByModel.getContent().getBytes(StandardCharsets.UTF_8);
827 zipOutputStream.write(content, 0, content.length);
828 zipOutputStream.closeEntry();
830 } catch (final IOException e) {
831 log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, CsarUtils.class.getName(),
832 "Error while writing the schema files by model to the CSAR", e);
833 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.CSAR_TOSCA_IMPORTS_ERROR));
837 private F<CassandraOperationStatus, ResponseFormat> schemaFilesFetchDBError(String firstThreeOctets) {
839 log.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}. Please fix DB table accordingly.", firstThreeOctets,
841 StorageOperationStatus sos = DaoStatusConverter.convertCassandraStatusToStorageStatus(cos);
842 return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(sos));
846 private Either<byte[], ResponseFormat> schemaFileFetchError(String firstThreeOctets) {
847 log.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}", firstThreeOctets, CONFORMANCE_LEVEL);
848 return Either.right(componentsUtils.getResponseFormat(ActionStatus.TOSCA_SCHEMA_FILES_NOT_FOUND, firstThreeOctets, CONFORMANCE_LEVEL));
851 private Either<byte[], ActionStatus> getFromCassandra(String cassandraId) {
852 return artifactCassandraDao.getArtifact(cassandraId).right().map(cos -> {
853 log.debug("Failed to fetch artifact from Cassandra by id {} error {} ", cassandraId, cos);
854 StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(cos);
855 return componentsUtils.convertFromStorageResponse(storageStatus);
856 }).left().map(DAOArtifactData::getDataAsArray);
859 private String createCsarBlock0(String metaFileVersion, String toscaConformanceLevel) {
860 return String.format(BLOCK_0_TEMPLATE, metaFileVersion, toscaConformanceLevel);
863 private String createToscaBlock0(String metaFileVersion, String csarVersion, String createdBy, String entryDef) {
864 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";
865 return String.format(block0template, metaFileVersion, csarVersion, createdBy, entryDef);
868 private String createNsMfBlock0(String serviceName, String createdBy, String serviceVersion, String releaseTime, String serviceType,
869 String description, String serviceTemplate, String hash) {
870 final String block0template = "metadata??\n" + "ns_product_name: %s\n" + "ns_provider_id: %s\n" + "ns_package_version: %s\n" +
871 //"ns_create_date_time: %s\n" +
872 "ns_release_data_time: %s\n" + "ns_type: %s\n" + "ns_package_description: %s\n\n" + "Source: %s\n" + "Algorithm: MD5\n" + "Hash: %s\n\n";
873 return String.format(block0template, serviceName, createdBy, serviceVersion, releaseTime, serviceType, description, serviceTemplate, hash);
876 private Either<ZipOutputStream, ResponseFormat> writeAllFilesToCsar(Component mainComponent, CsarDefinition csarDefinition,
877 ZipOutputStream zipstream, boolean isInCertificationRequest)
879 ComponentArtifacts componentArtifacts = csarDefinition.getComponentArtifacts();
880 Either<ZipOutputStream, ResponseFormat> writeComponentArtifactsToSpecifiedPath = writeComponentArtifactsToSpecifiedPath(mainComponent,
881 componentArtifacts, zipstream, ARTIFACTS_PATH, isInCertificationRequest);
882 if (writeComponentArtifactsToSpecifiedPath.isRight()) {
883 return Either.right(writeComponentArtifactsToSpecifiedPath.right().value());
885 ComponentTypeArtifacts mainTypeAndCIArtifacts = componentArtifacts.getMainTypeAndCIArtifacts();
886 writeComponentArtifactsToSpecifiedPath = writeArtifactsInfoToSpecifiedPath(mainComponent, mainTypeAndCIArtifacts.getComponentArtifacts(),
887 zipstream, ARTIFACTS_PATH, isInCertificationRequest);
888 if (writeComponentArtifactsToSpecifiedPath.isRight()) {
889 return Either.right(writeComponentArtifactsToSpecifiedPath.right().value());
891 Map<String, ArtifactsInfo> componentInstancesArtifacts = mainTypeAndCIArtifacts.getComponentInstancesArtifacts();
892 Set<String> keySet = componentInstancesArtifacts.keySet();
893 String currentPath = ARTIFACTS_PATH + RESOURCES_PATH;
894 for (String keyAssetName : keySet) {
895 ArtifactsInfo artifactsInfo = componentInstancesArtifacts.get(keyAssetName);
896 String pathWithAssetName = currentPath + keyAssetName + PATH_DELIMITER;
897 writeComponentArtifactsToSpecifiedPath = writeArtifactsInfoToSpecifiedPath(mainComponent, artifactsInfo, zipstream, pathWithAssetName,
898 isInCertificationRequest);
899 if (writeComponentArtifactsToSpecifiedPath.isRight()) {
900 return Either.right(writeComponentArtifactsToSpecifiedPath.right().value());
903 writeComponentArtifactsToSpecifiedPath = writeOperationsArtifactsToCsar(mainComponent, zipstream);
904 if (writeComponentArtifactsToSpecifiedPath.isRight()) {
905 return Either.right(writeComponentArtifactsToSpecifiedPath.right().value());
907 return Either.left(zipstream);
910 private Either<ZipOutputStream, ResponseFormat> writeOperationsArtifactsToCsar(Component component, ZipOutputStream zipstream) {
911 if (checkComponentBeforeOperation(component)) {
912 return Either.left(zipstream);
914 final Map<String, InterfaceDefinition> interfaces = ((Resource) component).getInterfaces();
915 for (Map.Entry<String, InterfaceDefinition> interfaceEntry : interfaces.entrySet()) {
916 for (OperationDataDefinition operation : interfaceEntry.getValue().getOperations().values()) {
918 if (checkComponentBeforeWrite(component, interfaceEntry, operation)) {
921 final String artifactUUID = operation.getImplementation().getArtifactUUID();
922 if (artifactUUID == null) {
925 final Either<byte[], ActionStatus> artifactFromCassandra = getFromCassandra(artifactUUID);
926 final String artifactName = operation.getImplementation().getArtifactName();
927 if (artifactFromCassandra.isRight()) {
928 log.error(ARTIFACT_NAME_UNIQUE_ID, artifactName, artifactUUID);
929 log.error("Failed to get {} payload from DB reason: {}", artifactName, artifactFromCassandra.right().value());
930 return Either.right(componentsUtils
931 .getResponseFormat(ActionStatus.ARTIFACT_PAYLOAD_NOT_FOUND_DURING_CSAR_CREATION, "Resource", component.getUniqueId(),
932 artifactName, artifactUUID));
934 final byte[] payloadData = artifactFromCassandra.left().value();
935 zipstream.putNextEntry(new ZipEntry(OperationArtifactUtil.createOperationArtifactPath(component, null, operation, true)));
936 zipstream.write(payloadData);
937 } catch (IOException e) {
938 log.error("Component Name {}, Interface Name {}, Operation Name {}", component.getNormalizedName(), interfaceEntry.getKey(),
939 operation.getName());
940 log.error("Error while writing the operation's artifacts to the CSAR " + "{}", e);
942 .right(componentsUtils.getResponseFormat(ActionStatus.ERROR_DURING_CSAR_CREATION, "Resource", component.getUniqueId()));
946 return Either.left(zipstream);
949 private boolean checkComponentBeforeWrite(Component component, Entry<String, InterfaceDefinition> interfaceEntry,
950 OperationDataDefinition operation) {
951 final ArtifactDataDefinition implementation = operation.getImplementation();
952 if (Objects.isNull(implementation)) {
953 log.debug("Component Name {}, Interface Id {}, Operation Name {} - no Operation Implementation found", component.getNormalizedName(),
954 interfaceEntry.getValue().getUniqueId(), operation.getName());
957 final String artifactName = implementation.getArtifactName();
958 if (Objects.isNull(artifactName)) {
959 log.debug("Component Name {}, Interface Id {}, Operation Name {} - no artifact found", component.getNormalizedName(),
960 interfaceEntry.getValue().getUniqueId(), operation.getName());
963 if (OperationArtifactUtil.artifactNameIsALiteralValue(artifactName)) {
964 log.debug("Component Name {}, Interface Id {}, Operation Name {} - artifact name is a literal value rather than an SDC artifact",
965 component.getNormalizedName(), interfaceEntry.getValue().getUniqueId(), operation.getName());
971 private boolean checkComponentBeforeOperation(Component component) {
972 if (component instanceof Service) {
975 if (Objects.isNull(((Resource) component).getInterfaces())) {
976 log.debug("Component Name {}- no interfaces found", component.getNormalizedName());
982 private Either<ZipOutputStream, ResponseFormat> writeComponentArtifactsToSpecifiedPath(Component mainComponent,
983 ComponentArtifacts componentArtifacts,
984 ZipOutputStream zipstream, String currentPath,
985 boolean isInCertificationRequest) throws IOException {
986 Map<String, ComponentTypeArtifacts> componentTypeArtifacts = componentArtifacts.getComponentTypeArtifacts();
989 //<Inner Asset TOSCA name (e.g. VFC name)> folder name: <Inner Asset TOSCA name (e.g. VFC name)>_v<version>.
991 //E.g. "org.openecomp.resource.vf.vipr_atm_v1.0"
992 Set<String> componentTypeArtifactsKeys = componentTypeArtifacts.keySet();
993 for (String keyAssetName : componentTypeArtifactsKeys) {
994 ComponentTypeArtifacts componentInstanceArtifacts = componentTypeArtifacts.get(keyAssetName);
995 ArtifactsInfo componentArtifacts2 = componentInstanceArtifacts.getComponentArtifacts();
996 String pathWithAssetName = currentPath + keyAssetName + PATH_DELIMITER;
997 Either<ZipOutputStream, ResponseFormat> writeArtifactsInfoToSpecifiedPath = writeArtifactsInfoToSpecifiedPath(mainComponent,
998 componentArtifacts2, zipstream, pathWithAssetName, isInCertificationRequest);
999 if (writeArtifactsInfoToSpecifiedPath.isRight()) {
1000 return writeArtifactsInfoToSpecifiedPath;
1003 return Either.left(zipstream);
1006 private Either<ZipOutputStream, ResponseFormat> writeArtifactsInfoToSpecifiedPath(final Component mainComponent,
1007 final ArtifactsInfo currArtifactsInfo,
1008 final ZipOutputStream zip, final String path,
1009 final boolean isInCertificationRequest) throws IOException {
1010 final Map<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> artifactsInfo = currArtifactsInfo.getArtifactsInfo();
1011 for (final ArtifactGroupTypeEnum artifactGroupTypeEnum : artifactsInfo.keySet()) {
1012 final String groupTypeFolder = path + WordUtils.capitalizeFully(artifactGroupTypeEnum.getType()) + PATH_DELIMITER;
1013 final Map<String, List<ArtifactDefinition>> artifactTypesMap = artifactsInfo.get(artifactGroupTypeEnum);
1014 for (final String artifactType : artifactTypesMap.keySet()) {
1015 final List<ArtifactDefinition> artifactDefinitionList = artifactTypesMap.get(artifactType);
1016 String artifactTypeFolder = groupTypeFolder + artifactType + PATH_DELIMITER;
1017 if (ArtifactTypeEnum.WORKFLOW.getType().equals(artifactType) && path.contains(ARTIFACTS_PATH + RESOURCES_PATH)) {
1018 // Ignore this packaging as BPMN artifacts needs to be packaged in different manner
1021 if (ArtifactTypeEnum.WORKFLOW.getType().equals(artifactType)) {
1022 artifactTypeFolder += OperationArtifactUtil.BPMN_ARTIFACT_PATH + File.separator;
1023 } else if (ArtifactTypeEnum.ONBOARDED_PACKAGE.getType().equals(artifactType)) {
1024 // renaming legacy folder ONBOARDED_PACKAGE to the new folder ETSI_PACKAGE
1025 artifactTypeFolder = artifactTypeFolder
1026 .replace(ArtifactTypeEnum.ONBOARDED_PACKAGE.getType(), ArtifactTypeEnum.ETSI_PACKAGE.getType());
1028 // TODO: We should not do this but in order to keep this refactoring small enough,
1030 // we'll leave this as is for now
1031 List<ArtifactDefinition> collect = filterArtifactDefinitionToZip(mainComponent, artifactDefinitionList, isInCertificationRequest)
1032 .collect(Collectors.toList());
1033 for (ArtifactDefinition ad : collect) {
1034 zip.putNextEntry(new ZipEntry(artifactTypeFolder + ad.getArtifactName()));
1035 zip.write(ad.getPayloadData());
1039 return Either.left(zip);
1042 private Stream<ArtifactDefinition> filterArtifactDefinitionToZip(Component mainComponent, List<ArtifactDefinition> artifactDefinitionList,
1043 boolean isInCertificationRequest) {
1044 return artifactDefinitionList.stream().filter(shouldBeInZip(isInCertificationRequest, mainComponent)).map(this::fetchPayLoadData)
1045 .filter(Either::isLeft).map(e -> e.left().value());
1048 private Predicate<ArtifactDefinition> shouldBeInZip(boolean isInCertificationRequest, Component component) {
1049 return artifactDefinition -> !(!isInCertificationRequest && component.isService() && artifactDefinition.isHeatEnvType() || artifactDefinition
1050 .hasNoMandatoryEsId());
1053 private Either<ArtifactDefinition, ActionStatus> fetchPayLoadData(ArtifactDefinition ad) {
1054 byte[] payloadData = ad.getPayloadData();
1055 if (payloadData == null) {
1056 return getFromCassandra(ad.getEsId()).left().map(pd -> {
1059 }).right().map(as -> {
1060 log.debug(ARTIFACT_NAME_UNIQUE_ID, ad.getArtifactName(), ad.getUniqueId());
1061 log.debug("Failed to get {} payload from DB reason: {}", ad.getArtifactName(), as);
1065 return Either.left(ad);
1069 /************************************ Artifacts Structure END******************************************************************/
1071 private Either<CsarDefinition, ResponseFormat> collectComponentCsarDefinition(Component component) {
1072 ComponentArtifacts componentArtifacts = new ComponentArtifacts();
1073 Component updatedComponent = component;
1075 //get service to receive the AII artifacts uploaded to the service
1076 if (updatedComponent.getComponentType() == ComponentTypeEnum.SERVICE) {
1077 Either<Service, StorageOperationStatus> getServiceResponse = toscaOperationFacade.getToscaElement(updatedComponent.getUniqueId());
1079 if (getServiceResponse.isRight()) {
1080 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getServiceResponse.right().value());
1081 return Either.right(componentsUtils.getResponseFormat(actionStatus));
1084 updatedComponent = getServiceResponse.left().value();
1087 //find the artifacts of the main component, it would have its composed instances artifacts in a separate folder
1088 ComponentTypeArtifacts componentInstanceArtifacts = new ComponentTypeArtifacts();
1089 ArtifactsInfo artifactsInfo = collectComponentArtifacts(updatedComponent);
1090 componentInstanceArtifacts.setComponentArtifacts(artifactsInfo);
1091 componentArtifacts.setMainTypeAndCIArtifacts(componentInstanceArtifacts);
1093 Map<String, ComponentTypeArtifacts> resourceTypeArtifacts = componentArtifacts
1094 .getComponentTypeArtifacts(); //artifacts mapped by the component type(tosca name+version)
1095 //get the component instances
1096 List<ComponentInstance> componentInstances = updatedComponent.getComponentInstances();
1097 if (componentInstances != null) {
1098 for (ComponentInstance componentInstance : componentInstances) {
1099 //call recursive to find artifacts for all the path
1100 Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts = collectComponentInstanceArtifacts(
1101 updatedComponent, componentInstance, resourceTypeArtifacts, componentInstanceArtifacts);
1102 if (collectComponentInstanceArtifacts.isRight()) {
1103 return Either.right(collectComponentInstanceArtifacts.right().value());
1108 if (log.isDebugEnabled()) {
1109 printResult(componentArtifacts, updatedComponent.getName());
1112 return Either.left(new CsarDefinition(componentArtifacts));
1115 private void printResult(ComponentArtifacts componentArtifacts, String name) {
1116 StringBuilder result = new StringBuilder();
1117 result.append("Artifacts of main component " + name + "\n");
1118 ComponentTypeArtifacts componentInstanceArtifacts = componentArtifacts.getMainTypeAndCIArtifacts();
1119 printArtifacts(componentInstanceArtifacts);
1120 result.append("Type Artifacts\n");
1121 for (Map.Entry<String, ComponentTypeArtifacts> typeArtifacts : componentArtifacts.getComponentTypeArtifacts().entrySet()) {
1122 result.append("Folder " + typeArtifacts.getKey() + "\n");
1123 result.append(printArtifacts(typeArtifacts.getValue()));
1126 if (log.isDebugEnabled()) {
1127 log.debug(result.toString());
1131 /************************************ Artifacts Structure ******************************************************************/
1133 private String printArtifacts(ComponentTypeArtifacts componentInstanceArtifacts) {
1134 StringBuilder result = new StringBuilder();
1135 ArtifactsInfo artifactsInfo = componentInstanceArtifacts.getComponentArtifacts();
1136 Map<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> componentArtifacts = artifactsInfo.getArtifactsInfo();
1137 printArtifacts(componentArtifacts);
1138 result = result.append("Resources\n");
1139 for (Map.Entry<String, ArtifactsInfo> resourceInstance : componentInstanceArtifacts.getComponentInstancesArtifacts().entrySet()) {
1140 result.append("Folder" + resourceInstance.getKey() + "\n");
1141 result.append(printArtifacts(resourceInstance.getValue().getArtifactsInfo()));
1144 return result.toString();
1147 private String printArtifacts(Map<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> componetArtifacts) {
1148 StringBuilder result = new StringBuilder();
1149 for (Map.Entry<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> artifactGroup : componetArtifacts.entrySet()) {
1150 result.append(" " + artifactGroup.getKey().getType());
1151 for (Map.Entry<String, List<ArtifactDefinition>> groupArtifacts : artifactGroup.getValue().entrySet()) {
1152 result.append(" " + groupArtifacts.getKey());
1153 for (ArtifactDefinition artifact : groupArtifacts.getValue()) {
1154 result.append(" " + artifact.getArtifactDisplayName());
1159 return result.toString();
1162 private ComponentTypeArtifacts collectComponentTypeArtifacts(
1163 Component fetchedComponent
1165 ArtifactsInfo componentArtifacts = collectComponentArtifacts(fetchedComponent);
1166 ComponentTypeArtifacts componentArtifactsInfo = new ComponentTypeArtifacts();
1167 if (componentArtifacts.isNotEmpty()) {
1168 componentArtifactsInfo.setComponentArtifacts(componentArtifacts);
1170 return componentArtifactsInfo;
1173 private Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts(Component parentComponent, ComponentInstance componentInstance,
1174 Map<String, ComponentTypeArtifacts> resourcesTypeArtifacts,
1175 ComponentTypeArtifacts instanceArtifactsLocation) {
1176 //1. get the component instance component
1177 String componentUid;
1178 if (componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy) {
1179 componentUid = componentInstance.getSourceModelUid();
1181 componentUid = componentInstance.getComponentUid();
1183 Either<Component, StorageOperationStatus> component = toscaOperationFacade.getToscaElement(componentUid);
1184 if (component.isRight()) {
1185 log.error("Failed to fetch resource with id {} for instance {}", componentUid, parentComponent.getUUID());
1186 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ASSET_NOT_FOUND_DURING_CSAR_CREATION,
1187 parentComponent.getComponentType().getValue(), parentComponent.getUUID(),
1188 componentInstance.getOriginType().getComponentType().getValue(), componentUid));
1190 Component fetchedComponent = component.left().value();
1192 //2. fill the artifacts for the current component parent type
1193 String toscaComponentName =
1194 componentInstance.getToscaComponentName() + "_v" + componentInstance.getComponentVersion();
1196 // if there are no artifacts for this component type we need to fetch and build them
1197 ComponentTypeArtifacts componentParentArtifacts = Optional
1198 .ofNullable(resourcesTypeArtifacts.get(toscaComponentName))
1199 .orElseGet(() -> collectComponentTypeArtifacts(fetchedComponent));
1201 if (componentParentArtifacts.getComponentArtifacts().isNotEmpty()) {
1202 resourcesTypeArtifacts.put(toscaComponentName, componentParentArtifacts);
1205 //3. find the artifacts specific to the instance
1206 Map<String, List<ArtifactDefinition>> componentInstanceSpecificInformationalArtifacts =
1207 getComponentInstanceSpecificArtifacts(componentInstance.getArtifacts(),
1208 componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), ArtifactGroupTypeEnum.INFORMATIONAL);
1209 Map<String, List<ArtifactDefinition>> componentInstanceSpecificDeploymentArtifacts =
1210 getComponentInstanceSpecificArtifacts(componentInstance.getDeploymentArtifacts(),
1211 componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), ArtifactGroupTypeEnum.DEPLOYMENT);
1213 //4. add the instances artifacts to the component type
1214 ArtifactsInfo artifactsInfo = new ArtifactsInfo();
1215 if (!componentInstanceSpecificInformationalArtifacts.isEmpty()) {
1216 artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.INFORMATIONAL, componentInstanceSpecificInformationalArtifacts);
1218 if (!componentInstanceSpecificDeploymentArtifacts.isEmpty()) {
1219 artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, componentInstanceSpecificDeploymentArtifacts);
1221 if (!artifactsInfo.isEmpty()) {
1222 instanceArtifactsLocation.addComponentInstancesArtifacts(componentInstance.getNormalizedName(), artifactsInfo);
1225 //5. do the same for all the component instances
1226 List<ComponentInstance> componentInstances = fetchedComponent.getComponentInstances();
1227 if (componentInstances != null) {
1228 for (ComponentInstance childComponentInstance : componentInstances) {
1229 Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts = collectComponentInstanceArtifacts(
1230 fetchedComponent, childComponentInstance, resourcesTypeArtifacts, componentParentArtifacts);
1231 if (collectComponentInstanceArtifacts.isRight()) {
1232 return collectComponentInstanceArtifacts;
1237 return Either.left(true);
1240 public String getVersionFirstThreeOctets() {
1241 return versionFirstThreeOctets;
1244 private Map<String, List<ArtifactDefinition>> getComponentInstanceSpecificArtifacts(Map<String, ArtifactDefinition> componentArtifacts,
1245 Map<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> componentTypeArtifacts,
1246 ArtifactGroupTypeEnum artifactGroupTypeEnum) {
1247 Map<String, List<ArtifactDefinition>> parentArtifacts = componentTypeArtifacts
1248 .get(artifactGroupTypeEnum); //the artfiacts of the component itself and not the instance
1250 Map<String, List<ArtifactDefinition>> artifactsByTypeOfComponentInstance = new HashMap<>();
1251 if (componentArtifacts != null) {
1252 for (ArtifactDefinition artifact : componentArtifacts.values()) {
1253 List<ArtifactDefinition> parentArtifactsByType = null;
1254 if (parentArtifacts != null) {
1255 parentArtifactsByType = parentArtifacts.get(artifact.getArtifactType());
1257 //the artifact is of instance
1258 if (parentArtifactsByType == null || !parentArtifactsByType.contains(artifact)) {
1259 List<ArtifactDefinition> typeArtifacts = artifactsByTypeOfComponentInstance.get(artifact.getArtifactType());
1260 if (typeArtifacts == null) {
1261 typeArtifacts = new ArrayList<>();
1262 artifactsByTypeOfComponentInstance.put(artifact.getArtifactType(), typeArtifacts);
1264 typeArtifacts.add(artifact);
1269 return artifactsByTypeOfComponentInstance;
1272 private ArtifactsInfo collectComponentArtifacts(Component component) {
1273 Map<String, ArtifactDefinition> informationalArtifacts = component.getArtifacts();
1274 Map<String, List<ArtifactDefinition>> informationalArtifactsByType = collectGroupArtifacts(informationalArtifacts);
1275 Map<String, ArtifactDefinition> deploymentArtifacts = component.getDeploymentArtifacts();
1276 Map<String, List<ArtifactDefinition>> deploymentArtifactsByType = collectGroupArtifacts(deploymentArtifacts);
1277 Map<String, ArtifactDefinition> interfaceOperationArtifacts =
1278 OperationArtifactUtil.getDistinctInterfaceOperationArtifactsByName(component);
1279 Map<String, List<ArtifactDefinition>> interfaceOperationArtifactsByType = collectGroupArtifacts(
1280 interfaceOperationArtifacts);
1281 ArtifactsInfo artifactsInfo = new ArtifactsInfo();
1282 if (!informationalArtifactsByType.isEmpty()) {
1283 artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.INFORMATIONAL, informationalArtifactsByType);
1285 if (!deploymentArtifactsByType.isEmpty()) {
1286 artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, deploymentArtifactsByType);
1289 return artifactsInfo;
1292 private Map<String, List<ArtifactDefinition>> collectGroupArtifacts(
1293 final Map<String, ArtifactDefinition> componentArtifacts) {
1294 final Map<String, List<ArtifactDefinition>> artifactsByType = new HashMap<>();
1295 for (final ArtifactDefinition artifact : componentArtifacts.values()) {
1296 if (artifact.getArtifactUUID() != null) {
1297 artifactsByType.putIfAbsent(artifact.getArtifactType(), new ArrayList<>());
1298 final List<ArtifactDefinition> typeArtifacts = artifactsByType.get(artifact.getArtifactType());
1299 typeArtifacts.add(artifact);
1302 return artifactsByType;
1305 public static class ToscaErrorException extends Exception {
1307 ToscaErrorException(ToscaError error) {
1308 super("Error while exporting component's interface (toscaError:" + error + ")");
1313 public static final class NonMetaArtifactInfo {
1315 private final String path;
1316 private final String artifactName;
1317 private final String displayName;
1318 private final String artifactLabel;
1319 private final String artifactType;
1320 private final ArtifactGroupTypeEnum artifactGroupType;
1321 private final String payloadData;
1322 private final String artifactChecksum;
1323 private final boolean isFromCsar;
1325 private String artifactUniqueId;
1327 public NonMetaArtifactInfo(final String artifactName, final String path, final String artifactType,
1328 final ArtifactGroupTypeEnum artifactGroupType, final byte[] payloadData, final String artifactUniqueId,
1329 final boolean isFromCsar) {
1332 this.isFromCsar = isFromCsar;
1333 this.artifactName = ValidationUtils.normalizeFileName(artifactName);
1334 this.artifactType = artifactType;
1335 this.artifactGroupType = artifactGroupType;
1336 final int pointIndex = artifactName.lastIndexOf('.');
1337 if (pointIndex > 0) {
1338 displayName = artifactName.substring(0, pointIndex);
1340 displayName = artifactName;
1342 this.artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactName);
1343 if (payloadData == null) {
1344 this.payloadData = null;
1345 this.artifactChecksum = null;
1347 this.payloadData = Base64.encodeBase64String(payloadData);
1348 this.artifactChecksum = GeneralUtility.calculateMD5Base64EncodedByByteArray(payloadData);
1350 this.artifactUniqueId = artifactUniqueId;
1355 * The artifacts Definition saved by their structure
1357 private class ArtifactsInfo {
1358 //Key is the type of artifacts(Informational/Deployment)
1360 //Value is a map between an artifact type and a list of all artifacts of this type
1361 private Map<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> artifactsInfoField;
1363 public ArtifactsInfo() {
1364 this.artifactsInfoField = new EnumMap<>(ArtifactGroupTypeEnum.class);
1367 public Map<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> getArtifactsInfo() {
1368 return artifactsInfoField;
1371 public void addArtifactsToGroup(ArtifactGroupTypeEnum artifactGroup, Map<String, List<ArtifactDefinition>> artifactsDefinition) {
1372 if (artifactsInfoField.get(artifactGroup) == null) {
1373 artifactsInfoField.put(artifactGroup, artifactsDefinition);
1375 Map<String, List<ArtifactDefinition>> artifactTypeEnumListMap = artifactsInfoField.get(artifactGroup);
1376 artifactTypeEnumListMap.putAll(artifactsDefinition);
1377 artifactsInfoField.put(artifactGroup, artifactTypeEnumListMap);
1381 public boolean isEmpty() {
1382 return artifactsInfoField.isEmpty();
1385 public boolean isNotEmpty() {
1391 * The artifacts of the component and of all its composed instances
1393 private class ComponentTypeArtifacts {
1395 private ArtifactsInfo componentArtifacts; //component artifacts (describes the Informational Deployment folders)
1397 private Map<String, ArtifactsInfo> componentInstancesArtifacts; //artifacts of the composed instances mapped by the resourceInstance normalized name (describes the Resources folder)
1399 public ComponentTypeArtifacts() {
1400 componentArtifacts = new ArtifactsInfo();
1401 componentInstancesArtifacts = new HashMap<>();
1404 public ArtifactsInfo getComponentArtifacts() {
1405 return componentArtifacts;
1408 public void setComponentArtifacts(ArtifactsInfo artifactsInfo) {
1409 this.componentArtifacts = artifactsInfo;
1412 public Map<String, ArtifactsInfo> getComponentInstancesArtifacts() {
1413 return componentInstancesArtifacts;
1416 public void addComponentInstancesArtifacts(String normalizedName, ArtifactsInfo artifactsInfo) {
1417 componentInstancesArtifacts.put(normalizedName, artifactsInfo);
1421 private class ComponentArtifacts {
1423 //artifacts of the component and CI's artifacts contained in it's composition (represents Informational, Deployment & Resource folders of main component)
1424 private ComponentTypeArtifacts mainTypeAndCIArtifacts;
1425 //artifacts of all component types mapped by their tosca name
1426 private Map<String, ComponentTypeArtifacts> componentTypeArtifacts;
1428 public ComponentArtifacts() {
1429 mainTypeAndCIArtifacts = new ComponentTypeArtifacts();
1430 componentTypeArtifacts = new HashMap<>();
1433 public ComponentTypeArtifacts getMainTypeAndCIArtifacts() {
1434 return mainTypeAndCIArtifacts;
1437 public void setMainTypeAndCIArtifacts(ComponentTypeArtifacts componentInstanceArtifacts) {
1438 this.mainTypeAndCIArtifacts = componentInstanceArtifacts;
1441 public Map<String, ComponentTypeArtifacts> getComponentTypeArtifacts() {
1442 return componentTypeArtifacts;
1446 private class CsarDefinition {
1448 private ComponentArtifacts componentArtifacts;
1450 // add list of tosca artifacts and meta describes CSAR zip root
1451 public CsarDefinition(ComponentArtifacts componentArtifacts) {
1452 this.componentArtifacts = componentArtifacts;
1455 public ComponentArtifacts getComponentArtifacts() {
1456 return componentArtifacts;