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