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