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