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