3597c5c23c21332ac2a69d738b1c0d5aca32fee9
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / tosca / CsarUtils.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
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
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
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=========================================================
19  */
20 package org.openecomp.sdc.be.tosca;
21
22 import static org.openecomp.sdc.be.tosca.ComponentCache.MergeStrategy.overwriteIfSameVersions;
23 import static org.openecomp.sdc.be.tosca.FJToVavrHelper.Try0.fromEither;
24
25 import fj.F;
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;
32 import java.io.File;
33 import java.io.IOException;
34 import java.text.SimpleDateFormat;
35 import java.util.ArrayList;
36 import java.util.Arrays;
37 import java.util.Date;
38 import java.util.EnumMap;
39 import java.util.HashMap;
40 import java.util.HashSet;
41 import java.util.List;
42 import java.util.Map;
43 import java.util.Map.Entry;
44 import java.util.Objects;
45 import java.util.Optional;
46 import java.util.Set;
47 import java.util.TimeZone;
48 import java.util.function.Function;
49 import java.util.function.Predicate;
50 import java.util.function.Supplier;
51 import java.util.regex.Matcher;
52 import java.util.regex.Pattern;
53 import java.util.stream.Collectors;
54 import java.util.stream.Stream;
55 import java.util.zip.ZipEntry;
56 import java.util.zip.ZipInputStream;
57 import java.util.zip.ZipOutputStream;
58 import lombok.Getter;
59 import lombok.Setter;
60 import org.apache.commons.codec.binary.Base64;
61 import org.apache.commons.collections.CollectionUtils;
62 import org.apache.commons.collections.MapUtils;
63 import org.apache.commons.io.output.ByteArrayOutputStream;
64 import org.apache.commons.lang.WordUtils;
65 import org.apache.commons.lang3.tuple.ImmutablePair;
66 import org.apache.commons.lang3.tuple.ImmutableTriple;
67 import org.apache.commons.lang3.tuple.Triple;
68 import org.onap.sdc.tosca.services.YamlUtil;
69 import org.openecomp.sdc.be.components.impl.ImportUtils;
70 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
71 import org.openecomp.sdc.be.config.ArtifactConfigManager;
72 import org.openecomp.sdc.be.config.ArtifactConfiguration;
73 import org.openecomp.sdc.be.config.ComponentType;
74 import org.openecomp.sdc.be.config.ConfigurationManager;
75 import org.openecomp.sdc.be.dao.api.ActionStatus;
76 import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao;
77 import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
78 import org.openecomp.sdc.be.dao.cassandra.SdcSchemaFilesCassandraDao;
79 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
80 import org.openecomp.sdc.be.datatypes.elements.OperationDataDefinition;
81 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
82 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
83 import org.openecomp.sdc.be.impl.ComponentsUtils;
84 import org.openecomp.sdc.be.model.ArtifactDefinition;
85 import org.openecomp.sdc.be.model.Component;
86 import org.openecomp.sdc.be.model.ComponentInstance;
87 import org.openecomp.sdc.be.model.InterfaceDefinition;
88 import org.openecomp.sdc.be.model.LifecycleStateEnum;
89 import org.openecomp.sdc.be.model.Resource;
90 import org.openecomp.sdc.be.model.Service;
91 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade;
92 import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter;
93 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
94 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
95 import org.openecomp.sdc.be.plugins.CsarEntryGenerator;
96 import org.openecomp.sdc.be.resources.data.DAOArtifactData;
97 import org.openecomp.sdc.be.tosca.utils.OperationArtifactUtil;
98 import org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum;
99 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
100 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
101 import org.openecomp.sdc.common.impl.ExternalConfiguration;
102 import org.openecomp.sdc.common.log.elements.LoggerSupportability;
103 import org.openecomp.sdc.common.log.enums.LoggerSupportabilityActions;
104 import org.openecomp.sdc.common.log.enums.StatusCode;
105 import org.openecomp.sdc.common.log.wrappers.Logger;
106 import org.openecomp.sdc.common.util.GeneralUtility;
107 import org.openecomp.sdc.common.util.ValidationUtils;
108 import org.openecomp.sdc.common.zip.ZipUtils;
109 import org.openecomp.sdc.exception.ResponseFormat;
110 import org.springframework.beans.factory.annotation.Autowired;
111 import org.yaml.snakeyaml.Yaml;
112
113 /**
114  * @author tg851x
115  */
116 @org.springframework.stereotype.Component("csar-utils")
117 public class CsarUtils {
118
119     public static final String NODES_YML = "nodes.yml";
120     public static final String ARTIFACTS_PATH = "Artifacts/";
121     public static final String WORKFLOW_ARTIFACT_DIR = "Workflows" + File.separator + "BPMN" + File.separator;
122     public static final String DEPLOYMENT_ARTIFACTS_DIR = "Deployment" + File.separator;
123     public static final String ARTIFACTS = "Artifacts";
124     public static final String ARTIFACT_CREATED_FROM_CSAR = "Artifact created from csar";
125     private static final Logger log = Logger.getLogger(CsarUtils.class);
126     private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(CsarUtils.class.getName());
127     private static final String PATH_DELIMITER = "/";
128     private static final String CONFORMANCE_LEVEL = ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel();
129     private static final String SDC_VERSION = ExternalConfiguration.getAppVersion();
130     private static final String RESOURCES_PATH = "Resources/";
131     private static final String DEFINITIONS_PATH = "Definitions/";
132     private static final String CSAR_META_VERSION = "1.0";
133     private static final String CSAR_META_PATH_FILE_NAME = "csar.meta";
134     private static final String TOSCA_META_PATH_FILE_NAME = "TOSCA-Metadata/TOSCA.meta";
135     private static final String TOSCA_META_VERSION = "1.0";
136     private static final String CSAR_VERSION = "1.1";
137     // add manifest
138     private static final String Service_Manifest = "NS.mf";
139     private static final String DEFINITION = "Definitions";
140     private static final String DEL_PATTERN = "([/\\\\]+)";
141     private static final String WORD_PATTERN = "\\w\\_\\@\\-\\.\\s]+)";
142     public static final String VALID_ENGLISH_ARTIFACT_NAME = "([" + WORD_PATTERN;
143     public static final String VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN = ARTIFACTS + DEL_PATTERN +
144         // Artifact Group (i.e Deployment/Informational)
145         VALID_ENGLISH_ARTIFACT_NAME + DEL_PATTERN +
146         // Artifact Type
147         VALID_ENGLISH_ARTIFACT_NAME + DEL_PATTERN +
148         // Artifact Any File Name
149         ".+";
150     public static final String SERVICE_TEMPLATE_PATH_PATTERN = DEFINITION + DEL_PATTERN +
151         // Service Template File Name
152         VALID_ENGLISH_ARTIFACT_NAME;
153     private static final String VALID_ENGLISH_ARTIFACT_NAME_WITH_DIGITS = "([\\d" + WORD_PATTERN;
154     private static final String ARTIFACT_NAME_UNIQUE_ID = "ArtifactName {}, unique ID {}";
155     private static final String VFC_NODE_TYPE_ARTIFACTS_PATH_PATTERN =
156         ARTIFACTS + DEL_PATTERN + ImportUtils.Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + VALID_ENGLISH_ARTIFACT_NAME_WITH_DIGITS + DEL_PATTERN
157             + VALID_ENGLISH_ARTIFACT_NAME_WITH_DIGITS + DEL_PATTERN + VALID_ENGLISH_ARTIFACT_NAME_WITH_DIGITS + DEL_PATTERN
158             + VALID_ENGLISH_ARTIFACT_NAME_WITH_DIGITS;
159     private static final String BLOCK_0_TEMPLATE = "SDC-TOSCA-Meta-File-Version: %s\nSDC-TOSCA-Definitions-Version: %s\n";
160     @Autowired
161     protected ToscaOperationFacade toscaOperationFacade;
162     @Autowired
163     private SdcSchemaFilesCassandraDao sdcSchemaFilesCassandraDao;
164     @Autowired
165     private ArtifactCassandraDao artifactCassandraDao;
166     @Autowired
167     private ComponentsUtils componentsUtils;
168     @Autowired
169     private ToscaExportHandler toscaExportUtils;
170     @Autowired(required = false)
171     private List<CsarEntryGenerator> generators;
172     private String versionFirstThreeOctets;
173
174     public CsarUtils() {
175         if (SDC_VERSION != null && !SDC_VERSION.isEmpty()) {
176             Matcher matcher = Pattern.compile("(?!\\.)(\\d+(\\.\\d+)+)(?![\\d\\.])").matcher(SDC_VERSION);
177             matcher.find();
178             setVersionFirstThreeOctets(matcher.group(0));
179         } else {
180             setVersionFirstThreeOctets("");
181         }
182     }
183
184     private static <L, R> F<L, Either<L, R>> iff(Predicate<L> p, Function<L, Either<L, R>> ifTrue) {
185         return l -> p.test(l) ? ifTrue.apply(l) : Either.left(l);
186     }
187
188     private static <A, B> F<A, B> iff(Predicate<A> p, Supplier<B> s, Function<A, B> orElse) {
189         return a -> p.test(a) ? s.get() : orElse.apply(a);
190     }
191
192     /**
193      * Extracts artifacts of VFCs from CSAR
194      *
195      * @param csar
196      * @return Map of <String, List<ArtifactDefinition>> the contains Lists of artifacts according vfcToscaNamespace
197      */
198     public static Map<String, List<ArtifactDefinition>> extractVfcsArtifactsFromCsar(Map<String, byte[]> csar) {
199         Map<String, List<ArtifactDefinition>> artifacts = new HashMap<>();
200         if (csar != null) {
201             log.debug("************* Going to extract VFCs artifacts from Csar. ");
202             Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
203             csar.entrySet().stream()
204                 // filter CSAR entry by node type artifact path
205                 .filter(e -> Pattern.compile(VFC_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey()).matches())
206                 // extract ArtifactDefinition from CSAR entry for each entry with matching artifact path
207                 .forEach(e -> extractVfcArtifact(e, collectedWarningMessages).ifPresent(ip -> addExtractedVfcArtifact(ip, artifacts)));
208             // add counter suffix to artifact labels
209             handleWarningMessages(collectedWarningMessages);
210         }
211         return artifacts;
212     }
213
214     /**
215      * Print warnings to log
216      *
217      * @param collectedWarningMessages
218      */
219     public static void handleWarningMessages(Map<String, Set<List<String>>> collectedWarningMessages) {
220         collectedWarningMessages.entrySet().stream()
221             // for each vfc
222             .forEach(e -> e.getValue().stream()
223                 // add each warning message to log
224                 .forEach(args -> log.warn(e.getKey(), args.toArray())));
225     }
226
227     private static void addExtractedVfcArtifact(ImmutablePair<String, ArtifactDefinition> extractedVfcArtifact,
228                                                 Map<String, List<ArtifactDefinition>> artifacts) {
229         String vfcToscaNamespace = extractedVfcArtifact.getKey();
230         artifacts.computeIfAbsent(vfcToscaNamespace, k -> new ArrayList<>());
231         artifacts.get(vfcToscaNamespace).add(extractedVfcArtifact.getValue());
232     }
233
234     private static Optional<ImmutablePair<String, ArtifactDefinition>> extractVfcArtifact(Entry<String, byte[]> entry,
235                                                                                           Map<String, Set<List<String>>> collectedWarningMessages) {
236         String[] parsedCsarArtifactPath = entry.getKey().split(PATH_DELIMITER);
237         String groupType = parsedCsarArtifactPath[2].toUpperCase();
238         return detectArtifactGroupType(groupType, collectedWarningMessages).left()
239             .map(buildArtifactDefinitionFromCsarArtifactPath(entry, collectedWarningMessages, parsedCsarArtifactPath))
240             .either(ad -> Optional.of(new ImmutablePair<>(parsedCsarArtifactPath[1], ad)), b -> Optional.empty());
241     }
242
243     private static Either<ArtifactGroupTypeEnum, Boolean> detectArtifactGroupType(String groupType,
244                                                                                   Map<String, Set<List<String>>> collectedWarningMessages) {
245         Either<ArtifactGroupTypeEnum, Boolean> result;
246         try {
247             ArtifactGroupTypeEnum artifactGroupType = ArtifactGroupTypeEnum.findType(groupType.toUpperCase());
248             if (artifactGroupType == null || (artifactGroupType != ArtifactGroupTypeEnum.INFORMATIONAL
249                 && artifactGroupType != ArtifactGroupTypeEnum.DEPLOYMENT)) {
250                 String warningMessage = "Warning - unrecognized artifact group type {} was received.";
251                 List<String> messageArguments = new ArrayList<>();
252                 messageArguments.add(groupType);
253                 if (!collectedWarningMessages.containsKey(warningMessage)) {
254                     Set<List<String>> messageArgumentLists = new HashSet<>();
255                     messageArgumentLists.add(messageArguments);
256                     collectedWarningMessages.put(warningMessage, messageArgumentLists);
257                 } else {
258                     collectedWarningMessages.get(warningMessage).add(messageArguments);
259                 }
260                 result = Either.right(false);
261             } else {
262                 result = Either.left(artifactGroupType);
263             }
264         } catch (Exception e) {
265             log.debug("detectArtifactGroupType failed with exception", e);
266             result = Either.right(false);
267         }
268         return result;
269     }
270
271     private static F<ArtifactGroupTypeEnum, ArtifactDefinition> buildArtifactDefinitionFromCsarArtifactPath(Entry<String, byte[]> entry,
272                                                                                                             Map<String, Set<List<String>>> collectedWarningMessages,
273                                                                                                             String[] parsedCsarArtifactPath) {
274         return artifactGroupType -> {
275             ArtifactDefinition artifact;
276             artifact = new ArtifactDefinition();
277             artifact.setArtifactGroupType(artifactGroupType);
278             artifact.setArtifactType(
279                 detectArtifactTypeVFC(artifactGroupType, parsedCsarArtifactPath[3], parsedCsarArtifactPath[1], collectedWarningMessages));
280             artifact.setArtifactName(ValidationUtils.normalizeFileName(parsedCsarArtifactPath[parsedCsarArtifactPath.length - 1]));
281             artifact.setPayloadData(Base64.encodeBase64String(entry.getValue()));
282             artifact.setArtifactDisplayName(
283                 artifact.getArtifactName().lastIndexOf('.') > 0 ? artifact.getArtifactName().substring(0, artifact.getArtifactName().lastIndexOf('.'))
284                     : artifact.getArtifactName());
285             artifact.setArtifactLabel(ValidationUtils.normalizeArtifactLabel(artifact.getArtifactName()));
286             artifact.setDescription(ARTIFACT_CREATED_FROM_CSAR);
287             artifact.setIsFromCsar(true);
288             artifact.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(entry.getValue()));
289             return artifact;
290         };
291     }
292
293     /**
294      * This method checks the artifact GroupType & Artifact Type. <br> if there is any problem warning messages are added to collectedWarningMessages
295      *
296      * @param artifactPath
297      * @param collectedWarningMessages
298      * @return
299      */
300     public static Either<NonMetaArtifactInfo, Boolean> validateNonMetaArtifact(String artifactPath, byte[] payloadData,
301                                                                                Map<String, Set<List<String>>> collectedWarningMessages) {
302         try {
303             String[] parsedArtifactPath = artifactPath.split(PATH_DELIMITER);
304             String groupType = parsedArtifactPath[1];
305             String receivedTypeName = parsedArtifactPath[2];
306             String artifactFileNameType = parsedArtifactPath[3];
307             return detectArtifactGroupType(groupType, collectedWarningMessages).left().bind(artifactGroupType -> {
308                 String artifactType = detectArtifactTypeVF(artifactGroupType, receivedTypeName, collectedWarningMessages);
309                 return Either
310                     .left(new NonMetaArtifactInfo(artifactFileNameType, artifactPath, artifactType, artifactGroupType, payloadData, null, true));
311             });
312         } catch (Exception e) {
313             log.debug("detectArtifactGroupType failed with exception", e);
314             return Either.right(false);
315         }
316     }
317
318     private static String detectArtifactTypeVFC(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, String parentVfName,
319                                                 Map<String, Set<List<String>>> collectedWarningMessages) {
320         String warningMessage = "Warning - artifact type {} that was provided for VFC {} is not recognized.";
321         return detectArtifactType(artifactGroupType, receivedTypeName, warningMessage, collectedWarningMessages, parentVfName);
322     }
323
324     private static String detectArtifactTypeVF(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName,
325                                                Map<String, Set<List<String>>> collectedWarningMessages) {
326         String warningMessage = "Warning - artifact type {} that was provided for VF is not recognized.";
327         return detectArtifactType(artifactGroupType, receivedTypeName, warningMessage, collectedWarningMessages);
328     }
329
330     private static String detectArtifactType(final ArtifactGroupTypeEnum artifactGroupType, final String receivedTypeName,
331                                              final String warningMessage, final Map<String, Set<List<String>>> collectedWarningMessages,
332                                              final String... arguments) {
333         final ArtifactConfiguration artifactConfiguration = ArtifactConfigManager.getInstance()
334             .find(receivedTypeName, artifactGroupType, ComponentType.RESOURCE).orElse(null);
335         if (artifactConfiguration == null) {
336             final List<String> messageArguments = new ArrayList<>();
337             messageArguments.add(receivedTypeName);
338             messageArguments.addAll(Arrays.asList(arguments));
339             if (!collectedWarningMessages.containsKey(warningMessage)) {
340                 final Set<List<String>> messageArgumentLists = new HashSet<>();
341                 messageArgumentLists.add(messageArguments);
342                 collectedWarningMessages.put(warningMessage, messageArgumentLists);
343             } else {
344                 collectedWarningMessages.get(warningMessage).add(messageArguments);
345             }
346         }
347         return artifactConfiguration == null ? ArtifactTypeEnum.OTHER.getType() : receivedTypeName;
348     }
349
350     /**
351      * @param component
352      * @param getFromCS
353      * @param isInCertificationRequest
354      * @return
355      */
356     public Either<byte[], ResponseFormat> createCsar(Component component, boolean getFromCS, boolean isInCertificationRequest) {
357         loggerSupportability
358             .log(LoggerSupportabilityActions.GENERATE_CSAR, StatusCode.STARTED, "Starting to create Csar for component {} ", component.getName());
359         final String createdBy = component.getCreatorFullName();
360         String fileName;
361         Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
362         ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
363         fileName = artifactDefinition.getArtifactName();
364         String toscaConformanceLevel = ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel();
365         String csarBlock0 = createCsarBlock0(CSAR_META_VERSION, toscaConformanceLevel);
366         byte[] csarBlock0Byte = csarBlock0.getBytes();
367         final String toscaBlock0 = createToscaBlock0(TOSCA_META_VERSION, CSAR_VERSION, createdBy, fileName);
368         byte[] toscaBlock0Byte = toscaBlock0.getBytes();
369         return generateCsarZip(csarBlock0Byte, toscaBlock0Byte, component, getFromCS, isInCertificationRequest).left().map(responseFormat -> {
370             loggerSupportability
371                 .log(LoggerSupportabilityActions.GENERATE_CSAR, StatusCode.COMPLETE, "Ended create Csar for component {} ", component.getName());
372             return responseFormat;
373         });
374     }
375
376     private Either<byte[], ResponseFormat> generateCsarZip(byte[] csarBlock0Byte, byte[] toscaBlock0Byte, Component component, boolean getFromCS,
377                                                            boolean isInCertificationRequest) {
378         try (ByteArrayOutputStream out = new ByteArrayOutputStream(); ZipOutputStream zip = new ZipOutputStream(out)) {
379             zip.putNextEntry(new ZipEntry(CSAR_META_PATH_FILE_NAME));
380             zip.write(csarBlock0Byte);
381             zip.putNextEntry(new ZipEntry(TOSCA_META_PATH_FILE_NAME));
382             zip.write(toscaBlock0Byte);
383             Either<ZipOutputStream, ResponseFormat> populateZip = populateZip(component, getFromCS, zip, isInCertificationRequest);
384             if (populateZip.isRight()) {
385                 log.debug("Failed to populate CSAR zip file {}. Please fix DB table accordingly ", populateZip.right().value());
386                 return Either.right(populateZip.right().value());
387             }
388             zip.finish();
389             byte[] byteArray = out.toByteArray();
390             return Either.left(byteArray);
391         } catch (IOException e) {
392             log.debug("Failed with IOexception to create CSAR zip for component {}. Please fix DB table accordingly ", component.getUniqueId(), e);
393             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
394             return Either.right(responseFormat);
395         }
396     }
397
398     private Either<ZipOutputStream, ResponseFormat> populateZip(Component component, boolean getFromCS, ZipOutputStream zip,
399                                                                 boolean isInCertificationRequest) throws IOException {
400         ArtifactDefinition artifactDef = component.getToscaArtifacts().get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
401         Either<ToscaRepresentation, ResponseFormat> toscaRepresentation = fetchToscaRepresentation(component, getFromCS, artifactDef);
402         // This should not be done but in order to keep the refactoring small enough we stop here.
403
404         // TODO: Refactor the rest of this function
405         byte[] mainYaml;
406         List<Triple<String, String, Component>> dependencies;
407         if (toscaRepresentation.isLeft()) {
408             mainYaml = toscaRepresentation.left().value().getMainYaml();
409             dependencies = toscaRepresentation.left().value().getDependencies().getOrElse(new ArrayList<>());
410         } else {
411             return Either.right(toscaRepresentation.right().value());
412         }
413         String fileName = artifactDef.getArtifactName();
414         zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + fileName));
415         zip.write(mainYaml);
416         LifecycleStateEnum lifecycleState = component.getLifecycleState();
417         addServiceMf(component, zip, lifecycleState, isInCertificationRequest, fileName, mainYaml);
418         //US798487 - Abstraction of complex types
419         if (!ModelConverter.isAtomicComponent(component)) {
420             log.debug("Component {} is complex - generating abstract type for it..", component.getName());
421             writeComponentInterface(component, zip, fileName, false);
422         }
423         //UID <cassandraId,filename,component>
424         Either<ZipOutputStream, ResponseFormat> zipOutputStreamOrResponseFormat = getZipOutputStreamResponseFormatEither(zip, dependencies);
425         if (zipOutputStreamOrResponseFormat != null && zipOutputStreamOrResponseFormat.isRight()) {
426             return zipOutputStreamOrResponseFormat;
427         }
428         //retrieve SDC.zip from Cassandra
429         Either<byte[], ResponseFormat> latestSchemaFilesFromCassandra = getLatestSchemaFilesFromCassandra();
430         if (latestSchemaFilesFromCassandra.isRight()) {
431             log.error("Error retrieving SDC Schema files from cassandra");
432             return Either.right(latestSchemaFilesFromCassandra.right().value());
433         }
434         final byte[] schemaFileZip = latestSchemaFilesFromCassandra.left().value();
435         final List<String> nodesFromPackage = findNonRootNodesFromPackage(dependencies);
436         //add files from retrieved SDC.zip to Definitions folder in CSAR
437         addSchemaFilesFromCassandra(zip, schemaFileZip, nodesFromPackage);
438         Either<CsarDefinition, ResponseFormat> collectedComponentCsarDefinition = collectComponentCsarDefinition(component);
439         if (collectedComponentCsarDefinition.isRight()) {
440             return Either.right(collectedComponentCsarDefinition.right().value());
441         }
442         if (generators != null) {
443             for (CsarEntryGenerator generator : generators) {
444                 log.debug("Invoking CsarEntryGenerator: {}", generator.getClass().getName());
445                 for (Entry<String, byte[]> pluginGeneratedFile : generator.generateCsarEntries(component).entrySet()) {
446                     zip.putNextEntry(new ZipEntry(pluginGeneratedFile.getKey()));
447                     zip.write(pluginGeneratedFile.getValue());
448                 }
449             }
450         }
451         return writeAllFilesToCsar(component, collectedComponentCsarDefinition.left().value(), zip, isInCertificationRequest);
452     }
453
454     private void addServiceMf(Component component, ZipOutputStream zip, LifecycleStateEnum lifecycleState, boolean isInCertificationRequest,
455                               String fileName, byte[] mainYaml) throws IOException {
456         // add mf
457         if ((component.getComponentType() == ComponentTypeEnum.SERVICE) && (lifecycleState != LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) {
458             String serviceName = component.getName();
459             String createdBy = component.getCreatorUserId();
460             String serviceVersion;
461             if (isInCertificationRequest) {
462                 int tmp = Integer.valueOf(component.getVersion().split("\\.")[0]) + 1;
463                 serviceVersion = String.valueOf(tmp) + ".0";
464             } else {
465                 serviceVersion = component.getVersion();
466             }
467             SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'");
468             format.setTimeZone(TimeZone.getTimeZone("UTC"));
469             Date date = new Date();
470             String releaseTime = format.format(date);
471             if (component.getCategories() == null || component.getCategories().get(0) == null) {
472                 return;
473             }
474             String serviceType = component.getCategories().get(0).getName();
475             String description = component.getDescription();
476             String serviceTemplate = DEFINITIONS_PATH + fileName;
477             String hash = GeneralUtility.calculateMD5Base64EncodedByByteArray(mainYaml);
478             String nsMfBlock0 = createNsMfBlock0(serviceName, createdBy, serviceVersion, releaseTime, serviceType, description, serviceTemplate,
479                 hash);
480             byte[] nsMfBlock0Byte = nsMfBlock0.getBytes();
481             zip.putNextEntry(new ZipEntry(Service_Manifest));
482             zip.write(nsMfBlock0Byte);
483         }
484     }
485
486     private Either<ToscaRepresentation, ResponseFormat> fetchToscaRepresentation(Component component, boolean getFromCS,
487                                                                                  ArtifactDefinition artifactDef) {
488         LifecycleStateEnum lifecycleState = component.getLifecycleState();
489         boolean shouldBeFetchedFromCassandra =
490             getFromCS || !(lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
491         Either<ToscaRepresentation, ResponseFormat> toscaRepresentation =
492             shouldBeFetchedFromCassandra ? fetchToscaRepresentation(artifactDef) : generateToscaRepresentation(component);
493         return toscaRepresentation.left()
494             .bind(iff(myd -> !myd.getDependencies().isDefined(), myd -> fetchToscaTemplateDependencies(myd.getMainYaml(), component)));
495     }
496
497     private Either<ToscaRepresentation, ResponseFormat> fetchToscaTemplateDependencies(byte[] mainYml, Component component) {
498         return toscaExportUtils.getDependencies(component).right().map(toscaError -> {
499             log.debug("Failed to retrieve dependencies for component {}, error {}", component.getUniqueId(), toscaError);
500             return componentsUtils.getResponseFormat(componentsUtils.convertFromToscaError(toscaError));
501         }).left().map(tt -> ToscaRepresentation.make(mainYml, tt));
502     }
503
504     private Either<ToscaRepresentation, ResponseFormat> generateToscaRepresentation(Component component) {
505         return toscaExportUtils.exportComponent(component).right().map(toscaError -> {
506             log.debug("exportComponent failed {}", toscaError);
507             return componentsUtils.getResponseFormat(componentsUtils.convertFromToscaError(toscaError));
508         });
509     }
510
511     private Either<ToscaRepresentation, ResponseFormat> fetchToscaRepresentation(ArtifactDefinition artifactDef) {
512         return getFromCassandra(artifactDef.getEsId()).right().map(as -> {
513             log.debug(ARTIFACT_NAME_UNIQUE_ID, artifactDef.getArtifactName(), artifactDef.getUniqueId());
514             return componentsUtils.getResponseFormat(as);
515         }).left().map(ToscaRepresentation::make);
516     }
517
518     /**
519      * Create a list of all derived nodes found on the package
520      *
521      * @param dependencies all node dependencies
522      * @return a list of nodes
523      */
524     private List<String> findNonRootNodesFromPackage(final List<Triple<String, String, Component>> dependencies) {
525         final List<String> nodes = new ArrayList<>();
526         if (CollectionUtils.isNotEmpty(dependencies)) {
527             final String NATIVE_ROOT = "tosca.nodes.Root";
528             dependencies.forEach(dependency -> {
529                 if (dependency.getRight() instanceof Resource) {
530                     final Resource resource = (Resource) dependency.getRight();
531                     if (CollectionUtils.isNotEmpty(resource.getDerivedList())) {
532                         resource.getDerivedList().stream().filter(node -> !nodes.contains(node) && !NATIVE_ROOT.equalsIgnoreCase(node))
533                             .forEach(node -> nodes.add(node));
534                     }
535                 }
536             });
537         }
538         return nodes;
539     }
540
541     /**
542      * Writes a new zip entry
543      *
544      * @param zipInputStream the zip entry to be read
545      * @return a map of the given zip entry
546      */
547     private Map<String, Object> readYamlZipEntry(final ZipInputStream zipInputStream) throws IOException {
548         final int initSize = 2048;
549         final StringBuilder zipEntry = new StringBuilder();
550         final byte[] buffer = new byte[initSize];
551         int read = 0;
552         while ((read = zipInputStream.read(buffer, 0, initSize)) >= 0) {
553             zipEntry.append(new String(buffer, 0, read));
554         }
555         return (Map<String, Object>) new Yaml().load(zipEntry.toString());
556     }
557
558     /**
559      * Filters and removes all duplicated nodes found
560      *
561      * @param nodesFromPackage      a List of all derived nodes found on the given package
562      * @param nodesFromArtifactFile represents the nodes.yml file stored in Cassandra
563      * @return a nodes Map updated
564      */
565     private Map<String, Object> updateNodeYml(final List<String> nodesFromPackage, final Map<String, Object> nodesFromArtifactFile) {
566         if (MapUtils.isNotEmpty(nodesFromArtifactFile)) {
567             final String nodeTypeBlock = ToscaTagNamesEnum.NODE_TYPES.getElementName();
568             final Map<String, Object> nodeTypes = (Map<String, Object>) nodesFromArtifactFile.get(nodeTypeBlock);
569             nodesFromPackage.stream().filter(nodeTypes::containsKey).forEach(nodeTypes::remove);
570             nodesFromArtifactFile.replace(nodeTypeBlock, nodeTypes);
571         }
572         return nodesFromArtifactFile;
573     }
574
575     /**
576      * Updates the zip entry from the given parameters
577      *
578      * @param byteArrayOutputStream an output stream in which the data is written into a byte array.
579      * @param nodesYaml             a Map of nodes to be written
580      */
581     private void updateZipEntry(final ByteArrayOutputStream byteArrayOutputStream, final Map<String, Object> nodesYaml) throws IOException {
582         if (MapUtils.isNotEmpty(nodesYaml)) {
583             byteArrayOutputStream.write(new YamlUtil().objectToYaml(nodesYaml).getBytes());
584         }
585     }
586
587     private Either<ZipOutputStream, ResponseFormat> getZipOutputStreamResponseFormatEither(ZipOutputStream zip,
588                                                                                            List<Triple<String, String, Component>> dependencies)
589         throws IOException {
590         ComponentCache innerComponentsCache = ComponentCache.overwritable(overwriteIfSameVersions()).onMerge((oldValue, newValue) -> {
591             log.warn("Overwriting component invariantID {} of version {} with a newer version {}", oldValue.id, oldValue.getComponentVersion(),
592                 newValue.getComponentVersion());
593         });
594         if (dependencies != null && !dependencies.isEmpty()) {
595             for (Triple<String, String, Component> d : dependencies) {
596                 String cassandraId = d.getMiddle();
597                 Component childComponent = d.getRight();
598                 Either<byte[], ResponseFormat> entryData = getEntryData(cassandraId, childComponent).right()
599                     .map(x -> componentsUtils.getResponseFormat(x));
600                 if (entryData.isRight()) {
601                     return Either.right(entryData.right().value());
602                 }
603                 //fill innerComponentsCache
604                 String fileName = d.getLeft();
605                 innerComponentsCache.put(cassandraId, fileName, childComponent);
606                 addInnerComponentsToCache(innerComponentsCache, childComponent);
607             }
608             //add inner components to CSAR
609             return addInnerComponentsToCSAR(zip, innerComponentsCache);
610         }
611         return null;
612     }
613
614     private Either<ZipOutputStream, ResponseFormat> addInnerComponentsToCSAR(ZipOutputStream zip, ComponentCache innerComponentsCache)
615         throws IOException {
616         for (ImmutableTriple<String, String, Component> ict : innerComponentsCache.iterable()) {
617             Component innerComponent = ict.getRight();
618             String icFileName = ict.getMiddle();
619             // add component to zip
620             Either<Tuple2<byte[], ZipEntry>, ResponseFormat> zipEntry = toZipEntry(ict);
621             // TODO: this should not be done, we should instead compose this either further,
622
623             // but in order to keep this refactoring small, we'll stop here.
624             if (zipEntry.isRight()) {
625                 return Either.right(zipEntry.right().value());
626             }
627             Tuple2<byte[], ZipEntry> value = zipEntry.left().value();
628             zip.putNextEntry(value._2);
629             zip.write(value._1);
630             // add component interface to zip
631             if (!ModelConverter.isAtomicComponent(innerComponent)) {
632                 writeComponentInterface(innerComponent, zip, icFileName, true);
633             }
634         }
635         return null;
636     }
637
638     private Either<Tuple2<byte[], ZipEntry>, ResponseFormat> toZipEntry(ImmutableTriple<String, String, Component> cachedEntry) {
639         String cassandraId = cachedEntry.getLeft();
640         String fileName = cachedEntry.getMiddle();
641         Component innerComponent = cachedEntry.getRight();
642         return getEntryData(cassandraId, innerComponent).right().map(status -> {
643             log.debug("Failed adding to zip component {}, error {}", cassandraId, status);
644             return componentsUtils.getResponseFormat(status);
645         }).left().map(content -> new Tuple2<>(content, new ZipEntry(DEFINITIONS_PATH + fileName)));
646     }
647
648     /**
649      * Writes to a CSAR zip from casandra schema data
650      *
651      * @param zipOutputStream  stores the input stream content
652      * @param schemaFileZip    zip data from Cassandra
653      * @param nodesFromPackage list of all nodes found on the onboarded package
654      */
655     private void addSchemaFilesFromCassandra(final ZipOutputStream zipOutputStream, final byte[] schemaFileZip, final List<String> nodesFromPackage) {
656         final int initSize = 2048;
657         log.debug("Starting copy from Schema file zip to CSAR zip");
658         try (final ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(
659             schemaFileZip)); final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); final BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(
660             byteArrayOutputStream, initSize)) {
661             ZipEntry entry;
662             while ((entry = zipInputStream.getNextEntry()) != null) {
663                 ZipUtils.checkForZipSlipInRead(entry);
664                 final String entryName = entry.getName();
665                 int readSize = initSize;
666                 final byte[] entryData = new byte[initSize];
667                 if (shouldZipEntryBeHandled(entryName)) {
668                     if (NODES_YML.equalsIgnoreCase(entryName)) {
669                         handleNode(zipInputStream, byteArrayOutputStream, nodesFromPackage);
670                     } else {
671                         while ((readSize = zipInputStream.read(entryData, 0, readSize)) != -1) {
672                             bufferedOutputStream.write(entryData, 0, readSize);
673                         }
674                         bufferedOutputStream.flush();
675                     }
676                     byteArrayOutputStream.flush();
677                     zipOutputStream.putNextEntry(new ZipEntry(DEFINITIONS_PATH + entryName));
678                     zipOutputStream.write(byteArrayOutputStream.toByteArray());
679                     zipOutputStream.flush();
680                     byteArrayOutputStream.reset();
681                 }
682             }
683         } catch (final Exception e) {
684             log.error("Error while writing the SDC schema file to the CSAR", e);
685             throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
686         }
687         log.debug("Finished copy from Schema file zip to CSAR zip");
688     }
689
690     /**
691      * Checks if the zip entry should or should not be added to the CSAR based on the given global type list
692      *
693      * @param entryName the zip entry name
694      * @return true if the zip entry should be handled
695      */
696     private boolean shouldZipEntryBeHandled(final String entryName) {
697         return ConfigurationManager.getConfigurationManager().getConfiguration().getGlobalCsarImports().stream()
698             .anyMatch(entry -> entry.contains(entryName));
699     }
700
701     /**
702      * Handles the nodes.yml zip entry, updating the nodes.yml to avoid duplicated nodes on it.
703      *
704      * @param zipInputStream        the zip entry to be read
705      * @param byteArrayOutputStream an output stream in which the data is written into a byte array.
706      * @param nodesFromPackage      list of all nodes found on the onboarded package
707      */
708     private void handleNode(final ZipInputStream zipInputStream, final ByteArrayOutputStream byteArrayOutputStream,
709                             final List<String> nodesFromPackage) throws IOException {
710         final Map<String, Object> nodesFromArtifactFile = readYamlZipEntry(zipInputStream);
711         final Map<String, Object> nodesYaml = updateNodeYml(nodesFromPackage, nodesFromArtifactFile);
712         updateZipEntry(byteArrayOutputStream, nodesYaml);
713     }
714
715     private void addInnerComponentsToCache(ComponentCache componentCache, Component childComponent) {
716         javaListToVavrList(childComponent.getComponentInstances()).filter(ci -> componentCache.notCached(ci.getComponentUid())).forEach(ci -> {
717             // all resource must be only once!
718             Either<Resource, StorageOperationStatus> resource = toscaOperationFacade.getToscaElement(ci.getComponentUid());
719             Component componentRI = checkAndAddComponent(componentCache, ci, resource);
720             //if not atomic - insert inner components as well
721
722             // TODO: This could potentially create a StackOverflowException if the call stack
723
724             // happens to be too large. Tail-recursive optimization should be used here.
725             if (!ModelConverter.isAtomicComponent(componentRI)) {
726                 addInnerComponentsToCache(componentCache, componentRI);
727             }
728         });
729     }
730
731     // TODO: Move this function in FJToVavrHelper.java once Change 108540 is merged
732     private io.vavr.collection.List<ComponentInstance> javaListToVavrList(List<ComponentInstance> componentInstances) {
733         return Option.of(componentInstances).map(io.vavr.collection.List::ofAll).getOrElse(io.vavr.collection.List::empty);
734     }
735
736     private Component checkAndAddComponent(ComponentCache componentCache, ComponentInstance ci, Either<Resource, StorageOperationStatus> resource) {
737         if (resource.isRight()) {
738             log.debug("Failed to fetch resource with id {} for instance {}", ci.getComponentUid(), ci.getName());
739         }
740         Component componentRI = resource.left().value();
741         Map<String, ArtifactDefinition> childToscaArtifacts = componentRI.getToscaArtifacts();
742         ArtifactDefinition childArtifactDefinition = childToscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
743         if (childArtifactDefinition != null) {
744             //add to cache
745             componentCache.put(childArtifactDefinition.getEsId(), childArtifactDefinition.getArtifactName(), componentRI);
746         }
747         return componentRI;
748     }
749
750     private Either<ZipOutputStream, ResponseFormat> writeComponentInterface(Component component, ZipOutputStream zip, String fileName,
751                                                                             boolean isAssociatedComponent) {
752         // TODO: This should not be done but we need this to keep the refactoring small enough to be easily reviewable
753         return writeComponentInterface(component, fileName, isAssociatedComponent, ZipWriter.live(zip))
754             .map(void0 -> Either.<ZipOutputStream, ResponseFormat>left(zip)).recover(th -> {
755                 log.error("#writeComponentInterface - zip writing failed with error: ", th);
756                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
757             }).get();
758     }
759
760     private Try<Void> writeComponentInterface(Component component, String fileName, boolean isAssociatedComponent, ZipWriter zw) {
761         Either<byte[], ToscaError> yml = toscaExportUtils.exportComponentInterface(component, isAssociatedComponent).left()
762             .map(ToscaRepresentation::getMainYaml);
763         return fromEither(yml, ToscaErrorException::new).flatMap(zw.write(DEFINITIONS_PATH + ToscaExportHandler.getInterfaceFilename(fileName)));
764     }
765
766     private Either<byte[], ActionStatus> getEntryData(String cassandraId, Component childComponent) {
767         if (cassandraId == null || cassandraId.isEmpty()) {
768             return toscaExportUtils.exportComponent(childComponent).right().map(toscaErrorToActionStatus(childComponent)).left()
769                 .map(ToscaRepresentation::getMainYaml);
770         } else {
771             return getFromCassandra(cassandraId);
772         }
773     }
774
775     private F<ToscaError, ActionStatus> toscaErrorToActionStatus(Component childComponent) {
776         return toscaError -> {
777             log.debug("Failed to export tosca template for child component {} error {}", childComponent.getUniqueId(), toscaError);
778             return componentsUtils.convertFromToscaError(toscaError);
779         };
780     }
781
782     private Either<byte[], ResponseFormat> getLatestSchemaFilesFromCassandra() {
783         String fto = getVersionFirstThreeOctets();
784         return sdcSchemaFilesCassandraDao.getSpecificSchemaFiles(fto, CONFORMANCE_LEVEL).right().map(schemaFilesFetchDBError(fto)).left()
785             .bind(iff(List::isEmpty, () -> schemaFileFetchError(fto), s -> Either.left(s.iterator().next().getPayloadAsArray())));
786     }
787
788     private F<CassandraOperationStatus, ResponseFormat> schemaFilesFetchDBError(String firstThreeOctets) {
789         return cos -> {
790             log.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}. Please fix DB table accordingly.", firstThreeOctets,
791                 CONFORMANCE_LEVEL);
792             StorageOperationStatus sos = DaoStatusConverter.convertCassandraStatusToStorageStatus(cos);
793             return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(sos));
794         };
795     }
796
797     private Either<byte[], ResponseFormat> schemaFileFetchError(String firstThreeOctets) {
798         log.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}", firstThreeOctets, CONFORMANCE_LEVEL);
799         return Either.right(componentsUtils.getResponseFormat(ActionStatus.TOSCA_SCHEMA_FILES_NOT_FOUND, firstThreeOctets, CONFORMANCE_LEVEL));
800     }
801
802     private Either<byte[], ActionStatus> getFromCassandra(String cassandraId) {
803         return artifactCassandraDao.getArtifact(cassandraId).right().map(cos -> {
804             log.debug("Failed to fetch artifact from Cassandra by id {} error {} ", cassandraId, cos);
805             StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(cos);
806             return componentsUtils.convertFromStorageResponse(storageStatus);
807         }).left().map(DAOArtifactData::getDataAsArray);
808     }
809
810     private String createCsarBlock0(String metaFileVersion, String toscaConformanceLevel) {
811         return String.format(BLOCK_0_TEMPLATE, metaFileVersion, toscaConformanceLevel);
812     }
813
814     private String createToscaBlock0(String metaFileVersion, String csarVersion, String createdBy, String entryDef) {
815         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";
816         return String.format(block0template, metaFileVersion, csarVersion, createdBy, entryDef);
817     }
818
819     private String createNsMfBlock0(String serviceName, String createdBy, String serviceVersion, String releaseTime, String serviceType,
820                                     String description, String serviceTemplate, String hash) {
821         final String block0template = "metadata??\n" + "ns_product_name: %s\n" + "ns_provider_id: %s\n" + "ns_package_version: %s\n" +
822             //"ns_create_date_time: %s\n" +
823             "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";
824         return String.format(block0template, serviceName, createdBy, serviceVersion, releaseTime, serviceType, description, serviceTemplate, hash);
825     }
826
827     private Either<ZipOutputStream, ResponseFormat> writeAllFilesToCsar(Component mainComponent, CsarDefinition csarDefinition,
828                                                                         ZipOutputStream zipstream, boolean isInCertificationRequest)
829         throws IOException {
830         ComponentArtifacts componentArtifacts = csarDefinition.getComponentArtifacts();
831         Either<ZipOutputStream, ResponseFormat> writeComponentArtifactsToSpecifiedPath = writeComponentArtifactsToSpecifiedPath(mainComponent,
832             componentArtifacts, zipstream, ARTIFACTS_PATH, isInCertificationRequest);
833         if (writeComponentArtifactsToSpecifiedPath.isRight()) {
834             return Either.right(writeComponentArtifactsToSpecifiedPath.right().value());
835         }
836         ComponentTypeArtifacts mainTypeAndCIArtifacts = componentArtifacts.getMainTypeAndCIArtifacts();
837         writeComponentArtifactsToSpecifiedPath = writeArtifactsInfoToSpecifiedPath(mainComponent, mainTypeAndCIArtifacts.getComponentArtifacts(),
838             zipstream, ARTIFACTS_PATH, isInCertificationRequest);
839         if (writeComponentArtifactsToSpecifiedPath.isRight()) {
840             return Either.right(writeComponentArtifactsToSpecifiedPath.right().value());
841         }
842         Map<String, ArtifactsInfo> componentInstancesArtifacts = mainTypeAndCIArtifacts.getComponentInstancesArtifacts();
843         Set<String> keySet = componentInstancesArtifacts.keySet();
844         String currentPath = ARTIFACTS_PATH + RESOURCES_PATH;
845         for (String keyAssetName : keySet) {
846             ArtifactsInfo artifactsInfo = componentInstancesArtifacts.get(keyAssetName);
847             String pathWithAssetName = currentPath + keyAssetName + PATH_DELIMITER;
848             writeComponentArtifactsToSpecifiedPath = writeArtifactsInfoToSpecifiedPath(mainComponent, artifactsInfo, zipstream, pathWithAssetName,
849                 isInCertificationRequest);
850             if (writeComponentArtifactsToSpecifiedPath.isRight()) {
851                 return Either.right(writeComponentArtifactsToSpecifiedPath.right().value());
852             }
853         }
854         writeComponentArtifactsToSpecifiedPath = writeOperationsArtifactsToCsar(mainComponent, zipstream);
855         if (writeComponentArtifactsToSpecifiedPath.isRight()) {
856             return Either.right(writeComponentArtifactsToSpecifiedPath.right().value());
857         }
858         return Either.left(zipstream);
859     }
860
861     private Either<ZipOutputStream, ResponseFormat> writeOperationsArtifactsToCsar(Component component, ZipOutputStream zipstream) {
862         if (checkComponentBeforeOperation(component)) {
863             return Either.left(zipstream);
864         }
865         final Map<String, InterfaceDefinition> interfaces = ((Resource) component).getInterfaces();
866         for (Map.Entry<String, InterfaceDefinition> interfaceEntry : interfaces.entrySet()) {
867             for (OperationDataDefinition operation : interfaceEntry.getValue().getOperations().values()) {
868                 try {
869                     if (checkComponentBeforeWrite(component, interfaceEntry, operation)) {
870                         continue;
871                     }
872                     final String artifactUUID = operation.getImplementation().getArtifactUUID();
873                     if (artifactUUID == null) {
874                         continue;
875                     }
876                     final Either<byte[], ActionStatus> artifactFromCassandra = getFromCassandra(artifactUUID);
877                     final String artifactName = operation.getImplementation().getArtifactName();
878                     if (artifactFromCassandra.isRight()) {
879                         log.error(ARTIFACT_NAME_UNIQUE_ID, artifactName, artifactUUID);
880                         log.error("Failed to get {} payload from DB reason: {}", artifactName, artifactFromCassandra.right().value());
881                         return Either.right(componentsUtils
882                             .getResponseFormat(ActionStatus.ARTIFACT_PAYLOAD_NOT_FOUND_DURING_CSAR_CREATION, "Resource", component.getUniqueId(),
883                                 artifactName, artifactUUID));
884                     }
885                     final byte[] payloadData = artifactFromCassandra.left().value();
886                     zipstream.putNextEntry(new ZipEntry(OperationArtifactUtil.createOperationArtifactPath(component, null, operation, true)));
887                     zipstream.write(payloadData);
888                 } catch (IOException e) {
889                     log.error("Component Name {},  Interface Name {}, Operation Name {}", component.getNormalizedName(), interfaceEntry.getKey(),
890                         operation.getName());
891                     log.error("Error while writing the operation's artifacts to the CSAR " + "{}", e);
892                     return Either
893                         .right(componentsUtils.getResponseFormat(ActionStatus.ERROR_DURING_CSAR_CREATION, "Resource", component.getUniqueId()));
894                 }
895             }
896         }
897         return Either.left(zipstream);
898     }
899
900     private boolean checkComponentBeforeWrite(Component component, Entry<String, InterfaceDefinition> interfaceEntry,
901                                               OperationDataDefinition operation) {
902         final ArtifactDataDefinition implementation = operation.getImplementation();
903         if (Objects.isNull(implementation)) {
904             log.debug("Component Name {}, Interface Id {}, Operation Name {} - no Operation Implementation found", component.getNormalizedName(),
905                 interfaceEntry.getValue().getUniqueId(), operation.getName());
906             return true;
907         }
908         final String artifactName = implementation.getArtifactName();
909         if (Objects.isNull(artifactName)) {
910             log.debug("Component Name {}, Interface Id {}, Operation Name {} - no artifact found", component.getNormalizedName(),
911                 interfaceEntry.getValue().getUniqueId(), operation.getName());
912             return true;
913         }
914         if (OperationArtifactUtil.artifactNameIsALiteralValue(artifactName)) {
915             log.debug("Component Name {}, Interface Id {}, Operation Name {} - artifact name is a literal value rather than an SDC artifact",
916                 component.getNormalizedName(), interfaceEntry.getValue().getUniqueId(), operation.getName());
917             return true;
918         }
919         return false;
920     }
921
922     private boolean checkComponentBeforeOperation(Component component) {
923         if (component instanceof Service) {
924             return true;
925         }
926         if (Objects.isNull(((Resource) component).getInterfaces())) {
927             log.debug("Component Name {}- no interfaces found", component.getNormalizedName());
928             return true;
929         }
930         return false;
931     }
932
933     private Either<ZipOutputStream, ResponseFormat> writeComponentArtifactsToSpecifiedPath(Component mainComponent,
934                                                                                            ComponentArtifacts componentArtifacts,
935                                                                                            ZipOutputStream zipstream, String currentPath,
936                                                                                            boolean isInCertificationRequest) throws IOException {
937         Map<String, ComponentTypeArtifacts> componentTypeArtifacts = componentArtifacts.getComponentTypeArtifacts();
938         //Keys are defined:
939
940         //<Inner Asset TOSCA name (e.g. VFC name)> folder name: <Inner Asset TOSCA name (e.g. VFC name)>_v<version>.
941
942         //E.g. "org.openecomp.resource.vf.vipr_atm_v1.0"
943         Set<String> componentTypeArtifactsKeys = componentTypeArtifacts.keySet();
944         for (String keyAssetName : componentTypeArtifactsKeys) {
945             ComponentTypeArtifacts componentInstanceArtifacts = componentTypeArtifacts.get(keyAssetName);
946             ArtifactsInfo componentArtifacts2 = componentInstanceArtifacts.getComponentArtifacts();
947             String pathWithAssetName = currentPath + keyAssetName + PATH_DELIMITER;
948             Either<ZipOutputStream, ResponseFormat> writeArtifactsInfoToSpecifiedPath = writeArtifactsInfoToSpecifiedPath(mainComponent,
949                 componentArtifacts2, zipstream, pathWithAssetName, isInCertificationRequest);
950             if (writeArtifactsInfoToSpecifiedPath.isRight()) {
951                 return writeArtifactsInfoToSpecifiedPath;
952             }
953         }
954         return Either.left(zipstream);
955     }
956
957     private Either<ZipOutputStream, ResponseFormat> writeArtifactsInfoToSpecifiedPath(final Component mainComponent,
958                                                                                       final ArtifactsInfo currArtifactsInfo,
959                                                                                       final ZipOutputStream zip, final String path,
960                                                                                       final boolean isInCertificationRequest) throws IOException {
961         final Map<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> artifactsInfo = currArtifactsInfo.getArtifactsInfo();
962         for (final ArtifactGroupTypeEnum artifactGroupTypeEnum : artifactsInfo.keySet()) {
963             final String groupTypeFolder = path + WordUtils.capitalizeFully(artifactGroupTypeEnum.getType()) + PATH_DELIMITER;
964             final Map<String, List<ArtifactDefinition>> artifactTypesMap = artifactsInfo.get(artifactGroupTypeEnum);
965             for (final String artifactType : artifactTypesMap.keySet()) {
966                 final List<ArtifactDefinition> artifactDefinitionList = artifactTypesMap.get(artifactType);
967                 String artifactTypeFolder = groupTypeFolder + artifactType + PATH_DELIMITER;
968                 if (ArtifactTypeEnum.WORKFLOW.getType().equals(artifactType) && path.contains(ARTIFACTS_PATH + RESOURCES_PATH)) {
969                     // Ignore this packaging as BPMN artifacts needs to be packaged in different manner
970                     continue;
971                 }
972                 if (ArtifactTypeEnum.WORKFLOW.getType().equals(artifactType)) {
973                     artifactTypeFolder += OperationArtifactUtil.BPMN_ARTIFACT_PATH + File.separator;
974                 } else if (ArtifactTypeEnum.ONBOARDED_PACKAGE.getType().equals(artifactType)) {
975                     // renaming legacy folder ONBOARDED_PACKAGE to the new folder ETSI_PACKAGE
976                     artifactTypeFolder = artifactTypeFolder
977                         .replace(ArtifactTypeEnum.ONBOARDED_PACKAGE.getType(), ArtifactTypeEnum.ETSI_PACKAGE.getType());
978                 }
979                 // TODO: We should not do this but in order to keep this refactoring small enough,
980
981                 // we'll leave this as is for now
982                 List<ArtifactDefinition> collect = filterArtifactDefinitionToZip(mainComponent, artifactDefinitionList, isInCertificationRequest)
983                     .collect(Collectors.toList());
984                 for (ArtifactDefinition ad : collect) {
985                     zip.putNextEntry(new ZipEntry(artifactTypeFolder + ad.getArtifactName()));
986                     zip.write(ad.getPayloadData());
987                 }
988             }
989         }
990         return Either.left(zip);
991     }
992
993     private Stream<ArtifactDefinition> filterArtifactDefinitionToZip(Component mainComponent, List<ArtifactDefinition> artifactDefinitionList,
994                                                                      boolean isInCertificationRequest) {
995         return artifactDefinitionList.stream().filter(shouldBeInZip(isInCertificationRequest, mainComponent)).map(this::fetchPayLoadData)
996             .filter(Either::isLeft).map(e -> e.left().value());
997     }
998
999     private Predicate<ArtifactDefinition> shouldBeInZip(boolean isInCertificationRequest, Component component) {
1000         return artifactDefinition -> !(!isInCertificationRequest && component.isService() && artifactDefinition.isHeatEnvType() || artifactDefinition
1001             .hasNoMandatoryEsId());
1002     }
1003
1004     private Either<ArtifactDefinition, ActionStatus> fetchPayLoadData(ArtifactDefinition ad) {
1005         byte[] payloadData = ad.getPayloadData();
1006         if (payloadData == null) {
1007             return getFromCassandra(ad.getEsId()).left().map(pd -> {
1008                 ad.setPayload(pd);
1009                 return ad;
1010             }).right().map(as -> {
1011                 log.debug(ARTIFACT_NAME_UNIQUE_ID, ad.getArtifactName(), ad.getUniqueId());
1012                 log.debug("Failed to get {} payload from DB reason: {}", ad.getArtifactName(), as);
1013                 return as;
1014             });
1015         } else {
1016             return Either.left(ad);
1017         }
1018     }
1019
1020     /************************************ Artifacts Structure END******************************************************************/
1021
1022     private Either<CsarDefinition, ResponseFormat> collectComponentCsarDefinition(Component component) {
1023         ComponentArtifacts componentArtifacts = new ComponentArtifacts();
1024         Component updatedComponent = component;
1025
1026         //get service to receive the AII artifacts uploaded to the service
1027         if (updatedComponent.getComponentType() == ComponentTypeEnum.SERVICE) {
1028             Either<Service, StorageOperationStatus> getServiceResponse = toscaOperationFacade.getToscaElement(updatedComponent.getUniqueId());
1029
1030             if (getServiceResponse.isRight()) {
1031                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getServiceResponse.right().value());
1032                 return Either.right(componentsUtils.getResponseFormat(actionStatus));
1033             }
1034
1035             updatedComponent = getServiceResponse.left().value();
1036         }
1037
1038         //find the artifacts of the main component, it would have its composed instances artifacts in a separate folder
1039         ComponentTypeArtifacts componentInstanceArtifacts = new ComponentTypeArtifacts();
1040         ArtifactsInfo artifactsInfo = collectComponentArtifacts(updatedComponent);
1041         componentInstanceArtifacts.setComponentArtifacts(artifactsInfo);
1042         componentArtifacts.setMainTypeAndCIArtifacts(componentInstanceArtifacts);
1043
1044         Map<String, ComponentTypeArtifacts> resourceTypeArtifacts = componentArtifacts
1045             .getComponentTypeArtifacts();    //artifacts mapped by the component type(tosca name+version)
1046         //get the component instances
1047         List<ComponentInstance> componentInstances = updatedComponent.getComponentInstances();
1048         if (componentInstances != null) {
1049             for (ComponentInstance componentInstance : componentInstances) {
1050                 //call recursive to find artifacts for all the path
1051                 Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts = collectComponentInstanceArtifacts(
1052                     updatedComponent, componentInstance, resourceTypeArtifacts, componentInstanceArtifacts);
1053                 if (collectComponentInstanceArtifacts.isRight()) {
1054                     return Either.right(collectComponentInstanceArtifacts.right().value());
1055                 }
1056             }
1057         }
1058
1059         if (log.isDebugEnabled()) {
1060             printResult(componentArtifacts, updatedComponent.getName());
1061         }
1062
1063         return Either.left(new CsarDefinition(componentArtifacts));
1064     }
1065
1066     private void printResult(ComponentArtifacts componentArtifacts, String name) {
1067         StringBuilder result = new StringBuilder();
1068         result.append("Artifacts of main component " + name + "\n");
1069         ComponentTypeArtifacts componentInstanceArtifacts = componentArtifacts.getMainTypeAndCIArtifacts();
1070         printArtifacts(componentInstanceArtifacts);
1071         result.append("Type Artifacts\n");
1072         for (Map.Entry<String, ComponentTypeArtifacts> typeArtifacts : componentArtifacts.getComponentTypeArtifacts().entrySet()) {
1073             result.append("Folder " + typeArtifacts.getKey() + "\n");
1074             result.append(printArtifacts(typeArtifacts.getValue()));
1075         }
1076
1077         if (log.isDebugEnabled()) {
1078             log.debug(result.toString());
1079         }
1080     }
1081
1082     /************************************ Artifacts Structure ******************************************************************/
1083
1084     private String printArtifacts(ComponentTypeArtifacts componentInstanceArtifacts) {
1085         StringBuilder result = new StringBuilder();
1086         ArtifactsInfo artifactsInfo = componentInstanceArtifacts.getComponentArtifacts();
1087         Map<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> componentArtifacts = artifactsInfo.getArtifactsInfo();
1088         printArtifacts(componentArtifacts);
1089         result = result.append("Resources\n");
1090         for (Map.Entry<String, ArtifactsInfo> resourceInstance : componentInstanceArtifacts.getComponentInstancesArtifacts().entrySet()) {
1091             result.append("Folder" + resourceInstance.getKey() + "\n");
1092             result.append(printArtifacts(resourceInstance.getValue().getArtifactsInfo()));
1093         }
1094
1095         return result.toString();
1096     }
1097
1098     private String printArtifacts(Map<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> componetArtifacts) {
1099         StringBuilder result = new StringBuilder();
1100         for (Map.Entry<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> artifactGroup : componetArtifacts.entrySet()) {
1101             result.append("    " + artifactGroup.getKey().getType());
1102             for (Map.Entry<String, List<ArtifactDefinition>> groupArtifacts : artifactGroup.getValue().entrySet()) {
1103                 result.append("        " + groupArtifacts.getKey());
1104                 for (ArtifactDefinition artifact : groupArtifacts.getValue()) {
1105                     result.append("            " + artifact.getArtifactDisplayName());
1106                 }
1107             }
1108         }
1109
1110         return result.toString();
1111     }
1112
1113     private ComponentTypeArtifacts collectComponentTypeArtifacts(
1114         Component fetchedComponent
1115     ) {
1116         ArtifactsInfo componentArtifacts = collectComponentArtifacts(fetchedComponent);
1117         ComponentTypeArtifacts componentArtifactsInfo = new ComponentTypeArtifacts();
1118         if (componentArtifacts.isNotEmpty()) {
1119             componentArtifactsInfo.setComponentArtifacts(componentArtifacts);
1120         }
1121         return componentArtifactsInfo;
1122     }
1123
1124     private Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts(Component parentComponent, ComponentInstance componentInstance,
1125                                                                               Map<String, ComponentTypeArtifacts> resourcesTypeArtifacts,
1126                                                                               ComponentTypeArtifacts instanceArtifactsLocation) {
1127         //1. get the component instance component
1128         String componentUid;
1129         if (componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy) {
1130             componentUid = componentInstance.getSourceModelUid();
1131         } else {
1132             componentUid = componentInstance.getComponentUid();
1133         }
1134         Either<Component, StorageOperationStatus> component = toscaOperationFacade.getToscaElement(componentUid);
1135         if (component.isRight()) {
1136             log.error("Failed to fetch resource with id {} for instance {}", componentUid, parentComponent.getUUID());
1137             return Either.right(componentsUtils.getResponseFormat(ActionStatus.ASSET_NOT_FOUND_DURING_CSAR_CREATION,
1138                 parentComponent.getComponentType().getValue(), parentComponent.getUUID(),
1139                 componentInstance.getOriginType().getComponentType().getValue(), componentUid));
1140         }
1141         Component fetchedComponent = component.left().value();
1142
1143         //2. fill the artifacts for the current component parent type
1144         String toscaComponentName =
1145             componentInstance.getToscaComponentName() + "_v" + componentInstance.getComponentVersion();
1146
1147         // if there are no artifacts for this component type we need to fetch and build them
1148         ComponentTypeArtifacts componentParentArtifacts = Optional
1149             .ofNullable(resourcesTypeArtifacts.get(toscaComponentName))
1150             .orElseGet(() -> collectComponentTypeArtifacts(fetchedComponent));
1151
1152         if (componentParentArtifacts.getComponentArtifacts().isNotEmpty()) {
1153             resourcesTypeArtifacts.put(toscaComponentName, componentParentArtifacts);
1154         }
1155
1156         //3. find the artifacts specific to the instance
1157         Map<String, List<ArtifactDefinition>> componentInstanceSpecificInformationalArtifacts =
1158             getComponentInstanceSpecificArtifacts(componentInstance.getArtifacts(),
1159                 componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), ArtifactGroupTypeEnum.INFORMATIONAL);
1160         Map<String, List<ArtifactDefinition>> componentInstanceSpecificDeploymentArtifacts =
1161             getComponentInstanceSpecificArtifacts(componentInstance.getDeploymentArtifacts(),
1162                 componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), ArtifactGroupTypeEnum.DEPLOYMENT);
1163
1164         //4. add the instances artifacts to the component type
1165         ArtifactsInfo artifactsInfo = new ArtifactsInfo();
1166         if (!componentInstanceSpecificInformationalArtifacts.isEmpty()) {
1167             artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.INFORMATIONAL, componentInstanceSpecificInformationalArtifacts);
1168         }
1169         if (!componentInstanceSpecificDeploymentArtifacts.isEmpty()) {
1170             artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, componentInstanceSpecificDeploymentArtifacts);
1171         }
1172         if (!artifactsInfo.isEmpty()) {
1173             instanceArtifactsLocation.addComponentInstancesArtifacts(componentInstance.getNormalizedName(), artifactsInfo);
1174         }
1175
1176         //5. do the same for all the component instances
1177         List<ComponentInstance> componentInstances = fetchedComponent.getComponentInstances();
1178         if (componentInstances != null) {
1179             for (ComponentInstance childComponentInstance : componentInstances) {
1180                 Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts = collectComponentInstanceArtifacts(
1181                     fetchedComponent, childComponentInstance, resourcesTypeArtifacts, componentParentArtifacts);
1182                 if (collectComponentInstanceArtifacts.isRight()) {
1183                     return collectComponentInstanceArtifacts;
1184                 }
1185             }
1186         }
1187
1188         return Either.left(true);
1189     }
1190
1191     public String getVersionFirstThreeOctets() {
1192         return versionFirstThreeOctets;
1193     }
1194
1195     public void setVersionFirstThreeOctets(String versionFirstThreeOctetes) {
1196         this.versionFirstThreeOctets = versionFirstThreeOctetes;
1197     }
1198
1199     private Map<String, List<ArtifactDefinition>> getComponentInstanceSpecificArtifacts(Map<String, ArtifactDefinition> componentArtifacts,
1200                                                                                         Map<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> componentTypeArtifacts,
1201                                                                                         ArtifactGroupTypeEnum artifactGroupTypeEnum) {
1202         Map<String, List<ArtifactDefinition>> parentArtifacts = componentTypeArtifacts
1203             .get(artifactGroupTypeEnum);    //the artfiacts of the component itself and not the instance
1204
1205         Map<String, List<ArtifactDefinition>> artifactsByTypeOfComponentInstance = new HashMap<>();
1206         if (componentArtifacts != null) {
1207             for (ArtifactDefinition artifact : componentArtifacts.values()) {
1208                 List<ArtifactDefinition> parentArtifactsByType = null;
1209                 if (parentArtifacts != null) {
1210                     parentArtifactsByType = parentArtifacts.get(artifact.getArtifactType());
1211                 }
1212                 //the artifact is of instance
1213                 if (parentArtifactsByType == null || !parentArtifactsByType.contains(artifact)) {
1214                     List<ArtifactDefinition> typeArtifacts = artifactsByTypeOfComponentInstance.get(artifact.getArtifactType());
1215                     if (typeArtifacts == null) {
1216                         typeArtifacts = new ArrayList<>();
1217                         artifactsByTypeOfComponentInstance.put(artifact.getArtifactType(), typeArtifacts);
1218                     }
1219                     typeArtifacts.add(artifact);
1220                 }
1221             }
1222         }
1223
1224         return artifactsByTypeOfComponentInstance;
1225     }
1226
1227     private ArtifactsInfo collectComponentArtifacts(Component component) {
1228         Map<String, ArtifactDefinition> informationalArtifacts = component.getArtifacts();
1229         Map<String, List<ArtifactDefinition>> informationalArtifactsByType = collectGroupArtifacts(informationalArtifacts);
1230         Map<String, ArtifactDefinition> deploymentArtifacts = component.getDeploymentArtifacts();
1231         Map<String, List<ArtifactDefinition>> deploymentArtifactsByType = collectGroupArtifacts(deploymentArtifacts);
1232         Map<String, ArtifactDefinition> interfaceOperationArtifacts =
1233             OperationArtifactUtil.getDistinctInterfaceOperationArtifactsByName(component);
1234         Map<String, List<ArtifactDefinition>> interfaceOperationArtifactsByType = collectGroupArtifacts(
1235             interfaceOperationArtifacts);
1236         ArtifactsInfo artifactsInfo = new ArtifactsInfo();
1237         if (!informationalArtifactsByType.isEmpty()) {
1238             artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.INFORMATIONAL, informationalArtifactsByType);
1239         }
1240         if (!deploymentArtifactsByType.isEmpty()) {
1241             artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, deploymentArtifactsByType);
1242         }
1243
1244         return artifactsInfo;
1245     }
1246
1247     private Map<String, List<ArtifactDefinition>> collectGroupArtifacts(
1248         final Map<String, ArtifactDefinition> componentArtifacts) {
1249         final Map<String, List<ArtifactDefinition>> artifactsByType = new HashMap<>();
1250         for (final ArtifactDefinition artifact : componentArtifacts.values()) {
1251             if (artifact.getArtifactUUID() != null) {
1252                 artifactsByType.putIfAbsent(artifact.getArtifactType(), new ArrayList<>());
1253                 final List<ArtifactDefinition> typeArtifacts = artifactsByType.get(artifact.getArtifactType());
1254                 typeArtifacts.add(artifact);
1255             }
1256         }
1257         return artifactsByType;
1258     }
1259
1260     public static class ToscaErrorException extends Exception {
1261
1262         ToscaErrorException(ToscaError error) {
1263             super("Error while exporting component's interface (toscaError:" + error + ")");
1264         }
1265     }
1266
1267     @Getter
1268     public static final class NonMetaArtifactInfo {
1269
1270         private final String path;
1271         private final String artifactName;
1272         private final String displayName;
1273         private final String artifactLabel;
1274         private final String artifactType;
1275         private final ArtifactGroupTypeEnum artifactGroupType;
1276         private final String payloadData;
1277         private final String artifactChecksum;
1278         private final boolean isFromCsar;
1279         @Setter
1280         private String artifactUniqueId;
1281
1282         public NonMetaArtifactInfo(final String artifactName, final String path, final String artifactType,
1283                                    final ArtifactGroupTypeEnum artifactGroupType, final byte[] payloadData, final String artifactUniqueId,
1284                                    final boolean isFromCsar) {
1285             super();
1286             this.path = path;
1287             this.isFromCsar = isFromCsar;
1288             this.artifactName = ValidationUtils.normalizeFileName(artifactName);
1289             this.artifactType = artifactType;
1290             this.artifactGroupType = artifactGroupType;
1291             final int pointIndex = artifactName.lastIndexOf('.');
1292             if (pointIndex > 0) {
1293                 displayName = artifactName.substring(0, pointIndex);
1294             } else {
1295                 displayName = artifactName;
1296             }
1297             this.artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactName);
1298             if (payloadData == null) {
1299                 this.payloadData = null;
1300                 this.artifactChecksum = null;
1301             } else {
1302                 this.payloadData = Base64.encodeBase64String(payloadData);
1303                 this.artifactChecksum = GeneralUtility.calculateMD5Base64EncodedByByteArray(payloadData);
1304             }
1305             this.artifactUniqueId = artifactUniqueId;
1306         }
1307     }
1308
1309     /**
1310      * The artifacts Definition saved by their structure
1311      */
1312     private class ArtifactsInfo {
1313         //Key is the type of artifacts(Informational/Deployment)
1314
1315         //Value is a map between an artifact type and a list of all artifacts of this type
1316         private Map<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> artifactsInfoField;
1317
1318         public ArtifactsInfo() {
1319             this.artifactsInfoField = new EnumMap<>(ArtifactGroupTypeEnum.class);
1320         }
1321
1322         public Map<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> getArtifactsInfo() {
1323             return artifactsInfoField;
1324         }
1325
1326         public void addArtifactsToGroup(ArtifactGroupTypeEnum artifactGroup, Map<String, List<ArtifactDefinition>> artifactsDefinition) {
1327             if (artifactsInfoField.get(artifactGroup) == null) {
1328                 artifactsInfoField.put(artifactGroup, artifactsDefinition);
1329             } else {
1330                 Map<String, List<ArtifactDefinition>> artifactTypeEnumListMap = artifactsInfoField.get(artifactGroup);
1331                 artifactTypeEnumListMap.putAll(artifactsDefinition);
1332                 artifactsInfoField.put(artifactGroup, artifactTypeEnumListMap);
1333             }
1334         }
1335
1336         public boolean isEmpty() {
1337             return artifactsInfoField.isEmpty();
1338         }
1339
1340         public boolean isNotEmpty() {
1341             return !isEmpty();
1342         }
1343     }
1344
1345     /**
1346      * The artifacts of the component and of all its composed instances
1347      */
1348     private class ComponentTypeArtifacts {
1349
1350         private ArtifactsInfo componentArtifacts;    //component artifacts (describes the Informational Deployment folders)
1351
1352         private Map<String, ArtifactsInfo> componentInstancesArtifacts;        //artifacts of the composed instances mapped by the resourceInstance normalized name (describes the Resources folder)
1353
1354         public ComponentTypeArtifacts() {
1355             componentArtifacts = new ArtifactsInfo();
1356             componentInstancesArtifacts = new HashMap<>();
1357         }
1358
1359         public ArtifactsInfo getComponentArtifacts() {
1360             return componentArtifacts;
1361         }
1362
1363         public void setComponentArtifacts(ArtifactsInfo artifactsInfo) {
1364             this.componentArtifacts = artifactsInfo;
1365         }
1366
1367         public Map<String, ArtifactsInfo> getComponentInstancesArtifacts() {
1368             return componentInstancesArtifacts;
1369         }
1370
1371         public void addComponentInstancesArtifacts(String normalizedName, ArtifactsInfo artifactsInfo) {
1372             componentInstancesArtifacts.put(normalizedName, artifactsInfo);
1373         }
1374     }
1375
1376     private class ComponentArtifacts {
1377
1378         //artifacts of the component and CI's artifacts contained in it's composition (represents Informational, Deployment & Resource folders of main component)
1379         private ComponentTypeArtifacts mainTypeAndCIArtifacts;
1380         //artifacts of all component types mapped by their tosca name
1381         private Map<String, ComponentTypeArtifacts> componentTypeArtifacts;
1382
1383         public ComponentArtifacts() {
1384             mainTypeAndCIArtifacts = new ComponentTypeArtifacts();
1385             componentTypeArtifacts = new HashMap<>();
1386         }
1387
1388         public ComponentTypeArtifacts getMainTypeAndCIArtifacts() {
1389             return mainTypeAndCIArtifacts;
1390         }
1391
1392         public void setMainTypeAndCIArtifacts(ComponentTypeArtifacts componentInstanceArtifacts) {
1393             this.mainTypeAndCIArtifacts = componentInstanceArtifacts;
1394         }
1395
1396         public Map<String, ComponentTypeArtifacts> getComponentTypeArtifacts() {
1397             return componentTypeArtifacts;
1398         }
1399     }
1400
1401     private class CsarDefinition {
1402
1403         private ComponentArtifacts componentArtifacts;
1404
1405         // add list of tosca artifacts and meta describes CSAR zip root
1406         public CsarDefinition(ComponentArtifacts componentArtifacts) {
1407             this.componentArtifacts = componentArtifacts;
1408         }
1409
1410         public ComponentArtifacts getComponentArtifacts() {
1411             return componentArtifacts;
1412         }
1413     }
1414 }
1415