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