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