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