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