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