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