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