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