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