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