Refactor CsarUtil::extractVfcArtifact
[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 ->
757                     extractVfcArtifact(e, collectedWarningMessages).ifPresent(ip ->
758                         addExtractedVfcArtifact(ip, artifacts)
759                     )
760                 );
761             // add counter suffix to artifact labels
762             handleWarningMessages(collectedWarningMessages);
763
764         }
765         return artifacts;
766     }
767
768     /**
769      * Print warnings to log
770      *
771      * @param collectedWarningMessages
772      */
773     public static void handleWarningMessages(Map<String, Set<List<String>>> collectedWarningMessages) {
774         collectedWarningMessages.entrySet().stream()
775                                 // for each vfc
776                                 .forEach(e -> e.getValue().stream()
777                                                // add each warning message to log
778                                                .forEach(args -> log.warn(e.getKey(), args.toArray())));
779
780     }
781
782     private static void addExtractedVfcArtifact(
783         ImmutablePair<String, ArtifactDefinition> extractedVfcArtifact,
784         Map<String, List<ArtifactDefinition>> artifacts
785     ) {
786         String vfcToscaNamespace = extractedVfcArtifact.getKey();
787
788         artifacts.computeIfAbsent(vfcToscaNamespace, k -> new ArrayList<>());
789         artifacts.get(vfcToscaNamespace).add(extractedVfcArtifact.getValue());
790     }
791
792     private static Optional<ImmutablePair<String, ArtifactDefinition>> extractVfcArtifact(
793         Entry<String, byte[]> entry,
794         Map<String, Set<List<String>>> collectedWarningMessages
795     ) {
796         String[] parsedCsarArtifactPath = entry.getKey().split(PATH_DELIMITER);
797         String groupType = parsedCsarArtifactPath[2].toUpperCase();
798
799         return detectArtifactGroupType(groupType, collectedWarningMessages)
800             .left()
801             .map(buildArtifactDefinitionFromCsarArtifactPath(entry, collectedWarningMessages, parsedCsarArtifactPath))
802             .either(
803                 ad -> Optional.of(new ImmutablePair<>(parsedCsarArtifactPath[1], ad)),
804                 b -> Optional.empty()
805             );
806     }
807
808     private static Either<ArtifactGroupTypeEnum, Boolean> detectArtifactGroupType(String groupType, Map<String, Set<List<String>>> collectedWarningMessages) {
809         Either<ArtifactGroupTypeEnum, Boolean> result;
810         try {
811             ArtifactGroupTypeEnum artifactGroupType = ArtifactGroupTypeEnum.findType(groupType.toUpperCase());
812             if (artifactGroupType == null || (artifactGroupType != ArtifactGroupTypeEnum.INFORMATIONAL && artifactGroupType != ArtifactGroupTypeEnum.DEPLOYMENT)) {
813                 String warningMessage = "Warning - unrecognized artifact group type {} was received.";
814                 List<String> messageArguments = new ArrayList<>();
815                 messageArguments.add(groupType);
816                 if (!collectedWarningMessages.containsKey(warningMessage)) {
817                     Set<List<String>> messageArgumentLists = new HashSet<>();
818                     messageArgumentLists.add(messageArguments);
819                     collectedWarningMessages.put(warningMessage, messageArgumentLists);
820                 } else {
821                     collectedWarningMessages.get(warningMessage).add(messageArguments);
822                 }
823
824                 result = Either.right(false);
825             } else {
826
827                 result = Either.left(artifactGroupType);
828             }
829         } catch (Exception e) {
830             log.debug("detectArtifactGroupType failed with exception", e);
831             result = Either.right(false);
832         }
833         return result;
834     }
835
836     private static F<ArtifactGroupTypeEnum, ArtifactDefinition> buildArtifactDefinitionFromCsarArtifactPath(
837         Entry<String, byte[]> entry,
838         Map<String, Set<List<String>>> collectedWarningMessages,
839         String[] parsedCsarArtifactPath
840     ) {
841         return artifactGroupType -> {
842             ArtifactDefinition artifact;
843             artifact = new ArtifactDefinition();
844             artifact.setArtifactGroupType(artifactGroupType);
845             artifact.setArtifactType(
846                 detectArtifactTypeVFC(artifactGroupType, parsedCsarArtifactPath[3], parsedCsarArtifactPath[1],
847                     collectedWarningMessages));
848             artifact.setArtifactName(
849                 ValidationUtils.normalizeFileName(parsedCsarArtifactPath[parsedCsarArtifactPath.length - 1]));
850             artifact.setPayloadData(Base64.encodeBase64String(entry.getValue()));
851             artifact.setArtifactDisplayName(artifact.getArtifactName().lastIndexOf('.') > 0 ? artifact.getArtifactName()
852                 .substring(0, artifact.getArtifactName().lastIndexOf('.')) : artifact.getArtifactName());
853             artifact.setArtifactLabel(ValidationUtils.normalizeArtifactLabel(artifact.getArtifactName()));
854             artifact.setDescription(ARTIFACT_CREATED_FROM_CSAR);
855             artifact.setIsFromCsar(true);
856             artifact.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(entry.getValue()));
857             return artifact;
858         };
859     }
860
861     @Getter
862     public static final class NonMetaArtifactInfo {
863         @Setter
864         private String artifactUniqueId;
865         private final String path;
866         private final String artifactName;
867         private final String displayName;
868         private final String artifactLabel;
869         private final String artifactType;
870         private final ArtifactGroupTypeEnum artifactGroupType;
871         private final String payloadData;
872         private final String artifactChecksum;
873         private final boolean isFromCsar;
874
875         public NonMetaArtifactInfo(final String artifactName, final String path, final String artifactType,
876                                    final ArtifactGroupTypeEnum artifactGroupType, final byte[] payloadData,
877                                    final String artifactUniqueId, final boolean isFromCsar) {
878             super();
879             this.path = path;
880             this.isFromCsar = isFromCsar;
881             this.artifactName = ValidationUtils.normalizeFileName(artifactName);
882             this.artifactType = artifactType;
883             this.artifactGroupType = artifactGroupType;
884             final int pointIndex = artifactName.lastIndexOf('.');
885             if (pointIndex > 0) {
886                 displayName = artifactName.substring(0, pointIndex);
887             } else {
888                 displayName = artifactName;
889             }
890             this.artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactName);
891             if (payloadData == null) {
892                 this.payloadData = null;
893                 this.artifactChecksum = null;
894             } else {
895                 this.payloadData = Base64.encodeBase64String(payloadData);
896                 this.artifactChecksum = GeneralUtility.calculateMD5Base64EncodedByByteArray(payloadData);
897             }
898             this.artifactUniqueId = artifactUniqueId;
899         }
900
901     }
902
903     /**
904      * This method checks the artifact GroupType & Artifact Type. <br>
905      * if there is any problem warning messages are added to collectedWarningMessages
906      *
907      * @param artifactPath
908      * @param collectedWarningMessages
909      * @return
910      */
911     public static Either<NonMetaArtifactInfo, Boolean> validateNonMetaArtifact(
912         String artifactPath,
913         byte[] payloadData,
914         Map<String, Set<List<String>>> collectedWarningMessages
915     ) {
916         try {
917             String[] parsedArtifactPath = artifactPath.split(PATH_DELIMITER);
918             String groupType = parsedArtifactPath[1];
919             String receivedTypeName = parsedArtifactPath[2];
920             String artifactFileNameType = parsedArtifactPath[3];
921
922             return detectArtifactGroupType(groupType, collectedWarningMessages)
923                 .left().bind(artifactGroupType -> {
924                     String artifactType =
925                         detectArtifactTypeVF(artifactGroupType, receivedTypeName, collectedWarningMessages);
926
927                     return Either.left(new NonMetaArtifactInfo(
928                         artifactFileNameType, artifactPath, artifactType,
929                         artifactGroupType, payloadData, null, true
930                     ));
931                 });
932         } catch (Exception e) {
933             log.debug("detectArtifactGroupType failed with exception", e);
934             return Either.right(false);
935         }
936     }
937
938     private static String detectArtifactTypeVFC(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, String parentVfName, Map<String, Set<List<String>>> collectedWarningMessages) {
939         String warningMessage = "Warning - artifact type {} that was provided for VFC {} is not recognized.";
940         return detectArtifactType(artifactGroupType, receivedTypeName, warningMessage, collectedWarningMessages, parentVfName);
941     }
942
943     private static String detectArtifactTypeVF(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, Map<String, Set<List<String>>> collectedWarningMessages) {
944         String warningMessage = "Warning - artifact type {} that was provided for VF is not recognized.";
945         return detectArtifactType(artifactGroupType, receivedTypeName, warningMessage, collectedWarningMessages);
946     }
947
948     private static String detectArtifactType(final ArtifactGroupTypeEnum artifactGroupType,
949                                              final String receivedTypeName, final String warningMessage,
950                                              final Map<String, Set<List<String>>> collectedWarningMessages,
951                                              final String... arguments) {
952         final ArtifactConfiguration artifactConfiguration =
953             ArtifactConfigManager.getInstance()
954                 .find(receivedTypeName, artifactGroupType, ComponentType.RESOURCE)
955                 .orElse(null);
956
957         if (artifactConfiguration == null) {
958             final List<String> messageArguments = new ArrayList<>();
959             messageArguments.add(receivedTypeName);
960             messageArguments.addAll(Arrays.asList(arguments));
961             if (!collectedWarningMessages.containsKey(warningMessage)) {
962                 final Set<List<String>> messageArgumentLists = new HashSet<>();
963                 messageArgumentLists.add(messageArguments);
964                 collectedWarningMessages.put(warningMessage, messageArgumentLists);
965             } else {
966                 collectedWarningMessages.get(warningMessage).add(messageArguments);
967             }
968         }
969
970         return artifactConfiguration == null ? ArtifactTypeEnum.OTHER.getType() : receivedTypeName;
971     }
972
973     private Either<ZipOutputStream, ResponseFormat> writeAllFilesToCsar(Component mainComponent, CsarDefinition csarDefinition, ZipOutputStream zipstream, boolean isInCertificationRequest) throws IOException{
974         ComponentArtifacts componentArtifacts = csarDefinition.getComponentArtifacts();
975
976         Either<ZipOutputStream, ResponseFormat> writeComponentArtifactsToSpecifiedPath = writeComponentArtifactsToSpecifiedPath(mainComponent, componentArtifacts, zipstream, ARTIFACTS_PATH, isInCertificationRequest);
977
978         if(writeComponentArtifactsToSpecifiedPath.isRight()){
979             return Either.right(writeComponentArtifactsToSpecifiedPath.right().value());
980         }
981
982         ComponentTypeArtifacts mainTypeAndCIArtifacts = componentArtifacts.getMainTypeAndCIArtifacts();
983         writeComponentArtifactsToSpecifiedPath = writeArtifactsInfoToSpecifiedPath(mainComponent, mainTypeAndCIArtifacts.getComponentArtifacts(), zipstream, ARTIFACTS_PATH, isInCertificationRequest);
984
985         if(writeComponentArtifactsToSpecifiedPath.isRight()){
986             return Either.right(writeComponentArtifactsToSpecifiedPath.right().value());
987         }
988
989         Map<String, ArtifactsInfo> componentInstancesArtifacts = mainTypeAndCIArtifacts.getComponentInstancesArtifacts();
990         Set<String> keySet = componentInstancesArtifacts.keySet();
991
992         String currentPath = ARTIFACTS_PATH + RESOURCES_PATH;
993         for (String keyAssetName : keySet) {
994             ArtifactsInfo artifactsInfo = componentInstancesArtifacts.get(keyAssetName);
995             String pathWithAssetName = currentPath + keyAssetName + PATH_DELIMITER;
996             writeComponentArtifactsToSpecifiedPath = writeArtifactsInfoToSpecifiedPath(mainComponent, artifactsInfo, zipstream, pathWithAssetName, isInCertificationRequest);
997
998             if(writeComponentArtifactsToSpecifiedPath.isRight()){
999                 return Either.right(writeComponentArtifactsToSpecifiedPath.right().value());
1000             }
1001         }
1002         writeComponentArtifactsToSpecifiedPath = writeOperationsArtifactsToCsar(mainComponent, zipstream);
1003
1004         if (writeComponentArtifactsToSpecifiedPath.isRight()) {
1005             return Either.right(writeComponentArtifactsToSpecifiedPath.right().value());
1006         }
1007         return Either.left(zipstream);
1008     }
1009
1010     private Either<ZipOutputStream, ResponseFormat> writeOperationsArtifactsToCsar(Component component,
1011             ZipOutputStream zipstream) {
1012         if (checkComponentBeforeOperation(component)) return Either.left(zipstream);
1013         final Map<String, InterfaceDefinition> interfaces = ((Resource) component).getInterfaces();
1014         for (Map.Entry<String, InterfaceDefinition> interfaceEntry : interfaces.entrySet()) {
1015             for (OperationDataDefinition operation : interfaceEntry.getValue().getOperations().values()) {
1016                 try {
1017                     if (checkComponentBeforeWrite(component, interfaceEntry, operation)) continue;
1018                     final String artifactUUID = operation.getImplementation().getArtifactUUID();
1019                     final Either<byte[], ActionStatus> artifactFromCassandra = getFromCassandra(artifactUUID);
1020                     final String artifactName = operation.getImplementation().getArtifactName();
1021                     if (artifactFromCassandra.isRight()) {
1022                         log.error(ARTIFACT_NAME_UNIQUE_ID, artifactName, artifactUUID);
1023                         log.error("Failed to get {} payload from DB reason: {}", artifactName,
1024                                 artifactFromCassandra.right().value());
1025                         return Either.right(componentsUtils.getResponseFormat(
1026                                 ActionStatus.ARTIFACT_PAYLOAD_NOT_FOUND_DURING_CSAR_CREATION, "Resource",
1027                                 component.getUniqueId(), artifactName, artifactUUID));
1028                     }
1029                     final byte[] payloadData = artifactFromCassandra.left().value();
1030                     zipstream.putNextEntry(new ZipEntry(OperationArtifactUtil.createOperationArtifactPath(
1031                             component, null, operation,true)));
1032                     zipstream.write(payloadData);
1033                 } catch (IOException e) {
1034                     log.error("Component Name {},  Interface Name {}, Operation Name {}", component.getNormalizedName(),
1035                             interfaceEntry.getKey(), operation.getName());
1036                     log.error("Error while writing the operation's artifacts to the CSAR " + "{}", e);
1037                     return Either.right(componentsUtils
1038                                                 .getResponseFormat(ActionStatus.ERROR_DURING_CSAR_CREATION, "Resource",
1039                                                         component.getUniqueId()));
1040                 }
1041             }
1042         }
1043         return Either.left(zipstream);
1044     }
1045
1046     private boolean checkComponentBeforeWrite(Component component, Entry<String, InterfaceDefinition> interfaceEntry, OperationDataDefinition operation) {
1047         if (Objects.isNull(operation.getImplementation())) {
1048             log.debug("Component Name {}, Interface Id {}, Operation Name {} - no Operation Implementation found",
1049                     component.getNormalizedName(), interfaceEntry.getValue().getUniqueId(),
1050                     operation.getName());
1051             return true;
1052         }
1053         if (Objects.isNull(operation.getImplementation().getArtifactName())) {
1054             log.debug("Component Name {}, Interface Id {}, Operation Name {} - no artifact found",
1055                     component.getNormalizedName(), interfaceEntry.getValue().getUniqueId(),
1056                     operation.getName());
1057             return true;
1058         }
1059         if (operation.getImplementation().getArtifactName().startsWith(Constants.ESCAPED_DOUBLE_QUOTE) && operation.getImplementation().getArtifactName().endsWith(Constants.ESCAPED_DOUBLE_QUOTE)) {
1060             log.debug("Component Name {}, Interface Id {}, Operation Name {} - artifact name is a literal value rather than an SDC artifact",
1061                     component.getNormalizedName(), interfaceEntry.getValue().getUniqueId(),
1062                     operation.getName());
1063             return true;
1064         }
1065         return false;
1066     }
1067
1068     private boolean checkComponentBeforeOperation(Component component) {
1069         if (component instanceof Service) {
1070             return true;
1071         }
1072         if (Objects.isNull(((Resource) component).getInterfaces())) {
1073             log.debug("Component Name {}- no interfaces found", component.getNormalizedName());
1074             return true;
1075         }
1076         return false;
1077     }
1078
1079     private Either<ZipOutputStream, ResponseFormat> writeComponentArtifactsToSpecifiedPath(Component mainComponent, ComponentArtifacts componentArtifacts, ZipOutputStream zipstream,
1080             String currentPath, boolean isInCertificationRequest) throws IOException {
1081         Map<String, ComponentTypeArtifacts> componentTypeArtifacts = componentArtifacts.getComponentTypeArtifacts();
1082         //Keys are defined:
1083         //<Inner Asset TOSCA name (e.g. VFC name)> folder name: <Inner Asset TOSCA name (e.g. VFC name)>_v<version>.
1084         //E.g. "org.openecomp.resource.vf.vipr_atm_v1.0"
1085         Set<String> componentTypeArtifactsKeys = componentTypeArtifacts.keySet();
1086         for (String keyAssetName : componentTypeArtifactsKeys) {
1087             ComponentTypeArtifacts componentInstanceArtifacts = componentTypeArtifacts.get(keyAssetName);
1088             ArtifactsInfo componentArtifacts2 = componentInstanceArtifacts.getComponentArtifacts();
1089             String pathWithAssetName = currentPath + keyAssetName + PATH_DELIMITER;
1090             Either<ZipOutputStream, ResponseFormat> writeArtifactsInfoToSpecifiedPath = writeArtifactsInfoToSpecifiedPath(mainComponent, componentArtifacts2, zipstream, pathWithAssetName, isInCertificationRequest);
1091
1092             if(writeArtifactsInfoToSpecifiedPath.isRight()){
1093                 return writeArtifactsInfoToSpecifiedPath;
1094             }
1095         }
1096
1097         return Either.left(zipstream);
1098     }
1099
1100     private Either<ZipOutputStream, ResponseFormat> writeArtifactsInfoToSpecifiedPath(final Component mainComponent,
1101                                                                                       final ArtifactsInfo currArtifactsInfo,
1102                                                                                       final ZipOutputStream zip,
1103                                                                                       final String path,
1104                                                                                       final boolean isInCertificationRequest) throws IOException {
1105         final Map<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> artifactsInfo =
1106             currArtifactsInfo.getArtifactsInfo();
1107         for (final ArtifactGroupTypeEnum artifactGroupTypeEnum : artifactsInfo.keySet()) {
1108             final String groupTypeFolder = path + WordUtils.capitalizeFully(artifactGroupTypeEnum.getType()) + PATH_DELIMITER;
1109
1110             final Map<String, List<ArtifactDefinition>> artifactTypesMap = artifactsInfo.get(artifactGroupTypeEnum);
1111
1112             for (final String artifactType : artifactTypesMap.keySet()) {
1113                 final List<ArtifactDefinition> artifactDefinitionList = artifactTypesMap.get(artifactType);
1114                                 String artifactTypeFolder = groupTypeFolder + artifactType + PATH_DELIMITER;
1115
1116                                 if(ArtifactTypeEnum.WORKFLOW.getType().equals(artifactType) && path.contains(ARTIFACTS_PATH + RESOURCES_PATH)){
1117                                         // Ignore this packaging as BPMN artifacts needs to be packaged in different manner
1118                                         continue;
1119                                 }
1120                                 if (ArtifactTypeEnum.WORKFLOW.getType().equals(artifactType)) {
1121                                         artifactTypeFolder += OperationArtifactUtil.BPMN_ARTIFACT_PATH + File.separator;
1122                                 }
1123
1124                 Either<ZipOutputStream, ResponseFormat> writeArtifactDefinition =
1125                     writeArtifactDefinition(mainComponent, zip, artifactDefinitionList, artifactTypeFolder, isInCertificationRequest);
1126
1127                 if (writeArtifactDefinition.isRight()) {
1128                     return writeArtifactDefinition;
1129                 }
1130             }
1131         }
1132
1133         return Either.left(zip);
1134     }
1135
1136     private Either<ZipOutputStream, ResponseFormat> writeArtifactDefinition(Component mainComponent, ZipOutputStream zip, List<ArtifactDefinition> artifactDefinitionList,
1137             String artifactPathAndFolder, boolean isInCertificationRequest) throws IOException {
1138
1139         ComponentTypeEnum componentType = mainComponent.getComponentType();
1140         String heatEnvType = ArtifactTypeEnum.HEAT_ENV.getType();
1141
1142         for (ArtifactDefinition artifactDefinition : artifactDefinitionList) {
1143             if (!isInCertificationRequest && componentType == ComponentTypeEnum.SERVICE
1144                         && artifactDefinition.getArtifactType().equals(heatEnvType) ||
1145                         //this is placeholder
1146                         (artifactDefinition.getEsId() == null && artifactDefinition.getMandatory())){
1147                 continue;
1148             }
1149
1150             byte[] payloadData = artifactDefinition.getPayloadData();
1151             String artifactFileName = artifactDefinition.getArtifactName();
1152
1153             if (payloadData == null) {
1154                 Either<byte[], ActionStatus> fromCassandra = getFromCassandra(artifactDefinition.getEsId());
1155
1156                 if (fromCassandra.isRight()) {
1157                     log.debug(ARTIFACT_NAME_UNIQUE_ID, artifactDefinition.getArtifactName(), artifactDefinition.getUniqueId());
1158                     log.debug("Failed to get {} payload from DB reason: {}", artifactFileName, fromCassandra.right().value());
1159                     continue;
1160                 }
1161                 payloadData = fromCassandra.left().value();
1162             }
1163             zip.putNextEntry(new ZipEntry(artifactPathAndFolder + artifactFileName));
1164             zip.write(payloadData);
1165         }
1166
1167         return Either.left(zip);
1168     }
1169
1170     /************************************ Artifacts Structure ******************************************************************/
1171     /**
1172      * The artifacts Definition saved by their structure
1173      */
1174     private class ArtifactsInfo {
1175         //Key is the type of artifacts(Informational/Deployment)
1176         //Value is a map between an artifact type and a list of all artifacts of this type
1177         private Map<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> artifactsInfoField;
1178
1179         public ArtifactsInfo() {
1180             this.artifactsInfoField = new EnumMap<>(ArtifactGroupTypeEnum.class);
1181         }
1182
1183         public Map<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> getArtifactsInfo() {
1184             return artifactsInfoField;
1185         }
1186
1187         public void addArtifactsToGroup(ArtifactGroupTypeEnum artifactGroup,
1188                                         Map<String, List<ArtifactDefinition>> artifactsDefinition) {
1189                         if (artifactsInfoField.get(artifactGroup) == null) {
1190                                 artifactsInfoField.put(artifactGroup, artifactsDefinition);
1191                         } else {
1192                                 Map<String, List<ArtifactDefinition>> artifactTypeEnumListMap =
1193                                                 artifactsInfoField.get(artifactGroup);
1194                                 artifactTypeEnumListMap.putAll(artifactsDefinition);
1195                                 artifactsInfoField.put(artifactGroup, artifactTypeEnumListMap);
1196                         }
1197
1198         }
1199
1200         public boolean isEmpty() {
1201             return artifactsInfoField.isEmpty();
1202         }
1203
1204         public boolean isNotEmpty() {
1205             return !isEmpty();
1206         }
1207
1208     }
1209
1210     /**
1211      * The artifacts of the component and of all its composed instances
1212      *
1213      */
1214     private class ComponentTypeArtifacts {
1215         private ArtifactsInfo componentArtifacts;    //component artifacts (describes the Informational Deployment folders)
1216         private Map<String, ArtifactsInfo> componentInstancesArtifacts;        //artifacts of the composed instances mapped by the resourceInstance normalized name (describes the Resources folder)
1217
1218         public ComponentTypeArtifacts() {
1219             componentArtifacts = new ArtifactsInfo();
1220             componentInstancesArtifacts = new HashMap<>();
1221         }
1222
1223         public ArtifactsInfo getComponentArtifacts() {
1224             return componentArtifacts;
1225         }
1226         public void setComponentArtifacts(ArtifactsInfo artifactsInfo) {
1227             this.componentArtifacts = artifactsInfo;
1228         }
1229         public Map<String, ArtifactsInfo> getComponentInstancesArtifacts() {
1230             return componentInstancesArtifacts;
1231         }
1232         public void setComponentInstancesArtifacts(Map<String, ArtifactsInfo> componentInstancesArtifacts) {
1233             this.componentInstancesArtifacts = componentInstancesArtifacts;
1234         }
1235
1236         public void addComponentInstancesArtifacts(String normalizedName, ArtifactsInfo artifactsInfo) {
1237             componentInstancesArtifacts.put(normalizedName, artifactsInfo);
1238         }
1239
1240     }
1241
1242     private class ComponentArtifacts {
1243         //artifacts of the component and CI's artifacts contained in it's composition (represents Informational, Deployment & Resource folders of main component)
1244         private ComponentTypeArtifacts mainTypeAndCIArtifacts;
1245         //artifacts of all component types mapped by their tosca name
1246         private Map<String, ComponentTypeArtifacts> componentTypeArtifacts;
1247
1248         public ComponentArtifacts(){
1249             mainTypeAndCIArtifacts = new ComponentTypeArtifacts();
1250             componentTypeArtifacts = new HashMap<>();
1251         }
1252
1253         public ComponentTypeArtifacts getMainTypeAndCIArtifacts() {
1254             return mainTypeAndCIArtifacts;
1255         }
1256
1257         public void setMainTypeAndCIArtifacts(ComponentTypeArtifacts componentInstanceArtifacts) {
1258             this.mainTypeAndCIArtifacts = componentInstanceArtifacts;
1259         }
1260
1261         public Map<String, ComponentTypeArtifacts> getComponentTypeArtifacts() {
1262             return componentTypeArtifacts;
1263         }
1264
1265         public void setComponentTypeArtifacts(Map<String, ComponentTypeArtifacts> componentTypeArtifacts) {
1266             this.componentTypeArtifacts = componentTypeArtifacts;
1267         }
1268     }
1269
1270     private class CsarDefinition {
1271         private ComponentArtifacts componentArtifacts;
1272
1273         // add list of tosca artifacts and meta describes CSAR zip root
1274
1275         public CsarDefinition(ComponentArtifacts componentArtifacts) {
1276             this.componentArtifacts = componentArtifacts;
1277         }
1278
1279         public ComponentArtifacts getComponentArtifacts() {
1280             return componentArtifacts;
1281         }
1282     }
1283
1284     /************************************ Artifacts Structure END******************************************************************/
1285
1286     private Either<CsarDefinition,ResponseFormat> collectComponentCsarDefinition(Component component){
1287         ComponentArtifacts componentArtifacts = new ComponentArtifacts();
1288         Component updatedComponent = component;
1289
1290         //get service to receive the AII artifacts uploaded to the service
1291         if (updatedComponent.getComponentType() == ComponentTypeEnum.SERVICE) {
1292             Either<Service, StorageOperationStatus> getServiceResponse = toscaOperationFacade.getToscaElement(updatedComponent.getUniqueId());
1293
1294             if(getServiceResponse.isRight()){
1295                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getServiceResponse.right().value());
1296                 return Either.right(componentsUtils.getResponseFormat(actionStatus));
1297             }
1298
1299             updatedComponent = getServiceResponse.left().value();
1300         }
1301
1302         //find the artifacts of the main component, it would have its composed instances artifacts in a separate folder
1303         ComponentTypeArtifacts componentInstanceArtifacts = new ComponentTypeArtifacts();
1304         ArtifactsInfo artifactsInfo = collectComponentArtifacts(updatedComponent);
1305         componentInstanceArtifacts.setComponentArtifacts(artifactsInfo);
1306         componentArtifacts.setMainTypeAndCIArtifacts(componentInstanceArtifacts);
1307
1308         Map<String,ComponentTypeArtifacts> resourceTypeArtifacts = componentArtifacts.getComponentTypeArtifacts();    //artifacts mapped by the component type(tosca name+version)
1309         //get the component instances
1310         List<ComponentInstance> componentInstances = updatedComponent.getComponentInstances();
1311         if (componentInstances!=null){
1312             for (ComponentInstance componentInstance:componentInstances){
1313                 //call recursive to find artifacts for all the path
1314                 Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts = collectComponentInstanceArtifacts(
1315                         updatedComponent, componentInstance, resourceTypeArtifacts, componentInstanceArtifacts);
1316                 if (collectComponentInstanceArtifacts.isRight()){
1317                     return Either.right(collectComponentInstanceArtifacts.right().value());
1318                 }
1319             }
1320         }
1321
1322         if(log.isDebugEnabled()){
1323             printResult(componentArtifacts,updatedComponent.getName());
1324         }
1325
1326         return Either.left(new CsarDefinition(componentArtifacts));
1327     }
1328
1329     private void printResult(ComponentArtifacts componentArtifacts, String name) {
1330         StringBuilder result = new StringBuilder();
1331         result.append("Artifacts of main component " + name + "\n");
1332         ComponentTypeArtifacts componentInstanceArtifacts = componentArtifacts.getMainTypeAndCIArtifacts();
1333         printArtifacts(componentInstanceArtifacts);
1334         result.append("Type Artifacts\n");
1335         for (Map.Entry<String, ComponentTypeArtifacts> typeArtifacts:componentArtifacts.getComponentTypeArtifacts().entrySet()){
1336             result.append("Folder " + typeArtifacts.getKey() + "\n");
1337             result.append(printArtifacts(typeArtifacts.getValue()));
1338         }
1339
1340         if(log.isDebugEnabled()){
1341             log.debug(result.toString());
1342         }
1343     }
1344
1345     private String printArtifacts(ComponentTypeArtifacts componentInstanceArtifacts) {
1346         StringBuilder result = new StringBuilder();
1347         ArtifactsInfo artifactsInfo = componentInstanceArtifacts.getComponentArtifacts();
1348         Map<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> componentArtifacts = artifactsInfo.getArtifactsInfo();
1349         printArtifacts(componentArtifacts);
1350         result = result.append("Resources\n");
1351         for (Map.Entry<String, ArtifactsInfo> resourceInstance:componentInstanceArtifacts.getComponentInstancesArtifacts().entrySet()){
1352             result.append("Folder" + resourceInstance.getKey() + "\n");
1353             result.append(printArtifacts(resourceInstance.getValue().getArtifactsInfo()));
1354         }
1355
1356         return result.toString();
1357     }
1358
1359     private String printArtifacts(Map<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> componetArtifacts) {
1360         StringBuilder result = new StringBuilder();
1361         for (Map.Entry<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> artifactGroup:componetArtifacts.entrySet()){
1362             result.append("    " + artifactGroup.getKey().getType());
1363             for (Map.Entry<String, List<ArtifactDefinition>> groupArtifacts:artifactGroup.getValue().entrySet()){
1364                 result.append("        " + groupArtifacts.getKey());
1365                 for (ArtifactDefinition artifact:groupArtifacts.getValue()){
1366                     result.append("            " + artifact.getArtifactDisplayName());
1367                 }
1368             }
1369         }
1370
1371         return result.toString();
1372     }
1373
1374     private ComponentTypeArtifacts collectComponentTypeArtifacts(
1375         Component fetchedComponent
1376     ) {
1377         ArtifactsInfo componentArtifacts = collectComponentArtifacts(fetchedComponent);
1378         ComponentTypeArtifacts componentArtifactsInfo = new ComponentTypeArtifacts();
1379         if (componentArtifacts.isNotEmpty()) {
1380             componentArtifactsInfo.setComponentArtifacts(componentArtifacts);
1381         }
1382         return componentArtifactsInfo;
1383     }
1384
1385     private Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts(Component parentComponent,ComponentInstance componentInstance,
1386             Map<String, ComponentTypeArtifacts> resourcesTypeArtifacts,ComponentTypeArtifacts instanceArtifactsLocation) {
1387         //1. get the component instance component
1388         String componentUid;
1389         if (componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy) {
1390                         componentUid = componentInstance.getSourceModelUid();
1391                 }
1392                 else {
1393                         componentUid = componentInstance.getComponentUid();
1394                 }
1395         Either<Component, StorageOperationStatus> component = toscaOperationFacade.getToscaElement(componentUid);
1396                 if (component.isRight()) {
1397             log.error("Failed to fetch resource with id {} for instance {}",componentUid, parentComponent.getUUID());
1398             return Either.right(componentsUtils.getResponseFormat(ActionStatus.ASSET_NOT_FOUND_DURING_CSAR_CREATION,
1399                     parentComponent.getComponentType().getValue(), parentComponent.getUUID(),
1400                     componentInstance.getOriginType().getComponentType().getValue(), componentUid));
1401         }
1402                 Component fetchedComponent = component.left().value();
1403
1404         //2. fill the artifacts for the current component parent type
1405         String toscaComponentName =
1406             componentInstance.getToscaComponentName() + "_v" + componentInstance.getComponentVersion();
1407
1408         // if there are no artifacts for this component type we need to fetch and build them
1409         ComponentTypeArtifacts componentParentArtifacts = Optional
1410             .ofNullable(resourcesTypeArtifacts.get(toscaComponentName))
1411             .orElseGet(() -> collectComponentTypeArtifacts(fetchedComponent));
1412
1413         if (componentParentArtifacts.getComponentArtifacts().isNotEmpty()) {
1414             resourcesTypeArtifacts.put(toscaComponentName, componentParentArtifacts);
1415         }
1416
1417         //3. find the artifacts specific to the instance
1418         Map<String, List<ArtifactDefinition>> componentInstanceSpecificInformationalArtifacts =
1419                 getComponentInstanceSpecificArtifacts(componentInstance.getArtifacts(),
1420                         componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), ArtifactGroupTypeEnum.INFORMATIONAL);
1421         Map<String, List<ArtifactDefinition>> componentInstanceSpecificDeploymentArtifacts =
1422                 getComponentInstanceSpecificArtifacts(componentInstance.getDeploymentArtifacts(),
1423                         componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), ArtifactGroupTypeEnum.DEPLOYMENT);
1424
1425         //4. add the instances artifacts to the component type
1426         ArtifactsInfo artifactsInfo = new ArtifactsInfo();
1427         if (!componentInstanceSpecificInformationalArtifacts.isEmpty()){
1428             artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.INFORMATIONAL, componentInstanceSpecificInformationalArtifacts);
1429         }
1430         if (!componentInstanceSpecificDeploymentArtifacts.isEmpty()){
1431             artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, componentInstanceSpecificDeploymentArtifacts);
1432         }
1433         if (!artifactsInfo.isEmpty()){
1434             instanceArtifactsLocation.addComponentInstancesArtifacts(componentInstance.getNormalizedName(), artifactsInfo);
1435         }
1436
1437         //5. do the same for all the component instances
1438         List<ComponentInstance> componentInstances = fetchedComponent.getComponentInstances();
1439         if (componentInstances!=null){
1440             for (ComponentInstance childComponentInstance:componentInstances){
1441                 Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts = collectComponentInstanceArtifacts(
1442                         fetchedComponent, childComponentInstance, resourcesTypeArtifacts, componentParentArtifacts);
1443                 if (collectComponentInstanceArtifacts.isRight()){
1444                     return collectComponentInstanceArtifacts;
1445                 }
1446             }
1447         }
1448
1449         return Either.left(true);
1450     }
1451
1452     public String getVersionFirstThreeOctets() {
1453         return versionFirstThreeOctets;
1454     }
1455
1456     public void setVersionFirstThreeOctets(String versionFirstThreeOctetes) {
1457         this.versionFirstThreeOctets = versionFirstThreeOctetes;
1458     }
1459     private Map<String, List<ArtifactDefinition>> getComponentInstanceSpecificArtifacts(Map<String, ArtifactDefinition> componentArtifacts,
1460             Map<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> componentTypeArtifacts, ArtifactGroupTypeEnum artifactGroupTypeEnum) {
1461         Map<String, List<ArtifactDefinition>> parentArtifacts = componentTypeArtifacts.get(artifactGroupTypeEnum);    //the artfiacts of the component itself and not the instance
1462
1463         Map<String, List<ArtifactDefinition>> artifactsByTypeOfComponentInstance = new HashMap<>();
1464         if (componentArtifacts!=null){
1465             for (ArtifactDefinition artifact:componentArtifacts.values()){
1466                 List<ArtifactDefinition> parentArtifactsByType = null;
1467                 if (parentArtifacts!=null){
1468                     parentArtifactsByType = parentArtifacts.get(artifact.getArtifactType());
1469                 }
1470                 //the artifact is of instance
1471                 if (parentArtifactsByType == null || !parentArtifactsByType.contains(artifact)){
1472                     List<ArtifactDefinition> typeArtifacts = artifactsByTypeOfComponentInstance.get(artifact.getArtifactType());
1473                     if (typeArtifacts == null){
1474                         typeArtifacts = new ArrayList<>();
1475                         artifactsByTypeOfComponentInstance.put(artifact.getArtifactType(), typeArtifacts);
1476                     }
1477                     typeArtifacts.add(artifact);
1478                 }
1479             }
1480         }
1481
1482         return artifactsByTypeOfComponentInstance;
1483     }
1484
1485     private ArtifactsInfo collectComponentArtifacts(Component component) {
1486         Map<String, ArtifactDefinition> informationalArtifacts = component.getArtifacts();
1487         Map<String, List<ArtifactDefinition>> informationalArtifactsByType = collectGroupArtifacts(informationalArtifacts);
1488         Map<String, ArtifactDefinition> deploymentArtifacts = component.getDeploymentArtifacts();
1489         Map<String, List<ArtifactDefinition>> deploymentArtifactsByType = collectGroupArtifacts(deploymentArtifacts);
1490                 Map<String, ArtifactDefinition> interfaceOperationArtifacts =
1491                                 OperationArtifactUtil.getDistinctInterfaceOperationArtifactsByName(component);
1492                 Map<String, List<ArtifactDefinition>> interfaceOperationArtifactsByType = collectGroupArtifacts(
1493                                 interfaceOperationArtifacts);
1494         ArtifactsInfo artifactsInfo = new ArtifactsInfo();
1495         if (!informationalArtifactsByType.isEmpty()){
1496             artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.INFORMATIONAL, informationalArtifactsByType);
1497         }
1498         if (!deploymentArtifactsByType.isEmpty() ){
1499             artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, deploymentArtifactsByType);
1500                 }
1501                 //Add component interface operation artifacts
1502                 if(MapUtils.isNotEmpty(interfaceOperationArtifacts)) {
1503                         artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, interfaceOperationArtifactsByType);
1504         }
1505
1506         return artifactsInfo;
1507     }
1508
1509     private Map<String, List<ArtifactDefinition>> collectGroupArtifacts(
1510             final Map<String, ArtifactDefinition> componentArtifacts) {
1511         final Map<String, List<ArtifactDefinition>> artifactsByType = new HashMap<>();
1512         for (final ArtifactDefinition artifact : componentArtifacts.values()) {
1513             if (artifact.getArtifactUUID() != null) {
1514                 artifactsByType.putIfAbsent(artifact.getArtifactType(), new ArrayList<>());
1515                 final List<ArtifactDefinition> typeArtifacts = artifactsByType.get(artifact.getArtifactType());
1516                 typeArtifacts.add(artifact);
1517             }
1518         }
1519         return artifactsByType;
1520     }
1521 }