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