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