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