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