fix a typo
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / components / csar / CsarArtifactsAndGroupsBusinessLogic.java
1 package org.openecomp.sdc.be.components.csar;
2
3 import com.google.gson.Gson;
4 import com.google.gson.JsonElement;
5 import com.google.gson.JsonObject;
6 import fj.data.Either;
7 import org.apache.commons.codec.binary.Base64;
8 import org.apache.commons.collections.CollectionUtils;
9 import org.apache.commons.lang3.tuple.ImmutablePair;
10 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
11 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum;
12 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationInfo;
13 import org.openecomp.sdc.be.components.impl.BaseBusinessLogic;
14 import org.openecomp.sdc.be.components.impl.CsarValidationUtils;
15 import org.openecomp.sdc.be.components.impl.ImportUtils;
16 import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
17 import org.openecomp.sdc.be.config.BeEcompErrorManager;
18 import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
19 import org.openecomp.sdc.be.config.Configuration.VfModuleProperty;
20 import org.openecomp.sdc.be.config.ConfigurationManager;
21 import org.openecomp.sdc.be.dao.api.ActionStatus;
22 import org.openecomp.sdc.be.datamodel.utils.ArtifactUtils;
23 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
24 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
25 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
26 import org.openecomp.sdc.be.impl.ComponentsUtils;
27 import org.openecomp.sdc.be.info.ArtifactTemplateInfo;
28 import org.openecomp.sdc.be.info.MergedArtifactInfo;
29 import org.openecomp.sdc.be.model.*;
30 import org.openecomp.sdc.be.model.heat.HeatParameterType;
31 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
32 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
33 import org.openecomp.sdc.be.servlets.RepresentationUtils;
34 import org.openecomp.sdc.be.tosca.CsarUtils;
35 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
36 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
37 import org.openecomp.sdc.common.api.Constants;
38 import org.openecomp.sdc.common.log.wrappers.Logger;
39 import org.openecomp.sdc.common.util.GeneralUtility;
40 import org.openecomp.sdc.exception.ResponseFormat;
41 import org.springframework.beans.factory.annotation.Autowired;
42
43 import java.util.*;
44 import java.util.Map.Entry;
45 import java.util.regex.Matcher;
46 import java.util.regex.Pattern;
47 import java.util.stream.Collectors;
48
49 import static org.openecomp.sdc.be.tosca.CsarUtils.ARTIFACTS_PATH;
50
51
52 @org.springframework.stereotype.Component("csarArtifactsAndGroupsBusinessLogic")
53 public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic {
54
55     private static final Logger log = Logger.getLogger(CsarArtifactsAndGroupsBusinessLogic.class.getName());
56     public static final String ARTIFACT_FILE_IS_NOT_IN_EXPECTED_FORMATR_FILE_NAME = "Artifact  file is not in expected formatr, fileName  {}";
57     public static final String ARTIFACT_FILE_IS_NOT_IN_EXPECTED_FORMAT_FILE_NAME = "Artifact  file is not in expected format, fileName  {}";
58     public static final String ARTIFACT_FILE_IS_NOT_IN_EXPECTED_FORMATR_FILE_NAME1 = "Artifact  file is not in expected formatr, fileName ";
59     public static final String ARTIFACT_FILE_IS_NOT_IN_EXPECTED_FORMAT_FILE_NAME1 = "Artifact  file is not in expected format, fileName ";
60     public static final String ARTIFACT_INTERNALS_ARE_INVALID = "Artifact internals are invalid";
61     public static final String ARTIFACT_WITH_NAME_AND_TYPE_ALREADY_EXIST_WITH_TYPE = "Artifact with name {} and type {} already exist with type  {}";
62     private final Gson gson = new Gson();
63     private static final Pattern pattern = Pattern.compile("\\..(.*?)\\..");
64     @Autowired
65     protected ArtifactsBusinessLogic artifactsBusinessLogic;
66
67     public Either<Resource, ResponseFormat> createResourceArtifactsFromCsar(CsarInfo csarInfo, Resource resource,
68             String artifactsMetaFile, String artifactsMetaFileName, List<ArtifactDefinition> createdArtifacts,
69             boolean shouldLock, boolean inTransaction) {
70
71         log.debug("parseResourceArtifactsInfoFromFile start");
72         return  parseResourceArtifactsInfoFromFile(resource, artifactsMetaFile, artifactsMetaFileName)
73                 .left()
74                 .bind( p-> createResourceArtifacts(csarInfo, resource, p, createdArtifacts,shouldLock, inTransaction))
75                 .right()
76                 .map(rf -> { componentsUtils.auditResource(rf, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE); return rf;})
77                 .left()
78                 .bind(this::getResourcetFromGraph);
79     }
80
81
82     public Either<Resource, ResponseFormat> updateResourceArtifactsFromCsar(CsarInfo csarInfo, Resource resource,
83             String artifactsMetaFile, String artifactsMetaFileName, List<ArtifactDefinition> createdNewArtifacts,
84             boolean shouldLock, boolean inTransaction){
85
86         Resource updatedResource = resource;
87
88         Either<Map<String, List<ArtifactTemplateInfo>>, ResponseFormat> parseResourceInfoFromYamlEither = parseResourceArtifactsInfoFromFile(
89                 updatedResource, artifactsMetaFile, artifactsMetaFileName);
90         if (parseResourceInfoFromYamlEither.isRight()) {
91             ResponseFormat responseFormat = parseResourceInfoFromYamlEither.right().value();
92             componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
93             return Either.right(responseFormat);
94         }
95
96         List<GroupDefinition> groups = updatedResource.getGroups();
97         Map<String, ArtifactDefinition> deplymentArtifact = updatedResource.getDeploymentArtifacts();
98         if (deplymentArtifact == null || deplymentArtifact.isEmpty()) {
99             if(groups != null){
100                 List<GroupDefinition> listToDelete =  groups.stream().filter(g -> g.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)).collect(Collectors.toList());
101                 groupBusinessLogic.deleteGroups(updatedResource, listToDelete);
102             }
103             return createResourceArtifacts(csarInfo, updatedResource, parseResourceInfoFromYamlEither.left().value(),
104                     createdNewArtifacts, shouldLock, inTransaction);
105         }
106
107         List<ArtifactDefinition> createdDeplymentArtifactsAfterDelete = deplymentArtifact.values().stream().collect(Collectors.toList());
108
109         int labelCounter = createdDeplymentArtifactsAfterDelete.size();
110
111
112         ////////////////////////////////////// create set parsed
113         ////////////////////////////////////// artifacts///////////////////////////////////////////
114         Map<String, List<ArtifactTemplateInfo>> parsedArtifactsMap = parseResourceInfoFromYamlEither.left().value();
115
116
117         List<ArtifactTemplateInfo> artifactsWithoutGroups = null;
118         if (parsedArtifactsMap.containsKey(ArtifactTemplateInfo.CSAR_ARTIFACT)) {
119             artifactsWithoutGroups = parsedArtifactsMap.get(ArtifactTemplateInfo.CSAR_ARTIFACT);
120             parsedArtifactsMap.remove(ArtifactTemplateInfo.CSAR_ARTIFACT);
121         }
122         Collection<List<ArtifactTemplateInfo>> parsedArifactsCollection = parsedArtifactsMap.values();
123
124         Either<Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>>, ResponseFormat> parsedArtifactsPerGroupEither = createArtifactsTemplateCollection(csarInfo, updatedResource, createdNewArtifacts, shouldLock, inTransaction,
125                 createdDeplymentArtifactsAfterDelete, labelCounter, parsedArifactsCollection);
126         if(parsedArtifactsPerGroupEither.isRight()){
127             log.error("Failed to parse artifacts. Status is {} ", parsedArtifactsPerGroupEither.right().value());
128             return Either.right(parsedArtifactsPerGroupEither.right().value());
129         }
130
131         Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup = parsedArtifactsPerGroupEither.left().value();
132
133         // find master in group
134         Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupArtifact = findMasterArtifactInGroup(
135                 groups, deplymentArtifact);
136
137         ///////////////////////////////// find artifacts to
138         ///////////////////////////////// delete////////////////////////////////////////////////////
139
140
141         Map<String, List<ArtifactDefinition>> groupToDelete = new HashMap<>();
142         Set<ArtifactDefinition> artifactsToDelete = findArtifactThatNotInGroupToDelete(parsedGroup, createdDeplymentArtifactsAfterDelete);
143
144         Set<ArtifactTemplateInfo> jsonMasterArtifacts = parsedGroup.keySet();
145         Map<GroupDefinition, MergedArtifactInfo> mergedgroup = mergeGroupInUpdateFlow(groupArtifact, parsedGroup,
146                 artifactsToDelete, groupToDelete, jsonMasterArtifacts, createdDeplymentArtifactsAfterDelete);
147
148         List<ArtifactDefinition> deletedArtifacts = new ArrayList<>();;
149         Either<Resource, ResponseFormat> deletedArtifactsEither = deleteArtifactsInUpdateCsarFlow(
150                 updatedResource, csarInfo.getModifier(), shouldLock, inTransaction, artifactsToDelete, groupToDelete, deletedArtifacts);
151         if (deletedArtifactsEither.isRight()) {
152             log.debug("Failed to delete artifacts. Status is {} ", deletedArtifactsEither.right().value());
153
154             return Either.right(deletedArtifactsEither.right().value());
155
156         }
157         updatedResource = deletedArtifactsEither.left().value();
158
159         // need to update resource if we updated artifacts
160         if (!deletedArtifacts.isEmpty()) {
161             for (ArtifactDefinition deletedArtifact : deletedArtifacts) {
162                 ArtifactDefinition artToRemove = null;
163                 for (ArtifactDefinition artFromResource : createdDeplymentArtifactsAfterDelete) {
164                     if (deletedArtifact.getUniqueId().equalsIgnoreCase(artFromResource.getUniqueId())) {
165                         artToRemove = artFromResource;
166                         break;
167                     }
168                 }
169                 if (artToRemove != null) {
170                     createdDeplymentArtifactsAfterDelete.remove(artToRemove);
171                 }
172
173             }
174         }
175
176         ////////////// dissociate, associate or create
177         ////////////// artifacts////////////////////////////
178         Either<Resource, ResponseFormat> assDissotiateEither = associateAndDissociateArtifactsToGroup(csarInfo,
179                 updatedResource, createdNewArtifacts, labelCounter, inTransaction,
180                 createdDeplymentArtifactsAfterDelete, mergedgroup, deletedArtifacts);
181         groups = updatedResource.getGroups();
182         if (assDissotiateEither.isRight()) {
183             log.debug("Failed to delete artifacts. Status is {} ", assDissotiateEither.right().value());
184
185             return Either.right(assDissotiateEither.right().value());
186
187         }
188         updatedResource = assDissotiateEither.left().value();
189         deplymentArtifact = updatedResource.getDeploymentArtifacts();
190         createdDeplymentArtifactsAfterDelete.clear();
191         if (deplymentArtifact != null && !deplymentArtifact.isEmpty()) {
192             for (Entry<String, ArtifactDefinition> entry : deplymentArtifact.entrySet()) {
193                 createdDeplymentArtifactsAfterDelete.add(entry.getValue());
194             }
195         }
196
197         // update vfModule names
198         Set<GroupDefinition> groupForAssociateWithMembers = mergedgroup.keySet();
199         if (groups != null && !groups.isEmpty()) {
200             Either<List<GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic
201                     .validateUpdateVfGroupNamesOnGraph(groups, updatedResource);
202             if (validateUpdateVfGroupNamesRes.isRight()) {
203                 return Either.right(validateUpdateVfGroupNamesRes.right().value());
204             }
205             List<GroupDefinition> heatGroups = null;
206
207             heatGroups = groups.stream().filter(e -> e.getMembers() != null).collect(Collectors.toList());
208
209             for (GroupDefinition updatedGroupDef : groupForAssociateWithMembers) {
210
211                 if (updatedGroupDef.getMembers() != null && !updatedGroupDef.getMembers().isEmpty()) {
212                     updatedGroupDef.getMembers().clear();
213                 }
214                 Map<String, String> members = new HashMap<>();
215                 Set<String> artifactsGroup = new HashSet<>();
216                 artifactsGroup.addAll(updatedGroupDef.getArtifacts());
217                 associateMembersToArtifacts(createdNewArtifacts, createdDeplymentArtifactsAfterDelete, heatGroups,
218                         artifactsGroup, members);
219                 if (!members.isEmpty()) {
220                     updatedGroupDef.setMembers(members);
221
222                 }
223
224             }
225
226         }
227
228         //////////////// create new artifacts in update
229         //////////////// flow////////////////////////////
230         List<ArtifactTemplateInfo> newArtifactsGroup = new ArrayList<>();
231
232         for (Entry<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroupSetEntry : parsedGroup.entrySet()) {
233             ArtifactTemplateInfo parsedArtifactMaster = parsedGroupSetEntry.getKey();
234             boolean isNewGroup = true;
235             for (Entry<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupListEntry : groupArtifact
236                     .entrySet()) {
237                 Map<ArtifactDefinition, List<ArtifactDefinition>> groupArtifacts = groupListEntry.getValue();
238                 Set<ArtifactDefinition> group = groupArtifacts.keySet();
239                 for (ArtifactDefinition artifactInfo : group) {
240                     if (parsedArtifactMaster.getFileName().equalsIgnoreCase(artifactInfo.getArtifactName())) {
241                         parsedArtifactMaster.setGroupName(groupListEntry.getKey().getName());
242                         isNewGroup = false;
243                     }
244                 }
245             }
246             if (isNewGroup) {
247                 newArtifactsGroup.add(parsedArtifactMaster);
248             }
249
250         }
251         if (!newArtifactsGroup.isEmpty()) {
252             Collections.sort(newArtifactsGroup, ArtifactTemplateInfo::compareByGroupName);
253             int startGroupCounter = groupBusinessLogic.getNextVfModuleNameCounter(groups);
254             Either<Boolean, ResponseFormat> validateGroupNamesRes = groupBusinessLogic
255                     .validateGenerateVfModuleGroupNames(newArtifactsGroup, updatedResource.getSystemName(), startGroupCounter);
256             if (validateGroupNamesRes.isRight()) {
257                 return Either.right(validateGroupNamesRes.right().value());
258             }
259             Either<Resource, ResponseFormat> resStatus = createGroupDeploymentArtifactsFromCsar(csarInfo, updatedResource,
260                     newArtifactsGroup, createdNewArtifacts, createdDeplymentArtifactsAfterDelete, labelCounter,
261                     shouldLock, inTransaction);
262             if (resStatus.isRight()) {
263                 return resStatus;
264             }
265         }
266
267         // updatedGroup
268         if (!groupForAssociateWithMembers.isEmpty()) {
269
270             List<GroupDefinition> groupsId = groupForAssociateWithMembers.stream().map(e -> e)
271                     .collect(Collectors.toList());
272
273             Either<List<GroupDefinition>, ResponseFormat> updateVersionEither = groupBusinessLogic
274                     .updateGroups(updatedResource, groupsId, true);
275             if (updateVersionEither.isRight()) {
276                 log.debug("Failed to update groups version. Status is {} ", updateVersionEither.right().value());
277
278                 return Either.right(updateVersionEither.right().value());
279
280             }
281         }
282         if (artifactsWithoutGroups != null && !artifactsWithoutGroups.isEmpty()) {
283             for (ArtifactTemplateInfo t : artifactsWithoutGroups) {
284                 List<ArtifactTemplateInfo> arrtifacts = new ArrayList<>();
285                 arrtifacts.add(t);
286                 Either<Resource, ResponseFormat> resStatus = createGroupDeploymentArtifactsFromCsar(csarInfo, updatedResource,
287                         arrtifacts, createdNewArtifacts, createdDeplymentArtifactsAfterDelete, labelCounter, shouldLock,
288                         inTransaction);
289                 if (resStatus.isRight()) {
290                     return resStatus;
291                 }
292             }
293
294         }
295
296         Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade
297                 .getToscaElement(updatedResource.getUniqueId());
298         if (eitherGerResource.isRight()) {
299             ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
300                     componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), updatedResource);
301
302             return Either.right(responseFormat);
303
304         }
305         return Either.left(eitherGerResource.left().value());
306     }
307
308     private Set<ArtifactDefinition> findArtifactThatNotInGroupToDelete(
309             Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup,
310             List<ArtifactDefinition> createdDeplymentArtifactsAfterDelete) {
311         Set<ArtifactDefinition> artifactsToDelete = new HashSet<>();
312         for (Entry<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroupSetEntry : parsedGroup.entrySet()) {
313             Set<ArtifactTemplateInfo> artifactsNames = parsedGroupSetEntry.getValue();
314             for (ArtifactTemplateInfo template : artifactsNames) {
315                 if(template.getType().equals(ArtifactTypeEnum.HEAT_ARTIFACT.getType())){
316                     Optional<ArtifactDefinition> op = createdDeplymentArtifactsAfterDelete.stream().filter(a -> a.getArtifactName().equalsIgnoreCase(template.getFileName())).findAny();
317                     if(op.isPresent()){
318                         if(!op.get().getArtifactType().equalsIgnoreCase(template.getType())){
319                             artifactsToDelete.add(op.get());
320                         }
321                             
322                     }
323                 } 
324             }
325         }
326                 
327         return artifactsToDelete;
328     }
329
330
331     private Either<Resource, ResponseFormat> createResourceArtifacts(CsarInfo csarInfo, Resource resource,
332             Map<String, List<ArtifactTemplateInfo>> artifactsMap,
333             List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction) {
334
335         Either<Resource, ResponseFormat> resStatus = Either.left(resource);
336
337         Collection<List<ArtifactTemplateInfo>> arifactsCollection = artifactsMap.values();
338
339         for (List<ArtifactTemplateInfo> groupTemplateList : arifactsCollection) {
340             if (groupTemplateList != null) {
341                 resStatus = createGroupDeploymentArtifactsFromCsar(csarInfo, resource, groupTemplateList,
342                         createdArtifacts, 0, shouldLock, inTransaction);
343                 if (resStatus.isRight()) {
344                     return resStatus;
345                 }
346             }
347         }
348
349         return resStatus;
350
351     }
352
353
354     private Either<Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>>, ResponseFormat> createArtifactsTemplateCollection(CsarInfo csarInfo, Resource resource,
355             List<ArtifactDefinition> createdNewArtifacts, boolean shouldLock, boolean inTransaction,
356             List<ArtifactDefinition> createdDeplymentArtifactsAfterDelete, int labelCounter,
357             Collection<List<ArtifactTemplateInfo>> parsedArifactsCollection) {
358
359         Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup = new HashMap<>();
360
361         for (List<ArtifactTemplateInfo> parsedGroupTemplateList : parsedArifactsCollection) {
362
363             for (ArtifactTemplateInfo parsedGroupTemplate : parsedGroupTemplateList) {
364                 if (parsedGroupTemplate.getGroupName() != null) {
365                     parsedGroupTemplate.setGroupName("");
366                     Set<ArtifactTemplateInfo> parsedArtifactsNames = new HashSet<>();
367                     parsedArtifactsNames.add(parsedGroupTemplate);
368                     List<ArtifactTemplateInfo> relatedGroupTemplateList = parsedGroupTemplate.getRelatedArtifactsInfo();
369                     if (relatedGroupTemplateList != null && !relatedGroupTemplateList.isEmpty()) {
370                         createArtifactsGroupSet(parsedGroupTemplateList, parsedArtifactsNames);
371                     }
372                     parsedGroup.put(parsedGroupTemplate, parsedArtifactsNames);
373                 } else {
374                     List<ArtifactTemplateInfo> arrtifacts = new ArrayList<>();
375                     arrtifacts.add(parsedGroupTemplate);
376                     Either<Resource, ResponseFormat> resStatus = createGroupDeploymentArtifactsFromCsar(csarInfo,
377                             resource, arrtifacts, createdNewArtifacts, createdDeplymentArtifactsAfterDelete,
378                             labelCounter, shouldLock, inTransaction);
379                     if (resStatus.isRight()) {
380                         return Either.right(resStatus.right().value());
381                     }
382
383                 }
384             }
385
386         }
387         return Either.left(parsedGroup);
388     }
389
390     @SuppressWarnings({ "unchecked", "static-access" })
391     public Either<Map<String, List<ArtifactTemplateInfo>>, ResponseFormat> parseResourceArtifactsInfoFromFile(
392             Resource resource, String artifactsMetaFile, String artifactFileName) {
393
394         try {
395             JsonObject jsonElement = new JsonObject();
396             jsonElement = gson.fromJson(artifactsMetaFile, jsonElement.getClass());
397
398             JsonElement importStructureElement = jsonElement.get(Constants.IMPORT_STRUCTURE);
399             if (importStructureElement == null || importStructureElement.isJsonNull()) {
400                 log.debug(ARTIFACT_FILE_IS_NOT_IN_EXPECTED_FORMATR_FILE_NAME, artifactFileName);
401                 BeEcompErrorManager.getInstance().logInternalDataError(
402                         ARTIFACT_FILE_IS_NOT_IN_EXPECTED_FORMATR_FILE_NAME1 + artifactFileName,
403                         ARTIFACT_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
404                 return Either
405                         .right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName));
406             }
407
408             Map<String, List<Map<String, Object>>> artifactTemplateMap = new HashMap<>();
409             artifactTemplateMap = ComponentsUtils.parseJsonToObject(importStructureElement.toString(), HashMap.class);
410             if (artifactTemplateMap.isEmpty()) {
411                 log.debug(ARTIFACT_FILE_IS_NOT_IN_EXPECTED_FORMATR_FILE_NAME, artifactFileName);
412                 BeEcompErrorManager.getInstance().logInternalDataError(
413                         ARTIFACT_FILE_IS_NOT_IN_EXPECTED_FORMATR_FILE_NAME1 + artifactFileName,
414                         ARTIFACT_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
415                 return Either
416                         .right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName));
417             }
418
419             Set<String> artifactsTypeKeys = artifactTemplateMap.keySet();
420             Map<String, List<ArtifactTemplateInfo>> artifactsMap = new HashMap<>();
421             List<ArtifactTemplateInfo> allGroups = new ArrayList<>();
422             for (String artifactsTypeKey : artifactsTypeKeys) {
423
424                 Either <List<ArtifactTemplateInfo>, ResponseFormat> artifactTemplateInfoListEither = parseArtifactTemplateList(artifactFileName,
425                         artifactTemplateMap, allGroups, artifactsTypeKey);
426                 if(artifactTemplateInfoListEither.isRight()){
427                     return Either.right(artifactTemplateInfoListEither.right().value());
428                 }
429                 artifactsMap.put(artifactsTypeKey, artifactTemplateInfoListEither.left().value());
430             }
431             int counter = groupBusinessLogic.getNextVfModuleNameCounter(resource.getGroups());
432             Either<Boolean, ResponseFormat> validateGroupNamesRes = groupBusinessLogic
433                     .validateGenerateVfModuleGroupNames(allGroups, resource.getSystemName(), counter);
434             if (validateGroupNamesRes.isRight()) {
435                 return Either.right(validateGroupNamesRes.right().value());
436             }
437             return Either.left(artifactsMap);
438         } catch (Exception e) {
439             log.debug(ARTIFACT_FILE_IS_NOT_IN_EXPECTED_FORMAT_FILE_NAME, artifactFileName);
440             log.debug("failed with exception.", e);
441             BeEcompErrorManager.getInstance().logInternalDataError(
442                     ARTIFACT_FILE_IS_NOT_IN_EXPECTED_FORMAT_FILE_NAME1 + artifactFileName,
443                     ARTIFACT_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
444             return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName));
445         }
446
447     }
448
449     private Either< List<ArtifactTemplateInfo>, ResponseFormat> parseArtifactTemplateList(String artifactFileName,
450             Map<String, List<Map<String, Object>>> artifactTemplateMap, List<ArtifactTemplateInfo> allGroups,
451             String artifactsTypeKey) {
452         List<Map<String, Object>> o = artifactTemplateMap.get(artifactsTypeKey);
453         Either<List<ArtifactTemplateInfo>, ResponseFormat> artifactTemplateInfoListPairStatus = createArtifactTemplateInfoModule(
454                 artifactsTypeKey, o);
455         if (artifactTemplateInfoListPairStatus.isRight()) {
456             log.debug(ARTIFACT_FILE_IS_NOT_IN_EXPECTED_FORMATR_FILE_NAME, artifactFileName);
457             BeEcompErrorManager.getInstance().logInternalDataError(
458                     ARTIFACT_FILE_IS_NOT_IN_EXPECTED_FORMAT_FILE_NAME1 + artifactFileName,
459                     ARTIFACT_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
460             return Either.right(artifactTemplateInfoListPairStatus.right().value());
461         }
462         List<ArtifactTemplateInfo> artifactTemplateInfoList = artifactTemplateInfoListPairStatus.left().value();
463         if (artifactTemplateInfoList == null) {
464             log.debug(ARTIFACT_FILE_IS_NOT_IN_EXPECTED_FORMATR_FILE_NAME, artifactFileName);
465             BeEcompErrorManager.getInstance().logInternalDataError(
466                     ARTIFACT_FILE_IS_NOT_IN_EXPECTED_FORMAT_FILE_NAME1 + artifactFileName,
467                     ARTIFACT_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
468             return Either.right(
469                     componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName));
470
471         }
472         if (!artifactsTypeKey.equalsIgnoreCase(ArtifactTemplateInfo.CSAR_ARTIFACT)) {
473             allGroups.addAll(artifactTemplateInfoList);
474         }
475         return Either.left(artifactTemplateInfoList);
476     }
477
478     private Either<List<ArtifactTemplateInfo>, ResponseFormat> createArtifactTemplateInfoModule(String artifactsTypeKey,
479             List<Map<String, Object>> jsonObject) {
480         List<ArtifactTemplateInfo> artifactTemplateInfoList = new ArrayList<>();
481         for (Map<String, Object> o : jsonObject) {
482             Either<ArtifactTemplateInfo, ResponseFormat> artifacttemplateInfoStatus = ArtifactTemplateInfo
483                     .createArtifactTemplateInfoFromJson(componentsUtils, artifactsTypeKey, o, artifactTemplateInfoList,
484                             null);
485             if (artifacttemplateInfoStatus.isRight()) {
486                 return Either.right(artifacttemplateInfoStatus.right().value());
487             }
488
489             ArtifactTemplateInfo artifacttemplateInfo = artifacttemplateInfoStatus.left().value();
490             if (artifacttemplateInfo != null) {
491                 artifactTemplateInfoList.add(artifacttemplateInfo);
492             }
493
494         }
495         return Either.left(artifactTemplateInfoList);
496     }
497
498
499
500     private Either<Resource, ResponseFormat> createGroupDeploymentArtifactsFromCsar(CsarInfo csarInfo,
501             Resource resource, List<ArtifactTemplateInfo> artifactsTemplateList,
502             List<ArtifactDefinition> createdArtifacts, int labelCounter, boolean shouldLock, boolean inTransaction) {
503         Either<Resource, ResponseFormat> resStatus = Either.left(resource);
504         List<GroupDefinition> createdGroups = resource.getGroups();
505         List<GroupDefinition> heatGroups = null;
506         if (createdGroups != null && !createdGroups.isEmpty()) {
507
508             heatGroups = createdGroups.stream().filter(e -> e.getMembers() != null).collect(Collectors.toList());
509
510         }
511         List<GroupDefinition> needToCreate = new ArrayList<>();
512         for (ArtifactTemplateInfo groupTemplateInfo : artifactsTemplateList) {
513             String groupName = groupTemplateInfo.getGroupName();
514             Set<String> artifactsGroup = new HashSet<>();
515             Set<String> artifactsUUIDGroup = new HashSet<>();
516
517             log.debug("createDeploymentArtifactsFromCsar start");
518             resStatus = createDeploymentArtifactFromCsar(csarInfo, ARTIFACTS_PATH, resource, artifactsGroup,
519                     artifactsUUIDGroup, groupTemplateInfo, createdArtifacts, labelCounter, shouldLock, inTransaction);
520             log.debug("createDeploymentArtifactsFromCsar end");
521             if (resStatus.isRight()) {
522                 return resStatus;
523             }
524             if (groupName != null && !groupName.isEmpty()) {
525
526                 Either<GroupDefinition, ResponseFormat> groupDefinitionEither = buildGroupDefinition(createdArtifacts, heatGroups, groupTemplateInfo,
527                         groupName, artifactsGroup, artifactsUUIDGroup);
528                 if (groupDefinitionEither.isRight()) {
529                     return Either.right(groupDefinitionEither.right().value());
530                 }
531                 needToCreate.add(groupDefinitionEither.left().value());
532             }
533         }
534
535         ComponentParametersView componentParametersView = new ComponentParametersView();
536         componentParametersView.disableAll();
537         componentParametersView.setIgnoreUsers(false);
538         componentParametersView.setIgnoreArtifacts(false);
539         componentParametersView.setIgnoreGroups(false);
540
541         componentParametersView.setIgnoreComponentInstances(false);
542
543         Either<Resource, StorageOperationStatus> component = toscaOperationFacade
544                 .getToscaElement(resource.getUniqueId(), componentParametersView);
545
546         if (component.isRight()) {
547             return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
548         }
549
550         Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic
551                 .addGroups(component.left().value(), needToCreate, false);
552         if (createGroups.isRight()) {
553             return Either.right(createGroups.right().value());
554         }
555
556         return Either.left(component.left().value());
557     }
558
559     private Either<GroupDefinition, ResponseFormat>  buildGroupDefinition(List<ArtifactDefinition> createdArtifacts,
560             List<GroupDefinition> heatGroups, ArtifactTemplateInfo groupTemplateInfo, String groupName,
561             Set<String> artifactsGroup, Set<String> artifactsUUIDGroup) {
562
563         Map<String, String> members = new HashMap<>();
564
565         associateMembersToArtifacts(createdArtifacts, null, heatGroups, artifactsGroup, members);
566
567         List<String> artifactsList = new ArrayList<>(artifactsGroup);
568         List<String> artifactsUUIDList = new ArrayList<>(artifactsUUIDGroup);
569
570         GroupDefinition groupDefinition = new GroupDefinition();
571         groupDefinition.setName(groupName);
572         groupDefinition.setType(Constants.DEFAULT_GROUP_VF_MODULE);
573         groupDefinition.setArtifacts(artifactsList);
574         groupDefinition.setArtifactsUuid(artifactsUUIDList);
575
576         if (!members.isEmpty()) {
577             groupDefinition.setMembers(members);
578         }
579         List<GroupProperty> properties = new ArrayList<>();
580         GroupProperty prop = new GroupProperty();
581         prop.setName(Constants.IS_BASE);
582         prop.setValue(Boolean.toString(groupTemplateInfo.isBase()));
583         properties.add(prop);
584         Either<GroupTypeDefinition, StorageOperationStatus> getLatestGroupTypeRes = groupTypeOperation
585                 .getLatestGroupTypeByType(Constants.DEFAULT_GROUP_VF_MODULE, true);
586         if (getLatestGroupTypeRes.isRight()) {
587             return Either.right(componentsUtils.getResponseFormat(
588                     componentsUtils.convertFromStorageResponse(getLatestGroupTypeRes.right().value())));
589         }
590         properties = createVfModuleAdditionalProperties(groupTemplateInfo.isBase(), groupName, properties,
591                 createdArtifacts, artifactsList, getLatestGroupTypeRes.left().value());
592         groupDefinition.convertFromGroupProperties(properties);
593         log.debug("createGroup start");
594         return Either.left(groupDefinition);
595     }
596
597     private Either<Resource, ResponseFormat> createDeploymentArtifactFromCsar(CsarInfo csarInfo, String artifactPath,
598             Resource resource, Set<String> artifactsGroup, Set<String> artifactsUUIDGroup,
599             ArtifactTemplateInfo artifactTemplateInfo, List<ArtifactDefinition> createdArtifacts, int labelCounter,
600             boolean shoudLock, boolean inTransaction) {
601         Either<Resource, ResponseFormat> resStatus = Either.left(resource);
602
603         String artifactUid = "";
604         String artifactEnvUid = "";
605         String artifactUUID = "";
606
607
608         // check if artifacts already exist
609         Either<ArtifactDefinition, ResponseFormat> createdArtifactEther = checkIfArtifactAlreadyExist(artifactTemplateInfo, createdArtifacts);
610         if(createdArtifactEther.isRight()){
611             return Either.right(createdArtifactEther.right().value());
612         }
613         ArtifactDefinition createdArtifact = createdArtifactEther.left().value();
614         if(createdArtifact == null){
615
616             Either<ArtifactDefinition, ResponseFormat> newArtifactEither = createDeploymentArtifact(csarInfo, resource,
617                     artifactPath, artifactTemplateInfo, createdArtifacts, labelCounter);
618             if (newArtifactEither.isRight()) {
619                 resStatus = Either.right(newArtifactEither.right().value());
620                 return resStatus;
621             }
622             ArtifactDefinition newArtifact = newArtifactEither.left().value();
623             artifactUid = newArtifact.getUniqueId();
624             artifactUUID = newArtifact.getArtifactUUID();
625
626             ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(newArtifact.getArtifactType());
627             if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET
628                     || artifactType == ArtifactTypeEnum.HEAT_VOL) {
629                 Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactsBusinessLogic
630                         .createHeatEnvPlaceHolder(newArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME,
631                                 resource.getUniqueId(), NodeTypeEnum.Resource, resource.getName(),
632                                 csarInfo.getModifier(), resource, null);
633                 if (createHeatEnvPlaceHolder.isRight()) {
634                     return Either.right(createHeatEnvPlaceHolder.right().value());
635                 }
636                 artifactEnvUid = createHeatEnvPlaceHolder.left().value().getUniqueId();
637             }
638         }else{
639             artifactUid = createdArtifact.getUniqueId();
640             artifactUUID = createdArtifact.getArtifactUUID();
641             artifactEnvUid = checkAndGetHeatEnvId(createdArtifact);
642         }
643         artifactsGroup.add(artifactUid);
644         artifactsUUIDGroup.add(artifactUUID);
645         if (!artifactEnvUid.isEmpty()) {
646             artifactsGroup.add(artifactEnvUid);
647         }
648
649         List<ArtifactTemplateInfo> relatedArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo();
650         if (relatedArtifacts != null) {
651             for (ArtifactTemplateInfo relatedArtifactTemplateInfo : relatedArtifacts) {
652                 resStatus = createDeploymentArtifactFromCsar(csarInfo, artifactPath, resource, artifactsGroup,
653                         artifactsUUIDGroup, relatedArtifactTemplateInfo, createdArtifacts, labelCounter, shoudLock,
654                         inTransaction);
655                 if (resStatus.isRight()) {
656                     return resStatus;
657                 }
658             }
659         }
660         return resStatus;
661     }
662
663     private String checkAndGetHeatEnvId(ArtifactDefinition createdArtifact) {
664         String artifactEnvUid = "";
665         ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(createdArtifact.getArtifactType());
666         if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET
667                 || artifactType == ArtifactTypeEnum.HEAT_VOL) {
668             artifactEnvUid = createdArtifact.getUniqueId() + ArtifactsBusinessLogic.HEAT_ENV_SUFFIX;
669         }
670         return artifactEnvUid;
671     }
672
673     private Either<ArtifactDefinition, ResponseFormat> checkIfArtifactAlreadyExist(ArtifactTemplateInfo artifactTemplateInfo, List<ArtifactDefinition> createdArtifacts){
674
675         ArtifactDefinition res = null;
676         String artifactFileName = artifactTemplateInfo.getFileName();
677         Optional<ArtifactDefinition> op = createdArtifacts.stream().filter(a -> a.getArtifactName().equals(artifactFileName)).findAny();
678         if(op.isPresent()){
679             res = op.get();
680             if (!res.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) {
681                 log.debug(ARTIFACT_WITH_NAME_AND_TYPE_ALREADY_EXIST_WITH_TYPE, artifactFileName,
682                         artifactTemplateInfo.getType(), res.getArtifactType());
683                 BeEcompErrorManager.getInstance().logInternalDataError(
684                         ARTIFACT_FILE_IS_NOT_IN_EXPECTED_FORMATR_FILE_NAME1 + artifactFileName,
685                         ARTIFACT_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
686                 return Either.right(componentsUtils.getResponseFormat(
687                         ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName,
688                         artifactTemplateInfo.getType(), res.getArtifactType()));
689             }
690         }
691         return Either.left(res);
692
693
694     }
695
696     private Either<ArtifactDefinition, ResponseFormat> createDeploymentArtifact(CsarInfo csarInfo, Resource resource,
697                                                                                 String artifactPath, ArtifactTemplateInfo artifactTemplateInfo, List<ArtifactDefinition> createdArtifacts,
698                                                                                 int label) {
699         int updatedlabel = label;
700         final String artifactFileName = artifactTemplateInfo.getFileName();
701         Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactContententStatus = CsarValidationUtils
702                 .getArtifactsContent(csarInfo.getCsarUUID(), csarInfo.getCsar(), artifactPath + artifactFileName,
703                         artifactFileName, componentsUtils);
704         if (artifactContententStatus.isRight()) {
705             return Either.right(artifactContententStatus.right().value());
706         }
707         updatedlabel += createdArtifacts.size();
708
709         Map<String, Object> json = ArtifactUtils.buildJsonForArtifact(artifactTemplateInfo,
710                 artifactContententStatus.left().value().getValue(), updatedlabel, true);
711
712         Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = createOrUpdateCsarArtifactFromJson(
713                 resource, csarInfo.getModifier(), json,
714                 artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.CREATE));
715
716         if (uploadArtifactToService.isRight()) {
717             return Either.right(uploadArtifactToService.right().value());
718         }
719
720         ArtifactDefinition currentInfo = uploadArtifactToService.left().value().left().value();
721         if (currentInfo.getHeatParameters() != null) {
722
723             Either<ArtifactDefinition, ResponseFormat> updateEnvEither = updateHeatParamsFromCsar(resource, csarInfo,
724                     artifactTemplateInfo, currentInfo, false);
725             if (updateEnvEither.isRight()) {
726                 log.debug("failed to update parameters to artifact {}", artifactFileName);
727                 return Either.right(updateEnvEither.right().value());
728
729             }
730             currentInfo = updateEnvEither.left().value();
731
732         }
733
734         createdArtifacts.add(currentInfo);
735
736         return Either.left(currentInfo);
737
738     }
739
740
741
742     private Either<ArtifactDefinition, ResponseFormat> updateHeatParamsFromCsar(Resource resource, CsarInfo csarInfo,
743             ArtifactTemplateInfo artifactTemplateInfo, ArtifactDefinition currentInfo, boolean isUpdateEnv) {
744
745         Resource updatedResource = resource;
746         Either<ArtifactDefinition, ResponseFormat> resStatus = Either.left(currentInfo);
747         if (artifactTemplateInfo.getEnv() != null && !artifactTemplateInfo.getEnv().isEmpty()) {
748
749             Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactparamsStatus = CsarValidationUtils
750                     .getArtifactsContent(csarInfo.getCsarUUID(), csarInfo.getCsar(),
751                             CsarUtils.ARTIFACTS_PATH + artifactTemplateInfo.getEnv(), artifactTemplateInfo.getEnv(),
752                             componentsUtils);
753             if (artifactparamsStatus.isRight()) {
754                 resStatus = Either.right(artifactparamsStatus.right().value());
755                 return resStatus;
756             }
757             Either<List<HeatParameterDefinition>, ResponseFormat> propsStatus = extractHeatParameters(
758                     ArtifactTypeEnum.HEAT_ENV.getType(), artifactTemplateInfo.getEnv(),
759                     artifactparamsStatus.left().value().getValue(), false);
760
761             if (propsStatus.isLeft()) {
762                 List<HeatParameterDefinition> updatedHeatEnvParams = propsStatus.left().value();
763                 resStatus = updateHeatParams(updatedResource, currentInfo, updatedHeatEnvParams);
764                 if (resStatus.isRight()) {
765                     return resStatus;
766                 }
767
768             }
769         }
770         if (isUpdateEnv) {
771             ComponentParametersView parametersView = new ComponentParametersView();
772             parametersView.disableAll();
773             parametersView.setIgnoreComponentInstances(false);
774             parametersView.setIgnoreUsers(false);
775             parametersView.setIgnoreArtifacts(false);
776             parametersView.setIgnoreGroups(false);
777
778             Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade
779                     .getToscaElement(updatedResource.getUniqueId(), parametersView);
780
781             if (eitherGerResource.isRight()) {
782                 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
783                         componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), updatedResource);
784
785                 resStatus = Either.right(responseFormat);
786                 return resStatus;
787
788             }
789
790             updatedResource = eitherGerResource.left().value();
791             Map<String, ArtifactDefinition> artifacts = updatedResource.getDeploymentArtifacts();
792             Optional<ArtifactDefinition> op = artifacts.values().stream().filter(
793                     p -> p.getGeneratedFromId() != null && p.getGeneratedFromId().equals(currentInfo.getUniqueId()))
794                     .findAny();
795             if (op.isPresent()) {
796                 ArtifactDefinition artifactInfoHeatEnv = op.get();
797                 Either<ArtifactDefinition, StorageOperationStatus> updateArifactOnResource = artifactToscaOperation
798                         .updateArtifactOnResource(artifactInfoHeatEnv, updatedResource.getUniqueId(),
799                                 artifactInfoHeatEnv.getUniqueId(), null, null);
800                 if (updateArifactOnResource.isRight()) {
801                     log.debug("Failed to update heat env on CSAR flow for component {} artifact {} label {}",
802                             updatedResource.getUniqueId(), artifactInfoHeatEnv.getUniqueId(),
803                             artifactInfoHeatEnv.getArtifactLabel());
804                     return Either.right(componentsUtils.getResponseFormat(
805                             componentsUtils.convertFromStorageResponse(updateArifactOnResource.right().value())));
806                 }
807                 resStatus = Either.left(updateArifactOnResource.left().value());
808             }
809         }
810         return resStatus;
811     }
812
813     private Either<List<HeatParameterDefinition>, ResponseFormat> extractHeatParameters(String artifactType,
814             String fileName, byte[] content, boolean is64Encoded) {
815         // extract heat parameters
816         String heatDecodedPayload = is64Encoded ? new String(Base64.decodeBase64(content)) : new String(content);
817         Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils
818                 .getHeatParamsWithoutImplicitTypes(heatDecodedPayload, artifactType);
819         if (heatParameters.isRight()) {
820             log.debug("File {} is not in expected key-value form in csar ", fileName);
821             BeEcompErrorManager.getInstance().logInternalDataError(
822                     "File " + fileName + " is not in expected key-value form in csar ", "CSAR internals are invalid",
823                     ErrorSeverity.ERROR);
824             return Either
825                     .right(componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, fileName));
826
827         }
828         return Either.left(heatParameters.left().value());
829
830     }
831
832     private Either<ArtifactDefinition, ResponseFormat> updateHeatParams(Resource resource,
833             ArtifactDefinition currentInfo, List<HeatParameterDefinition> updatedHeatEnvParams) {
834
835         Either<ArtifactDefinition, ResponseFormat> resStatus = Either.left(currentInfo);
836         List<HeatParameterDefinition> currentHeatEnvParams = currentInfo.getListHeatParameters();
837
838         if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty() && currentHeatEnvParams != null
839                 && !currentHeatEnvParams.isEmpty()) {
840
841             String paramName;
842             for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
843
844                 paramName = heatEnvParam.getName();
845                 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
846                     if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
847
848                         String updatedParamValue = heatEnvParam.getCurrentValue();
849                         if (updatedParamValue == null) {
850                             updatedParamValue = heatEnvParam.getDefaultValue();
851                         }
852                         HeatParameterType paramType = HeatParameterType.isValidType(currHeatParam.getType());
853                         if (!paramType.getValidator().isValid(updatedParamValue, null)) {
854                             ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
855                             ResponseFormat responseFormat = componentsUtils.getResponseFormat(status,
856                                     ArtifactTypeEnum.HEAT_ENV.getType(), paramType.getType(), paramName);
857                             resStatus = Either.right(responseFormat);
858                             return resStatus;
859                         }
860                         currHeatParam.setCurrentValue(
861                                 paramType.getConverter().convert(updatedParamValue, null, null));
862
863                         break;
864                     }
865                 }
866             }
867             currentInfo.setListHeatParameters(currentHeatEnvParams);
868             Either<ArtifactDefinition, StorageOperationStatus> updateArifactOnResource = artifactToscaOperation
869                     .updateArtifactOnResource(currentInfo, resource.getUniqueId(), currentInfo.getUniqueId(),
870                             null, null);
871             if (updateArifactOnResource.isRight()) {
872                 log.debug(
873                         "Failed to update heat paratemers of heat on CSAR flow for component {} artifact {} label {}",
874                         resource.getUniqueId(), currentInfo.getUniqueId(), currentInfo.getArtifactLabel());
875                 return Either.right(componentsUtils.getResponseFormat(
876                         componentsUtils.convertFromStorageResponse(updateArifactOnResource.right().value())));
877             }
878             resStatus = Either.left(updateArifactOnResource.left().value());
879         }
880         return resStatus;
881     }
882
883
884
885
886     public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createOrUpdateCsarArtifactFromJson(
887             Resource resource, User user, Map<String, Object> json, ArtifactOperationInfo operation) {
888
889         String jsonStr = gson.toJson(json);
890
891         String origMd5 = GeneralUtility.calculateMD5Base64EncodedByString(jsonStr);
892         ArtifactDefinition artifactDefinitionFromJson = RepresentationUtils.convertJsonToArtifactDefinition(jsonStr,
893                 ArtifactDefinition.class);
894                 
895         String artifactUniqueId = artifactDefinitionFromJson == null ? null : artifactDefinitionFromJson.getUniqueId();
896         Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = artifactsBusinessLogic
897                 .validateAndHandleArtifact(resource.getUniqueId(), ComponentTypeEnum.RESOURCE, operation,
898                         artifactUniqueId, artifactDefinitionFromJson, origMd5, jsonStr, null, null, user,
899                         resource, false, true, false);
900         if (uploadArtifactToService.isRight()) {
901             return Either.right(uploadArtifactToService.right().value());
902         }
903
904         return Either.left(uploadArtifactToService.left().value());
905     }
906
907     private void associateMembersToArtifacts(List<ArtifactDefinition> createdArtifacts,
908             List<ArtifactDefinition> artifactsFromResource, List<GroupDefinition> heatGroups,
909             Set<String> artifactsGroup, Map<String, String> members) {
910         if (heatGroups != null && !heatGroups.isEmpty()) {
911             for (GroupDefinition heatGroup : heatGroups) {
912                 List<GroupProperty> grpoupProps = heatGroup.convertToGroupProperties();
913                 if (grpoupProps != null) {
914                     associatemembersToVFgroups(createdArtifacts, artifactsFromResource, grpoupProps, artifactsGroup, heatGroup, members);
915                 }
916             }
917
918         }
919     }
920
921     private void associatemembersToVFgroups(List<ArtifactDefinition> createdArtifacts,List<ArtifactDefinition> artifactsFromResource, List<GroupProperty> grpoupProps, Set<String> artifactsGroup, GroupDefinition heatGroup, Map<String, String> members){
922         Optional<GroupProperty> op = grpoupProps.stream()
923                 .filter(p -> p.getName().equals(Constants.HEAT_FILE_PROPS)).findAny();
924         if (op.isPresent()) {
925             GroupProperty prop = op.get();
926             String heatFileNAme = prop.getValue();
927             if (null == heatFileNAme || heatFileNAme.isEmpty()) {
928                 return;
929             }
930             List<ArtifactDefinition> artifacts = new ArrayList<>();
931             for (String artifactId : artifactsGroup) {
932                 Optional<ArtifactDefinition> opArt = createdArtifacts.stream()
933                         .filter(p -> p.getUniqueId().equals(artifactId)).findAny();
934                 if (opArt.isPresent()) {
935                     artifacts.add(opArt.get());
936                 }
937                 if (artifactsFromResource != null) {
938                     opArt = artifactsFromResource.stream().filter(p -> p.getUniqueId().equals(artifactId))
939                             .findAny();
940                     if (opArt.isPresent()) {
941                         artifacts.add(opArt.get());
942                     }
943                 }
944             }
945             Optional<ArtifactDefinition> resOp = artifacts.stream()
946                     .filter(p -> heatFileNAme.contains(p.getArtifactName())).findAny();
947             if (resOp.isPresent()) {
948                 members.putAll(heatGroup.getMembers());
949             }
950         }
951     }
952
953     public List<GroupProperty> createVfModuleAdditionalProperties(boolean isBase, String moduleName,
954             List<GroupProperty> properties, List<ArtifactDefinition> deploymentArtifacts, List<String> artifactsInGroup,
955             GroupTypeDefinition groupType) {
956         Map<String, VfModuleProperty> vfModuleProperties = ConfigurationManager.getConfigurationManager()
957                 .getConfiguration().getVfModuleProperties();
958         vfModuleProperties.entrySet().forEach(p -> {
959             GroupProperty prop = new GroupProperty();
960             prop.setName(p.getKey());
961             if (isBase) {
962                 prop.setValue(p.getValue().getForBaseModule());
963                 prop.setDefaultValue(p.getValue().getForBaseModule());
964             } else {
965                 prop.setValue(p.getValue().getForNonBaseModule());
966                 prop.setDefaultValue(p.getValue().getForNonBaseModule());
967             }
968             properties.add(prop);
969
970         });
971         GroupProperty proplabel = new GroupProperty();
972         proplabel.setName("vf_module_label");
973
974         Matcher matcher = pattern.matcher(moduleName);
975
976         if (matcher.find()) {
977             proplabel.setValue(matcher.group(1));
978             proplabel.setDefaultValue(matcher.group(1));
979         } else {
980             proplabel.setValue(moduleName);
981             proplabel.setDefaultValue(moduleName);
982         }
983         properties.add(proplabel);
984
985         GroupProperty propvolume = new GroupProperty();
986         propvolume.setName("volume_group");
987         boolean isVolume = false;
988         for (String artifactId : artifactsInGroup) {
989             ArtifactDefinition artifactDef = null;
990             artifactDef = ArtifactUtils.findArtifactInList(deploymentArtifacts, artifactId);
991             if (artifactDef != null
992                     && artifactDef.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType())) {
993                 isVolume = true;
994                 break;
995             }
996         }
997         propvolume.setValue(String.valueOf(isVolume));
998         propvolume.setDefaultValue(String.valueOf(isVolume));
999         properties.add(propvolume);
1000         mergeWithGroupTypeProperties(properties, groupType.getProperties());
1001         return properties;
1002     }
1003
1004     private void mergeWithGroupTypeProperties(List<GroupProperty> properties,
1005             List<PropertyDefinition> groupTypeProperties) {
1006
1007         Map<String, GroupProperty> propertiesMap = properties.stream()
1008                 .collect(Collectors.toMap(PropertyDataDefinition::getName, p -> p));
1009         for (PropertyDefinition groupTypeProperty : groupTypeProperties) {
1010             if (!propertiesMap.containsKey(groupTypeProperty.getName())) {
1011                 properties.add(new GroupProperty(groupTypeProperty));
1012             }
1013         }
1014     }
1015
1016     private Map<GroupDefinition, MergedArtifactInfo> mergeGroupInUpdateFlow(
1017             Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupArtifact,
1018             Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup, Set<ArtifactDefinition> artifactsToDelete,
1019             Map<String, List<ArtifactDefinition>> groupToDelete, Set<ArtifactTemplateInfo> jsonMasterArtifacts,
1020             List<ArtifactDefinition> createdDeplymentArtifacts) {
1021         Map<GroupDefinition, MergedArtifactInfo> mergedgroup = new HashMap<>();
1022         for (Entry<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupListEntry : groupArtifact
1023                 .entrySet()) {
1024             Map<ArtifactDefinition, List<ArtifactDefinition>> createdArtifactMap = groupListEntry.getValue();
1025             boolean isNeedToDeleteGroup = true;
1026             List<ArtifactDefinition> listToDelete = null;
1027             for (ArtifactDefinition maserArtifact : createdArtifactMap.keySet()) {
1028                 listToDelete = createdArtifactMap.get(maserArtifact);
1029                 for (ArtifactDefinition artToDelete : listToDelete) {
1030                     findArtifactToDelete(parsedGroup, artifactsToDelete, artToDelete, createdDeplymentArtifacts);
1031                 }
1032                 if (artifactsToDelete != null && !artifactsToDelete.isEmpty()) {
1033                     GroupDefinition group = groupListEntry.getKey();
1034                     for (ArtifactDefinition artifactDefinition : artifactsToDelete) {
1035                         if (CollectionUtils.isNotEmpty(group.getArtifacts())
1036                                 && group.getArtifacts().contains(artifactDefinition.getUniqueId())) {
1037                             group.getArtifacts().remove(artifactDefinition.getUniqueId());
1038
1039                         }
1040                         if (CollectionUtils.isNotEmpty(group.getArtifactsUuid())
1041                                 && group.getArtifactsUuid().contains(artifactDefinition.getArtifactUUID())) {
1042                             group.getArtifactsUuid().remove(artifactDefinition.getArtifactUUID());
1043
1044                         }
1045                     }
1046
1047                 }
1048
1049                 for (ArtifactTemplateInfo jsonMasterArtifact : jsonMasterArtifacts) {
1050                     if (maserArtifact.getArtifactName().equalsIgnoreCase(jsonMasterArtifact.getFileName())) {
1051                         MergedArtifactInfo mergedGroup = new MergedArtifactInfo();
1052                         mergedGroup.setJsonArtifactTemplate(jsonMasterArtifact);
1053                         mergedGroup.setCreatedArtifact(createdArtifactMap.get(maserArtifact));
1054                         mergedgroup.put(groupListEntry.getKey(), mergedGroup);
1055                         isNeedToDeleteGroup = false;
1056
1057                     }
1058                 }
1059
1060             }
1061             if (isNeedToDeleteGroup) {
1062                 groupToDelete.put(groupListEntry.getKey().getUniqueId(), listToDelete);
1063             }
1064
1065         }
1066         return mergedgroup;
1067     }
1068
1069     private void findArtifactToDelete(Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup,
1070             Set<ArtifactDefinition> artifactsToDelete, ArtifactDefinition artifact,
1071             List<ArtifactDefinition> createdDeplymentArtifacts) {
1072         boolean isNeedToDeleteArtifact = true;
1073         String artifactType = artifact.getArtifactType();
1074         ArtifactDefinition generatedFromArt = null;
1075         if (artifact.getGeneratedFromId() != null && !artifact.getGeneratedFromId().isEmpty()) {
1076             Optional<ArtifactDefinition> op = createdDeplymentArtifacts.stream()
1077                     .filter(p -> p.getUniqueId().equals(artifact.getGeneratedFromId())).findAny();
1078             if (op.isPresent()) {
1079                 generatedFromArt = op.get();
1080             }
1081
1082         }
1083
1084         for (Entry<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroupSetEntry : parsedGroup.entrySet()) {
1085             Set<ArtifactTemplateInfo> artifactsNames = parsedGroupSetEntry.getValue();
1086             for (ArtifactTemplateInfo template : artifactsNames) {
1087                 if (artifact.getArtifactName().equalsIgnoreCase(template.getFileName())
1088                         && artifactType.equalsIgnoreCase(template.getType())) {
1089                     isNeedToDeleteArtifact = false;
1090                     break;
1091
1092                 } else {
1093
1094                     if (generatedFromArt != null) {
1095                         if (generatedFromArt.getArtifactName().equalsIgnoreCase(template.getFileName())
1096                                 && generatedFromArt.getArtifactType().equalsIgnoreCase(template.getType())) {
1097                             isNeedToDeleteArtifact = false;
1098                             break;
1099                         }
1100                     }
1101                 }
1102             }
1103
1104         }
1105         if (isNeedToDeleteArtifact) {
1106             artifactsToDelete.add(artifact);
1107
1108         }
1109     }
1110
1111     private Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> findMasterArtifactInGroup(
1112             List<GroupDefinition> groups, Map<String, ArtifactDefinition> deplymentArtifact) {
1113         Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupArtifact = new HashMap<>();
1114
1115         for (GroupDefinition group : groups) {
1116             Map<ArtifactDefinition, List<ArtifactDefinition>> gupsMap = new HashMap<>();
1117             List<ArtifactDefinition> artifacts = new ArrayList<>();
1118             List<String> artifactsList = group.getArtifacts();
1119             if (artifactsList != null && !artifactsList.isEmpty()) {
1120
1121                 ArtifactDefinition masterArtifact = ArtifactUtils.findMasterArtifact(deplymentArtifact, artifacts,
1122                         artifactsList);
1123                 if (masterArtifact != null) {
1124                     gupsMap.put(masterArtifact, artifacts);
1125                 }
1126                 groupArtifact.put(group, gupsMap);
1127
1128             }
1129         }
1130         return groupArtifact;
1131     }
1132
1133     private Either<Resource, ResponseFormat> deleteArtifactsInUpdateCsarFlow(Resource resource,
1134             User user, boolean shouldLock, boolean inTransaction, Set<ArtifactDefinition> artifactsToDelete,
1135             Map<String, List<ArtifactDefinition>> groupToDelete, List<ArtifactDefinition> deletedArtifacts) {
1136
1137         Resource updatedResource = resource;
1138
1139         String resourceId = updatedResource.getUniqueId();
1140         if (!artifactsToDelete.isEmpty()) {
1141             for (ArtifactDefinition artifact : artifactsToDelete) {
1142                 String artifactType = artifact.getArtifactType();
1143                 ArtifactTypeEnum artifactTypeEnum = ArtifactTypeEnum.findType(artifactType);
1144                 if (artifactTypeEnum != ArtifactTypeEnum.HEAT_ENV) {
1145                     Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic
1146                             .handleDelete(resourceId, artifact.getUniqueId(), user, AuditingActionEnum.ARTIFACT_DELETE,
1147                                     ComponentTypeEnum.RESOURCE, updatedResource, shouldLock, inTransaction);
1148                     if (handleDelete.isRight()) {
1149                         return Either.right(handleDelete.right().value());
1150                     }
1151
1152                     deletedArtifacts.add(handleDelete.left().value().left().value());
1153                 }
1154
1155             }
1156         }
1157         if (!groupToDelete.isEmpty()) {
1158             log.debug("try to delete group");
1159             List<GroupDefinition> groupDefinitionstoDelete = new ArrayList<>();
1160             List<GroupDefinition> groups = updatedResource.getGroups();
1161             for (Entry<String, List<ArtifactDefinition>> deleteGroup : groupToDelete.entrySet()) {
1162                 Optional<GroupDefinition> op = groups.stream()
1163                         .filter(gr -> gr.getUniqueId().equals(deleteGroup.getKey())).findAny();
1164                 if (op.isPresent()) {
1165                     groupDefinitionstoDelete.add(op.get());
1166                 }
1167
1168             }
1169             if (!groupDefinitionstoDelete.isEmpty()) {
1170                 Either<List<GroupDefinition>, ResponseFormat> prepareGroups = groupBusinessLogic.deleteGroups(resource, groupDefinitionstoDelete);
1171                 if (prepareGroups.isRight()) {
1172                     return Either.right(prepareGroups.right().value());
1173                 }
1174             }
1175         }
1176         List<GroupDefinition> oldGroups = updatedResource.getGroups();
1177         Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade
1178                 .getToscaElement(updatedResource.getUniqueId());
1179         if (eitherGerResource.isRight()) {
1180             ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
1181                     componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), updatedResource);
1182
1183             return Either.right(responseFormat);
1184
1185         }
1186         updatedResource = eitherGerResource.left().value();
1187         updatedResource.setGroups(oldGroups);
1188         return Either.left(updatedResource);
1189     }
1190
1191     private void createArtifactsGroupSet(List<ArtifactTemplateInfo> parsedGroupTemplateList,
1192             Set<ArtifactTemplateInfo> parsedArtifactsName) {
1193
1194         for (ArtifactTemplateInfo parsedGroupTemplate : parsedGroupTemplateList) {
1195             parsedArtifactsName.add(parsedGroupTemplate);
1196             List<ArtifactTemplateInfo> relatedArtifacts = parsedGroupTemplate.getRelatedArtifactsInfo();
1197             if (relatedArtifacts != null && !relatedArtifacts.isEmpty()) {
1198                 createArtifactsGroupSet(relatedArtifacts, parsedArtifactsName);
1199             }
1200         }
1201     }
1202
1203     private Either<Resource, ResponseFormat> createGroupDeploymentArtifactsFromCsar(CsarInfo csarInfo,
1204             Resource resource, List<ArtifactTemplateInfo> artifactsTemplateList,
1205             List<ArtifactDefinition> createdNewArtifacts, List<ArtifactDefinition> artifactsFromResource,
1206             int labelCounter, boolean shouldLock, boolean inTransaction) {
1207
1208         Resource updatedResource = resource;
1209
1210         Either<Resource, ResponseFormat> resStatus = Either.left(updatedResource);
1211         List<GroupDefinition> createdGroups = updatedResource.getGroups();
1212         List<GroupDefinition> heatGroups = null;
1213         if (createdGroups != null && !createdGroups.isEmpty()) {
1214             heatGroups = createdGroups.stream().filter(e -> e.getMembers() != null).collect(Collectors.toList());
1215         }
1216
1217         List<GroupDefinition> needToAdd = new ArrayList<>();
1218         for (ArtifactTemplateInfo groupTemplateInfo : artifactsTemplateList) {
1219             String groupName = groupTemplateInfo.getGroupName();
1220             Set<String> artifactsGroup = new HashSet<>();
1221             Set<String> artifactsUUIDGroup = new HashSet<>();
1222
1223             resStatus = createDeploymentArtifactsFromCsar(csarInfo, updatedResource, artifactsGroup, artifactsUUIDGroup,
1224                     groupTemplateInfo, createdNewArtifacts, artifactsFromResource, labelCounter, shouldLock,
1225                     inTransaction);
1226             if (resStatus.isRight()) {
1227                 return resStatus;
1228             }
1229             if (groupName != null && !groupName.isEmpty()) {
1230                 Map<String, String> members = new HashMap<>();
1231                 associateMembersToArtifacts(createdNewArtifacts, artifactsFromResource, heatGroups, artifactsGroup,
1232                         members);
1233
1234                 List<String> artifactsList = new ArrayList<>(artifactsGroup);
1235                 List<String> artifactsUUIDList = new ArrayList<>(artifactsUUIDGroup);
1236
1237                 GroupDefinition groupDefinition = new GroupDefinition();
1238                 groupDefinition.setName(groupName);
1239                 groupDefinition.setType(Constants.DEFAULT_GROUP_VF_MODULE);
1240                 groupDefinition.setArtifacts(artifactsList);
1241                 groupDefinition.setArtifactsUuid(artifactsUUIDList);
1242
1243                 if (!members.isEmpty()) {
1244                     groupDefinition.setMembers(members);
1245                 }
1246
1247                 List<GroupProperty> properties = new ArrayList<>();
1248                 GroupProperty prop = new GroupProperty();
1249                 prop.setName(Constants.IS_BASE);
1250                 prop.setValue(Boolean.toString(groupTemplateInfo.isBase()));
1251                 properties.add(prop);
1252
1253                 List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
1254                 createdArtifacts.addAll(createdNewArtifacts);
1255                 createdArtifacts.addAll(artifactsFromResource);
1256                 Either<GroupTypeDefinition, StorageOperationStatus> getLatestGroupTypeRes = groupTypeOperation
1257                         .getLatestGroupTypeByType(Constants.DEFAULT_GROUP_VF_MODULE, true);
1258                 if (getLatestGroupTypeRes.isRight()) {
1259                     return Either.right(componentsUtils.getResponseFormat(
1260                             componentsUtils.convertFromStorageResponse(getLatestGroupTypeRes.right().value())));
1261                 }
1262                 properties = createVfModuleAdditionalProperties(groupTemplateInfo.isBase(), groupName, properties,
1263                         createdArtifacts, artifactsList, getLatestGroupTypeRes.left().value());
1264                 groupDefinition.convertFromGroupProperties(properties);
1265
1266                 needToAdd.add(groupDefinition);
1267             }
1268         }
1269         ComponentParametersView componentParametersView = new ComponentParametersView();
1270         componentParametersView.disableAll();
1271         componentParametersView.setIgnoreArtifacts(false);
1272         componentParametersView.setIgnoreGroups(false);
1273         componentParametersView.setIgnoreComponentInstances(false);
1274
1275         Either<Resource, StorageOperationStatus> component = toscaOperationFacade
1276                 .getToscaElement(updatedResource.getUniqueId(), componentParametersView);
1277         if (component.isRight()) {
1278             return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1279         }
1280         updatedResource = component.left().value();
1281
1282          Either<List<GroupDefinition>, ResponseFormat> addGroups = groupBusinessLogic.addGroups(updatedResource, needToAdd, false);
1283         if (addGroups.isRight()) {
1284             return Either.right(addGroups.right().value());
1285         }
1286
1287         return resStatus;
1288     }
1289
1290     private Either<Resource, ResponseFormat> createDeploymentArtifactsFromCsar(CsarInfo csarInfo, Resource resource,
1291             Set<String> artifactsGroup, Set<String> artifactsUUIDGroup, ArtifactTemplateInfo artifactTemplateInfo,
1292             List<ArtifactDefinition> createdArtifacts, List<ArtifactDefinition> artifactsFromResource, int labelCounter,
1293             boolean shoudLock, boolean inTransaction) {
1294         Either<Resource, ResponseFormat> resStatus = Either.left(resource);
1295         String artifactFileName = artifactTemplateInfo.getFileName();
1296         String artifactUid = "";
1297         String artifactUUID = "";
1298         String artifactEnvUid = "";
1299         boolean alreadyExist = false;
1300
1301         // check if artifacts already exist
1302         if (artifactsFromResource != null && !artifactsFromResource.isEmpty()) {
1303             for (ArtifactDefinition artifactFromResource : artifactsFromResource) {
1304                 if (artifactFromResource.getArtifactName().equals(artifactFileName)) {
1305                     artifactUid = artifactFromResource.getUniqueId();
1306                     artifactUUID = artifactFromResource.getArtifactUUID();
1307                     if (!artifactFromResource.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) {
1308                         log.debug(ARTIFACT_WITH_NAME_AND_TYPE_ALREADY_EXIST_WITH_TYPE, artifactFileName,
1309                                 artifactTemplateInfo.getType(), artifactFromResource.getArtifactType());
1310                         BeEcompErrorManager.getInstance().logInternalDataError(
1311                                 ARTIFACT_FILE_IS_NOT_IN_EXPECTED_FORMATR_FILE_NAME1 + artifactFileName,
1312                                 ARTIFACT_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
1313                         return Either.right(componentsUtils.getResponseFormat(
1314                                 ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName,
1315                                 artifactTemplateInfo.getType(), artifactFromResource.getArtifactType()));
1316                     }
1317                     alreadyExist = true;
1318                     artifactEnvUid = checkAndGetHeatEnvId(artifactFromResource);
1319                     break;
1320                 }
1321
1322             }
1323
1324         }
1325         if (!alreadyExist) {
1326             for (ArtifactDefinition createdArtifact : createdArtifacts) {
1327                 if (createdArtifact.getArtifactName().equals(artifactFileName)) {
1328                     artifactUid = createdArtifact.getUniqueId();
1329                     artifactUUID = createdArtifact.getArtifactUUID();
1330
1331                     if (!createdArtifact.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) {
1332                         log.debug(ARTIFACT_WITH_NAME_AND_TYPE_ALREADY_EXIST_WITH_TYPE, artifactFileName,
1333                                 artifactTemplateInfo.getType(), createdArtifact.getArtifactType());
1334                         BeEcompErrorManager.getInstance().logInternalDataError(
1335                                 ARTIFACT_FILE_IS_NOT_IN_EXPECTED_FORMATR_FILE_NAME1 + artifactFileName,
1336                                 ARTIFACT_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
1337                         return Either.right(componentsUtils.getResponseFormat(
1338                                 ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName,
1339                                 artifactTemplateInfo.getType(), createdArtifact.getArtifactType()));
1340                     }
1341                     alreadyExist = true;
1342                     artifactEnvUid = checkAndGetHeatEnvId(createdArtifact);
1343                     break;
1344                 }
1345
1346             }
1347         }
1348         // if not exist need to create
1349         if (!alreadyExist) {
1350
1351             Either<ArtifactDefinition, ResponseFormat> newArtifactEither = createDeploymentArtifact(csarInfo, resource,
1352                     ARTIFACTS_PATH, artifactTemplateInfo, createdArtifacts, labelCounter);
1353             if (newArtifactEither.isRight()) {
1354                 resStatus = Either.right(newArtifactEither.right().value());
1355                 return resStatus;
1356             }
1357             ArtifactDefinition newArtifact = newArtifactEither.left().value();
1358             artifactUid = newArtifact.getUniqueId();
1359             artifactUUID = newArtifact.getArtifactUUID();
1360             ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(newArtifact.getArtifactType());
1361             if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET
1362                     || artifactType == ArtifactTypeEnum.HEAT_VOL) {
1363                 Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactsBusinessLogic
1364                         .createHeatEnvPlaceHolder(newArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME,
1365                                 resource.getUniqueId(), NodeTypeEnum.Resource, resource.getName(),
1366                                 csarInfo.getModifier(), resource, null);
1367                 if (createHeatEnvPlaceHolder.isRight()) {
1368                     return Either.right(createHeatEnvPlaceHolder.right().value());
1369                 }
1370                 artifactEnvUid = createHeatEnvPlaceHolder.left().value().getUniqueId();
1371             }
1372         }
1373
1374         artifactsGroup.add(artifactUid);
1375         artifactsUUIDGroup.add(artifactUUID);
1376         if (!artifactEnvUid.isEmpty()) {
1377             artifactsGroup.add(artifactEnvUid);
1378         }
1379
1380         List<ArtifactTemplateInfo> relatedArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo();
1381         if (relatedArtifacts != null) {
1382             for (ArtifactTemplateInfo relatedArtifactTemplateInfo : relatedArtifacts) {
1383                 resStatus = createDeploymentArtifactsFromCsar(csarInfo, resource, artifactsGroup, artifactsUUIDGroup,
1384                         relatedArtifactTemplateInfo, createdArtifacts, artifactsFromResource, labelCounter, shoudLock,
1385                         inTransaction);
1386                 if (resStatus.isRight()) {
1387                     return resStatus;
1388                 }
1389             }
1390         }
1391         return resStatus;
1392     }
1393
1394     private Either<Resource, ResponseFormat> associateAndDissociateArtifactsToGroup(CsarInfo csarInfo,
1395                                                                                     Resource resource, List<ArtifactDefinition> createdNewArtifacts, int labelCounter,
1396                                                                                     boolean inTransaction, List<ArtifactDefinition> createdDeplymentArtifactsAfterDelete,
1397                                                                                     Map<GroupDefinition, MergedArtifactInfo> mergedgroup, List<ArtifactDefinition> deletedArtifacts) {
1398         Map<GroupDefinition, List<ArtifactTemplateInfo>> artifactsToAssotiate = new HashMap<>();
1399         Map<GroupDefinition, List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>>> artifactsToUpdateMap = new HashMap<>();
1400         Either<Resource, ResponseFormat> resEither = Either.left(resource);
1401         for (Entry<GroupDefinition, MergedArtifactInfo> entry : mergedgroup.entrySet()) {
1402             List<ArtifactDefinition> dissArtifactsInGroup = entry.getValue()
1403                     .getListToDissotiateArtifactFromGroup(deletedArtifacts);
1404             GroupDefinition grDef = entry.getKey();
1405             if (dissArtifactsInGroup != null && !dissArtifactsInGroup.isEmpty()) {
1406                 for (ArtifactDefinition art : dissArtifactsInGroup) {
1407                     grDef.getArtifacts().remove(art.getUniqueId());
1408                     grDef.getArtifactsUuid().remove(art.getArtifactUUID());
1409                 }
1410             }
1411
1412             List<ArtifactTemplateInfo> newArtifactsInGroup = entry.getValue().getListToAssociateArtifactToGroup();
1413             if (newArtifactsInGroup != null && !newArtifactsInGroup.isEmpty()) {
1414                 artifactsToAssotiate.put(entry.getKey(), newArtifactsInGroup);
1415             }
1416
1417             List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>> artifactsToUpdate = entry.getValue()
1418                     .getListToUpdateArtifactInGroup();
1419             if (artifactsToUpdate != null && !artifactsToUpdate.isEmpty()) {
1420                 artifactsToUpdateMap.put(entry.getKey(), artifactsToUpdate);
1421             }
1422         }
1423
1424         if (!artifactsToUpdateMap.isEmpty()) {
1425             List<ArtifactDefinition> updatedArtifacts = new ArrayList<>();
1426             for (Entry<GroupDefinition, List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>>> artifactsToUpdateEntry : artifactsToUpdateMap
1427                     .entrySet()) {
1428                 List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>> artifactsToUpdateList = artifactsToUpdateEntry
1429                         .getValue();
1430                 GroupDefinition groupToUpdate = artifactsToUpdateEntry.getKey();
1431
1432                 for (ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo> artifact : artifactsToUpdateList) {
1433                     String prevUUID = artifact.getKey().getArtifactUUID();
1434                     String prevId = artifact.getKey().getUniqueId();
1435                     String prevHeatEnvId = checkAndGetHeatEnvId(artifact.getKey());
1436                     Either<ArtifactDefinition, ResponseFormat> updateArtifactEither = updateDeploymentArtifactsFromCsar(
1437                             csarInfo, resource, artifact.getKey(), artifact.getValue(), updatedArtifacts,
1438                             artifact.getRight().getRelatedArtifactsInfo());
1439                     if (updateArtifactEither.isRight()) {
1440                         log.debug("failed to update artifacts. status is {}", updateArtifactEither.right().value());
1441                         resEither = Either.right(updateArtifactEither.right().value());
1442                         return resEither;
1443                     }
1444                     ArtifactDefinition artAfterUpdate = updateArtifactEither.left().value();
1445                     if (!prevUUID.equals(artAfterUpdate.getArtifactUUID())
1446                             || !prevId.equals(artAfterUpdate.getUniqueId())) {
1447                         groupToUpdate.getArtifacts().remove(prevId);
1448                         groupToUpdate.getArtifactsUuid().remove(prevUUID);
1449                         groupToUpdate.getArtifacts().add(artAfterUpdate.getUniqueId());
1450                         groupToUpdate.getArtifactsUuid().add(artAfterUpdate.getArtifactUUID());
1451                     }
1452                     Optional<ArtifactDefinition> op = updatedArtifacts.stream()
1453                             .filter(p -> p.getGeneratedFromId() != null
1454                             && p.getGeneratedFromId().equals(artAfterUpdate.getUniqueId()))
1455                             .findAny();
1456                     if (op.isPresent()) {
1457                         ArtifactDefinition artifactInfoHeatEnv = op.get();
1458                         groupToUpdate.getArtifacts().remove(prevHeatEnvId);
1459                         groupToUpdate.getArtifacts().add(artifactInfoHeatEnv.getUniqueId());
1460                     }
1461
1462                 }
1463             }
1464         }
1465
1466         for (Entry<GroupDefinition, List<ArtifactTemplateInfo>> associateEntry : artifactsToAssotiate.entrySet()) {
1467             List<ArtifactTemplateInfo> associatedArtifact = associateEntry.getValue();
1468             Set<String> arifactsUids = new HashSet<>();
1469             Set<String> arifactsUuids = new HashSet<>();
1470             for (ArtifactTemplateInfo artifactTemplate : associatedArtifact) { // try
1471                 // to
1472                 // find
1473                 // artifact
1474                 // in
1475                 // resource
1476                 boolean isCreate = true;
1477                 for (ArtifactDefinition createdArtifact : createdDeplymentArtifactsAfterDelete) {
1478                     if (artifactTemplate.getFileName().equalsIgnoreCase(createdArtifact.getArtifactName())) {
1479                         arifactsUids.add(createdArtifact.getUniqueId());
1480                         arifactsUuids.add(createdArtifact.getArtifactUUID());
1481                         isCreate = false;
1482                         String heatEnvId = checkAndGetHeatEnvId(createdArtifact);
1483                         if (!heatEnvId.isEmpty()) {
1484                             arifactsUids.add(heatEnvId);
1485                             Optional<ArtifactDefinition> op = createdDeplymentArtifactsAfterDelete.stream()
1486                                     .filter(p -> p.getUniqueId().equals(heatEnvId)).findAny();
1487                             if (op.isPresent()) {
1488                                 this.artifactToscaOperation.updateHeatEnvPlaceholder(op.get(), resource.getUniqueId(),
1489                                         resource.getComponentType().getNodeType());
1490
1491                             }
1492                         }
1493
1494                         break;
1495                     }
1496
1497                 }
1498                 if (isCreate) { // check if already created
1499                     for (ArtifactDefinition createdNewArtifact : createdNewArtifacts) {
1500                         if (artifactTemplate.getFileName().equalsIgnoreCase(createdNewArtifact.getArtifactName())) {
1501                             arifactsUids.add(createdNewArtifact.getUniqueId());
1502                             arifactsUuids.add(createdNewArtifact.getArtifactUUID());
1503                             isCreate = false;
1504                             String heatEnvId = checkAndGetHeatEnvId(createdNewArtifact);
1505                             if (!heatEnvId.isEmpty()) {
1506                                 arifactsUids.add(heatEnvId);
1507                             }
1508                             break;
1509                         }
1510                     }
1511                 }
1512
1513                 if (isCreate) {
1514                     Either<ArtifactDefinition, ResponseFormat> createArtifactEither = createDeploymentArtifact(csarInfo,
1515                             resource, ARTIFACTS_PATH, artifactTemplate, createdNewArtifacts, labelCounter);
1516                     if (createArtifactEither.isRight()) {
1517                         resEither = Either.right(createArtifactEither.right().value());
1518                         return resEither;
1519                     }
1520                     ArtifactDefinition createdArtifact = createArtifactEither.left().value();
1521                     arifactsUids.add(createdArtifact.getUniqueId());
1522                     arifactsUuids.add(createdArtifact.getArtifactUUID());
1523                     ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(createdArtifact.getArtifactType());
1524                     if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET
1525                             || artifactType == ArtifactTypeEnum.HEAT_VOL) {
1526                         Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactsBusinessLogic
1527                                 .createHeatEnvPlaceHolder(createdArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME,
1528                                         resource.getUniqueId(), NodeTypeEnum.Resource, resource.getName(),
1529                                         csarInfo.getModifier(), resource, null);
1530                         if (createHeatEnvPlaceHolder.isRight()) {
1531                             return Either.right(createHeatEnvPlaceHolder.right().value());
1532                         }
1533                         String heatEnvId = createHeatEnvPlaceHolder.left().value().getUniqueId();
1534                         arifactsUids.add(heatEnvId);
1535                     }
1536                 }
1537
1538             }
1539             if (arifactsUids != null && !arifactsUids.isEmpty()) {
1540                 List<String> artifactsToAssociate = new ArrayList<>();
1541                 artifactsToAssociate.addAll(arifactsUids);
1542                 GroupDefinition assotiateGroup = associateEntry.getKey();
1543                 assotiateGroup.getArtifacts().addAll(arifactsUids);
1544                 assotiateGroup.getArtifactsUuid().addAll(arifactsUuids);
1545             }
1546         }
1547
1548         ComponentParametersView parametersView = new ComponentParametersView();
1549         parametersView.disableAll();
1550         parametersView.setIgnoreComponentInstances(false);
1551         parametersView.setIgnoreUsers(false);
1552         parametersView.setIgnoreArtifacts(false);
1553         parametersView.setIgnoreGroups(false);
1554
1555         Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade
1556                 .getToscaElement(resource.getUniqueId(), parametersView);
1557
1558         if (eitherGerResource.isRight()) {
1559             ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
1560                     componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
1561
1562             resEither = Either.right(responseFormat);
1563             return resEither;
1564
1565         }
1566         resEither = Either.left(eitherGerResource.left().value());
1567         return resEither;
1568     }
1569
1570     private Either<ArtifactDefinition, ResponseFormat> updateDeploymentArtifactsFromCsar(CsarInfo csarInfo,
1571             Resource resource, ArtifactDefinition oldArtifact, ArtifactTemplateInfo artifactTemplateInfo,
1572             List<ArtifactDefinition> updatedArtifacts, List<ArtifactTemplateInfo> updatedRequiredArtifacts) {
1573
1574         Either<ArtifactDefinition, ResponseFormat> resStatus = null;
1575         String artifactFileName = artifactTemplateInfo.getFileName();
1576
1577         // check if artifacts already exist
1578         for (ArtifactDefinition updatedArtifact : updatedArtifacts) {
1579             if (updatedArtifact.getArtifactName().equals(artifactFileName)) {
1580                 if (!updatedArtifact.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) {
1581                     log.debug("Artifact with name {} and type {} already updated with type  {}", artifactFileName,
1582                             artifactTemplateInfo.getType(), updatedArtifact.getArtifactType());
1583                     BeEcompErrorManager.getInstance().logInternalDataError(
1584                             ARTIFACT_FILE_IS_NOT_IN_EXPECTED_FORMATR_FILE_NAME1 + artifactFileName,
1585                             ARTIFACT_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
1586                     resStatus = Either.right(componentsUtils.getResponseFormat(
1587                             ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName,
1588                             artifactTemplateInfo.getType(), updatedArtifact.getArtifactType()));
1589                     return resStatus;
1590                 }
1591                 resStatus = Either.left(updatedArtifact);
1592                 return resStatus;
1593             }
1594
1595         }
1596
1597         Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactContententStatus = CsarValidationUtils
1598                 .getArtifactsContent(csarInfo.getCsarUUID(), csarInfo.getCsar(),
1599                         CsarUtils.ARTIFACTS_PATH + artifactFileName, artifactFileName, componentsUtils);
1600         if (artifactContententStatus.isRight()) {
1601             resStatus = Either.right(artifactContententStatus.right().value());
1602             return resStatus;
1603         }
1604
1605         Map<String, Object> json = ArtifactUtils.buildJsonForUpdateArtifact(oldArtifact.getUniqueId(), artifactFileName,
1606                 oldArtifact.getArtifactType(), ArtifactGroupTypeEnum.DEPLOYMENT, oldArtifact.getArtifactLabel(),
1607                 oldArtifact.getArtifactDisplayName(), oldArtifact.getDescription(),
1608                 artifactContententStatus.left().value().getRight(), updatedRequiredArtifacts, oldArtifact.getIsFromCsar());
1609
1610         Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = createOrUpdateCsarArtifactFromJson(
1611                 resource, csarInfo.getModifier(), json,
1612                 artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.UPDATE));
1613
1614         if (uploadArtifactToService.isRight()) {
1615             resStatus = Either.right(uploadArtifactToService.right().value());
1616             return resStatus;
1617         }
1618         ArtifactDefinition currentInfo = uploadArtifactToService.left().value().left().value();
1619         updatedArtifacts.add(currentInfo);
1620
1621         Either<ArtifactDefinition, ResponseFormat> updateEnvEither = updateHeatParamsFromCsar(resource, csarInfo,
1622                 artifactTemplateInfo, currentInfo, true);
1623         if (updateEnvEither.isRight()) {
1624             log.debug("failed to update parameters to artifact {}", artifactFileName);
1625             resStatus = Either.right(updateEnvEither.right().value());
1626             return resStatus;
1627         }
1628
1629         updatedArtifacts.add(updateEnvEither.left().value());
1630         resStatus = Either.left(currentInfo);
1631
1632         return resStatus;
1633
1634     }
1635
1636     public Either<Resource, ResponseFormat> deleteVFModules(Resource resource, CsarInfo csarInfo, boolean shouldLock, boolean inTransaction) {
1637         Resource updatedResource = resource;
1638         List<GroupDefinition> groupsToDelete = updatedResource.getGroups();
1639         if(groupsToDelete != null && !groupsToDelete.isEmpty()){
1640             List<GroupDefinition> vfGroupsToDelete = groupsToDelete.stream().filter(g -> g.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)).collect(Collectors.toList());
1641             if(vfGroupsToDelete != null && !vfGroupsToDelete.isEmpty()){
1642                 for(GroupDefinition gr : vfGroupsToDelete){
1643                     List<String> artifacts = gr.getArtifacts();
1644                     for (String artifactId : artifacts) {
1645                         Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(updatedResource.getUniqueId(), artifactId, csarInfo.getModifier(), AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE,
1646                                 updatedResource, shouldLock, inTransaction);
1647                         if (handleDelete.isRight()) {
1648                             log.debug("Couldn't delete  artifact {}", artifactId);
1649                             return Either.right(handleDelete.right().value());
1650                         }
1651                     }
1652
1653                 }
1654                 groupBusinessLogic.deleteGroups(updatedResource, vfGroupsToDelete);
1655
1656                 Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(updatedResource.getUniqueId());
1657                 if (eitherGetResource.isRight()) {
1658                     ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), updatedResource);
1659
1660                     return Either.right(responseFormat);
1661
1662                 }
1663                 updatedResource = eitherGetResource.left().value();
1664             }
1665         }
1666         return Either.left(updatedResource);
1667     }
1668
1669     private Either<Resource, ResponseFormat>  getResourcetFromGraph(Resource component){
1670         log.debug("getResource start");
1671         return toscaOperationFacade.getToscaElement(component.getUniqueId())
1672                 .right()
1673                 .map(rf ->  componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(rf), component))
1674                 .left()
1675                 .map (c -> (Resource) c);
1676         
1677
1678     }
1679
1680 }