Remove dead code
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / components / impl / ServiceImportParseLogic.java
1 /*
2  * Copyright (C) 2020 CMCC, Inc. and others. All rights reserved.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.openecomp.sdc.be.components.impl;
18
19
20 import fj.data.Either;
21 import lombok.Getter;
22 import lombok.Setter;
23 import org.apache.commons.codec.binary.Base64;
24 import org.apache.commons.collections.CollectionUtils;
25 import org.apache.commons.collections.MapUtils;
26 import org.apache.commons.lang3.tuple.ImmutablePair;
27 import org.openecomp.sdc.be.components.csar.CsarInfo;
28 import org.openecomp.sdc.be.components.impl.artifact.ArtifactOperationInfo;
29 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
30 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
31 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
32 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
33 import org.openecomp.sdc.be.config.BeEcompErrorManager;
34 import org.openecomp.sdc.be.config.ConfigurationManager;
35 import org.openecomp.sdc.be.dao.api.ActionStatus;
36 import org.openecomp.sdc.be.datatypes.elements.*;
37 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
38 import org.openecomp.sdc.be.datatypes.enums.CreatedFrom;
39 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
40 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
41 import org.openecomp.sdc.be.impl.ComponentsUtils;
42 import org.openecomp.sdc.be.model.*;
43 import org.openecomp.sdc.be.model.category.CategoryDefinition;
44 import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
45 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade;
46 import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter;
47 import org.openecomp.sdc.be.model.operations.api.ICapabilityTypeOperation;
48 import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation;
49 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
50 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
51 import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
52 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
53 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo;
54 import org.openecomp.sdc.be.tosca.CsarUtils;
55 import org.openecomp.sdc.be.utils.CommonBeUtils;
56 import org.openecomp.sdc.be.utils.TypeUtils;
57 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
58 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
59 import org.openecomp.sdc.common.api.Constants;
60 import org.openecomp.sdc.common.log.wrappers.Logger;
61 import org.openecomp.sdc.common.util.GeneralUtility;
62 import org.openecomp.sdc.common.util.ValidationUtils;
63 import org.openecomp.sdc.exception.ResponseFormat;
64 import org.springframework.beans.factory.annotation.Autowired;
65 import org.yaml.snakeyaml.DumperOptions;
66 import org.yaml.snakeyaml.Yaml;
67
68 import java.util.*;
69 import java.util.function.Function;
70
71 import static java.util.stream.Collectors.*;
72 import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
73
74 @Getter
75 @Setter
76 @org.springframework.stereotype.Component
77 public class ServiceImportParseLogic {
78
79     private static final String INITIAL_VERSION = "0.1";
80     private static final String CREATE_RESOURCE = "Create Resource";
81     private static final String IN_RESOURCE = "  in resource {} ";
82     private static final String COMPONENT_INSTANCE_WITH_NAME = "component instance with name ";
83     private static final String COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE = "component instance with name {}  in resource {} ";
84     private static final String CERTIFICATION_ON_IMPORT = "certification on import";
85     private static final String VALIDATE_DERIVED_BEFORE_UPDATE = "validate derived before update";
86     private static final String PLACE_HOLDER_RESOURCE_TYPES = "validForResourceTypes";
87     private static final String CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES = "Create Resource - validateCapabilityTypesCreate";
88     private static final String CATEGORY_IS_EMPTY = "Resource category is empty";
89
90
91     @Autowired
92     private ServiceBusinessLogic serviceBusinessLogic;
93     public ServiceBusinessLogic getServiceBusinessLogic() {
94         return serviceBusinessLogic;
95     }
96
97     public void setServiceBusinessLogic(
98             ServiceBusinessLogic serviceBusinessLogic) {
99         this.serviceBusinessLogic = serviceBusinessLogic;
100     }
101
102     @Autowired
103     protected ComponentsUtils componentsUtils;
104     @Autowired
105     protected ToscaOperationFacade toscaOperationFacade;
106     @Autowired
107     private LifecycleBusinessLogic lifecycleBusinessLogic;
108     @Autowired
109     private InputsBusinessLogic inputsBusinessLogic;
110     @Autowired
111     private ResourceImportManager resourceImportManager;
112     @Autowired
113     private IInterfaceLifecycleOperation interfaceTypeOperation = null;
114     private static final Logger log = Logger.getLogger(ServiceImportParseLogic.class);
115
116     @Autowired
117     private ICapabilityTypeOperation capabilityTypeOperation = null;
118
119     public ICapabilityTypeOperation getCapabilityTypeOperation() {
120         return capabilityTypeOperation;
121     }
122
123     public void setCapabilityTypeOperation(ICapabilityTypeOperation capabilityTypeOperation) {
124         this.capabilityTypeOperation = capabilityTypeOperation;
125     }
126
127     public Either<Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandle(
128             Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo, Service oldResource) {
129
130         Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = new HashMap<>();
131         Either<Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> nodeTypesArtifactsToHandleRes
132                 = Either.left(nodeTypesArtifactsToHandle);
133
134         try {
135             Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts = CsarUtils.extractVfcsArtifactsFromCsar(csarInfo.getCsar());
136             Map<String, ImmutablePair<String, String>> extractedVfcToscaNames =
137                     extractVfcToscaNames(nodeTypesInfo, oldResource.getName(), csarInfo);
138             log.debug("Going to fetch node types for resource with name {} during import csar with UUID {}. ",
139                     oldResource.getName(), csarInfo.getCsarUUID());
140             extractedVfcToscaNames.forEach((namespace, vfcToscaNames) -> findAddNodeTypeArtifactsToHandle(csarInfo, nodeTypesArtifactsToHandle, oldResource,
141                     extractedVfcsArtifacts,
142                     namespace, vfcToscaNames));
143         } catch (Exception e) {
144             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
145             nodeTypesArtifactsToHandleRes = Either.right(responseFormat);
146             log.debug("Exception occured when findNodeTypesUpdatedArtifacts, error is:{}", e.getMessage(), e);
147         }
148         return nodeTypesArtifactsToHandleRes;
149     }
150
151     private Map<String, ImmutablePair<String, String>> extractVfcToscaNames(Map<String, NodeTypeInfo> nodeTypesInfo,
152                                                                             String vfResourceName, CsarInfo csarInfo) {
153         Map<String, ImmutablePair<String, String>> vfcToscaNames = new HashMap<>();
154
155         Map<String, Object> nodes = extractAllNodes(nodeTypesInfo, csarInfo);
156         if (!nodes.isEmpty()) {
157             Iterator<Map.Entry<String, Object>> nodesNameEntry = nodes.entrySet().iterator();
158             while (nodesNameEntry.hasNext()) {
159                 Map.Entry<String, Object> nodeType = nodesNameEntry.next();
160                 ImmutablePair<String, String> toscaResourceName = buildNestedToscaResourceName(
161                         ResourceTypeEnum.VFC.name(), vfResourceName, nodeType.getKey());
162                 vfcToscaNames.put(nodeType.getKey(), toscaResourceName);
163             }
164         }
165         for (NodeTypeInfo cvfc : nodeTypesInfo.values()) {
166             vfcToscaNames.put(cvfc.getType(),
167                     buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), vfResourceName, cvfc.getType()));
168         }
169         return vfcToscaNames;
170     }
171
172     public String buildNodeTypeYaml(Map.Entry<String, Object> nodeNameValue, Map<String, Object> mapToConvert,
173                                      String nodeResourceType, CsarInfo csarInfo) {
174         // We need to create a Yaml from each node_types in order to create
175         // resource from each node type using import normative flow.
176         DumperOptions options = new DumperOptions();
177         options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
178         Yaml yaml = new Yaml(options);
179
180         Map<String, Object> node = new HashMap<>();
181         node.put(buildNestedToscaResourceName(nodeResourceType, csarInfo.getVfResourceName(), nodeNameValue.getKey())
182                 .getLeft(), nodeNameValue.getValue());
183         mapToConvert.put(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName(), node);
184
185         return yaml.dumpAsMap(mapToConvert);
186     }
187
188     ImmutablePair<String, String> buildNestedToscaResourceName(String nodeResourceType, String vfResourceName,
189                                                                String nodeTypeFullName) {
190         String actualType;
191         String actualVfName;
192         if (ResourceTypeEnum.CVFC.name().equals(nodeResourceType)) {
193             actualVfName = vfResourceName + ResourceTypeEnum.CVFC.name();
194             actualType = ResourceTypeEnum.VFC.name();
195         } else {
196             actualVfName = vfResourceName;
197             actualType = nodeResourceType;
198         }
199         String nameWithouNamespacePrefix;
200         try {
201             StringBuilder toscaResourceName = new StringBuilder(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
202             if (!nodeTypeFullName.contains(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX)){
203                 nameWithouNamespacePrefix = nodeTypeFullName;
204             } else {
205                 nameWithouNamespacePrefix = nodeTypeFullName
206                         .substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
207             }
208             String[] findTypes = nameWithouNamespacePrefix.split("\\.");
209             String resourceType = findTypes[0];
210             String actualName = nameWithouNamespacePrefix.substring(resourceType.length());
211
212             if (actualName.startsWith(Constants.ABSTRACT)) {
213                 toscaResourceName.append(resourceType.toLowerCase()).append('.')
214                         .append(ValidationUtils.convertToSystemName(actualVfName));
215             } else {
216                 toscaResourceName.append(actualType.toLowerCase()).append('.').append(ValidationUtils.convertToSystemName(actualVfName));
217                 //toscaResourceName.append(actualType.toLowerCase());
218             }
219             StringBuilder previousToscaResourceName = new StringBuilder(toscaResourceName);
220             return new ImmutablePair<>(toscaResourceName.append(actualName.toLowerCase()).toString(),
221                     previousToscaResourceName
222                             .append(actualName.substring(actualName.split("\\.")[1].length() + 1).toLowerCase())
223                             .toString());
224         } catch (Exception e) {
225             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE);
226             log.debug("Exception occured when buildNestedToscaResourceName, error is:{}", e.getMessage(), e);
227             throw new ComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE, vfResourceName);
228         }
229     }
230
231     private Map<String, Object> extractAllNodes(Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo) {
232         Map<String, Object> nodes = new HashMap<>();
233         for (NodeTypeInfo nodeTypeInfo : nodeTypesInfo.values()) {
234             extractNodeTypes(nodes, nodeTypeInfo.getMappedToscaTemplate());
235         }
236         extractNodeTypes(nodes, csarInfo.getMappedToscaMainTemplate());
237         return nodes;
238     }
239
240     private void extractNodeTypes(Map<String, Object> nodes, Map<String, Object> mappedToscaTemplate) {
241         Either<Map<String, Object>, ImportUtils.ResultStatusEnum> eitherNodeTypes = ImportUtils
242                 .findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES);
243         if (eitherNodeTypes.isLeft()) {
244             nodes.putAll(eitherNodeTypes.left().value());
245         }
246     }
247
248     protected void findAddNodeTypeArtifactsToHandle(CsarInfo csarInfo, Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
249                                                   Service resource, Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts, String namespace, ImmutablePair<String, String> vfcToscaNames){
250
251         EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> curNodeTypeArtifactsToHandle = null;
252         log.debug("Going to fetch node type with tosca name {}. ", vfcToscaNames.getLeft());
253         Resource curNodeType = findVfcResource(csarInfo, resource, vfcToscaNames.getLeft(), vfcToscaNames.getRight(), null);
254         if (!MapUtils.isEmpty(extractedVfcsArtifacts)) {
255             List<ArtifactDefinition> currArtifacts = new ArrayList<>();
256             if (extractedVfcsArtifacts.containsKey(namespace)) {
257                 handleAndAddExtractedVfcsArtifacts(currArtifacts, extractedVfcsArtifacts.get(namespace));
258             }
259             curNodeTypeArtifactsToHandle = findNodeTypeArtifactsToHandle(curNodeType, currArtifacts);
260         } else if (curNodeType != null) {
261             // delete all artifacts if have not received artifacts from
262             // csar
263             try {
264                 curNodeTypeArtifactsToHandle = new EnumMap<>(ArtifactsBusinessLogic.ArtifactOperationEnum.class);
265                 List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
266                 // delete all informational artifacts
267                 artifactsToDelete.addAll(curNodeType.getArtifacts().values().stream()
268                     .filter(a -> a.getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
269                     .collect(toList()));
270                 // delete all deployment artifacts
271                 artifactsToDelete.addAll(curNodeType.getDeploymentArtifacts().values());
272                 if (!artifactsToDelete.isEmpty()) {
273                     curNodeTypeArtifactsToHandle
274                         .put(ArtifactsBusinessLogic.ArtifactOperationEnum.DELETE, artifactsToDelete);
275                 }
276             } catch (Exception e) {
277                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE);
278                 log.debug("Exception occured when findAddNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
279                 throw new ComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE, vfcToscaNames.getLeft());
280             }
281         }
282         if (MapUtils.isNotEmpty(curNodeTypeArtifactsToHandle)) {
283             nodeTypesArtifactsToHandle.put(namespace, curNodeTypeArtifactsToHandle);
284         }
285     }
286
287     protected void handleAndAddExtractedVfcsArtifacts(List<ArtifactDefinition> vfcArtifacts,
288                                                     List<ArtifactDefinition> artifactsToAdd) {
289         List<String> vfcArtifactNames = vfcArtifacts.stream().map(ArtifactDataDefinition::getArtifactName)
290                 .collect(toList());
291         artifactsToAdd.stream().forEach(a -> {
292             if (!vfcArtifactNames.contains(a.getArtifactName())) {
293                 vfcArtifacts.add(a);
294             } else {
295                 log.debug("Can't upload two artifact with the same name {}. ", a.getArtifactName());
296             }
297         });
298     }
299
300     protected Resource findVfcResource(CsarInfo csarInfo, Service resource, String currVfcToscaName, String previousVfcToscaName, StorageOperationStatus status) {
301         if (status != null && status != StorageOperationStatus.NOT_FOUND) {
302             log.debug("Error occured during fetching node type with tosca name {}, error: {}", currVfcToscaName, status);
303             throw new ComponentException(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID());
304         } else if (org.apache.commons.lang.StringUtils.isNotEmpty(currVfcToscaName)) {
305             return (Resource)toscaOperationFacade.getLatestByToscaResourceName(currVfcToscaName)
306                     .left()
307                     .on(st -> findVfcResource(csarInfo, resource, previousVfcToscaName, null, st));
308         }
309         return null;
310     }
311
312     protected EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> findNodeTypeArtifactsToHandle(
313             Resource curNodeType, List<ArtifactDefinition> extractedArtifacts) {
314
315         EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null;
316         try {
317             List<ArtifactDefinition> artifactsToUpload = new ArrayList<>(extractedArtifacts);
318             List<ArtifactDefinition> artifactsToUpdate = new ArrayList<>();
319             List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
320             processExistingNodeTypeArtifacts(extractedArtifacts, artifactsToUpload, artifactsToUpdate, artifactsToDelete,
321                     collectExistingArtifacts(curNodeType));
322             nodeTypeArtifactsToHandle = putFoundArtifacts(artifactsToUpload, artifactsToUpdate, artifactsToDelete);
323         } catch (Exception e) {
324             log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
325             throw new ComponentException(ActionStatus.GENERAL_ERROR);
326         }
327         return nodeTypeArtifactsToHandle;
328     }
329
330     protected Map<String, ArtifactDefinition> collectExistingArtifacts(Resource curNodeType) {
331         Map<String, ArtifactDefinition> existingArtifacts = new HashMap<>();
332         if (curNodeType == null) {
333             return existingArtifacts;
334         }
335         if (MapUtils.isNotEmpty(curNodeType.getDeploymentArtifacts())) {
336             existingArtifacts.putAll(curNodeType.getDeploymentArtifacts());
337         }
338         if (MapUtils.isNotEmpty(curNodeType.getArtifacts())) {
339             existingArtifacts
340                     .putAll(curNodeType.getArtifacts().entrySet()
341                             .stream()
342                             .filter(e -> e.getValue().getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
343                             .collect(toMap(Map.Entry::getKey, Map.Entry::getValue)));
344         }
345         return existingArtifacts;
346     }
347
348     protected EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> putFoundArtifacts(List<ArtifactDefinition> artifactsToUpload, List<ArtifactDefinition> artifactsToUpdate, List<ArtifactDefinition> artifactsToDelete) {
349         EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null;
350         if (!artifactsToUpload.isEmpty() || !artifactsToUpdate.isEmpty() || !artifactsToDelete.isEmpty()) {
351             nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactsBusinessLogic.ArtifactOperationEnum.class);
352             if (!artifactsToUpload.isEmpty()) {
353                 nodeTypeArtifactsToHandle.put(ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE, artifactsToUpload);
354             }
355             if (!artifactsToUpdate.isEmpty()) {
356                 nodeTypeArtifactsToHandle.put(ArtifactsBusinessLogic.ArtifactOperationEnum.UPDATE, artifactsToUpdate);
357             }
358             if (!artifactsToDelete.isEmpty()) {
359                 nodeTypeArtifactsToHandle.put(ArtifactsBusinessLogic.ArtifactOperationEnum.DELETE, artifactsToDelete);
360             }
361         }
362         return nodeTypeArtifactsToHandle;
363     }
364
365     protected void processExistingNodeTypeArtifacts(List<ArtifactDefinition> extractedArtifacts, List<ArtifactDefinition> artifactsToUpload,
366         List<ArtifactDefinition> artifactsToUpdate, List<ArtifactDefinition> artifactsToDelete,
367         Map<String, ArtifactDefinition> existingArtifacts) {
368         try {
369             if (!existingArtifacts.isEmpty()) {
370                 extractedArtifacts.stream()
371                     .forEach(a -> processNodeTypeArtifact(artifactsToUpload, artifactsToUpdate, existingArtifacts, a));
372                 artifactsToDelete.addAll(existingArtifacts.values());
373             }
374         } catch (Exception e) {
375             log.debug("Exception occured when processExistingNodeTypeArtifacts, error is:{}", e.getMessage(), e);
376             throw new ComponentException(ActionStatus.GENERAL_ERROR);
377         }
378
379     }
380
381     protected void processNodeTypeArtifact(List<ArtifactDefinition> artifactsToUpload, List<ArtifactDefinition> artifactsToUpdate, Map<String, ArtifactDefinition> existingArtifacts, ArtifactDefinition currNewArtifact) {
382         Optional<ArtifactDefinition> foundArtifact = existingArtifacts.values()
383                 .stream()
384                 .filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName()))
385                 .findFirst();
386         if (foundArtifact.isPresent()) {
387             if (foundArtifact.get().getArtifactType().equals(currNewArtifact.getArtifactType())) {
388                 updateFoundArtifact(artifactsToUpdate, currNewArtifact, foundArtifact.get());
389                 existingArtifacts.remove(foundArtifact.get().getArtifactLabel());
390                 artifactsToUpload.remove(currNewArtifact);
391             } else {
392                 log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName());
393                 throw new ComponentException(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR,
394                         currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(),
395                         foundArtifact.get().getArtifactType());
396             }
397         }
398     }
399
400     protected void updateFoundArtifact(List<ArtifactDefinition> artifactsToUpdate, ArtifactDefinition currNewArtifact, ArtifactDefinition foundArtifact) {
401         if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) {
402             foundArtifact.setPayload(currNewArtifact.getPayloadData());
403             foundArtifact.setPayloadData(
404                     Base64.encodeBase64String(currNewArtifact.getPayloadData()));
405             foundArtifact.setArtifactChecksum(GeneralUtility
406                     .calculateMD5Base64EncodedByByteArray(currNewArtifact.getPayloadData()));
407             artifactsToUpdate.add(foundArtifact);
408         }
409     }
410
411     public void addNonMetaCreatedArtifactsToSupportRollback(ArtifactOperationInfo operation,
412                                                              List<ArtifactDefinition> createdArtifacts,
413                                                              Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts) {
414         if (ArtifactsBusinessLogic.ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && createdArtifacts != null
415                 && eitherNonMetaArtifacts.isLeft()) {
416             Either<ArtifactDefinition, Operation> eitherResult = eitherNonMetaArtifacts.left().value();
417             if (eitherResult.isLeft()) {
418                 createdArtifacts.add(eitherResult.left().value());
419             }
420         }
421     }
422
423     public boolean isArtifactDeletionRequired(String artifactId, byte[] artifactFileBytes, boolean isFromCsar) {
424         return !org.apache.commons.lang.StringUtils.isEmpty(artifactId) && artifactFileBytes == null && isFromCsar;
425     }
426
427     public void fillGroupsFinalFields(List<GroupDefinition> groupsAsList) {
428         groupsAsList.forEach(groupDefinition -> {
429             groupDefinition.setInvariantName(groupDefinition.getName());
430             groupDefinition.setCreatedFrom(CreatedFrom.CSAR);
431         });
432     }
433
434     public String getComponentTypeForResponse(Component component) {
435         String componentTypeForResponse = "SERVICE";
436         if (component instanceof Resource) {
437             componentTypeForResponse = ((Resource) component).getResourceType().name();
438         }
439         return componentTypeForResponse;
440     }
441
442     protected boolean isfillGroupMemebersRecursivlyStopCondition(String groupName, Map<String, GroupDefinition> allGroups,
443                                                                Set<String> allGroupMembers) {
444
445         boolean stop = false;
446         // In Case Not Group Stop
447         if (!allGroups.containsKey(groupName)) {
448             stop = true;
449         }
450         // In Case Group Has no members stop
451         if (!stop) {
452             GroupDefinition groupDefinition = allGroups.get(groupName);
453             stop = MapUtils.isEmpty(groupDefinition.getMembers());
454
455         }
456         // In Case all group members already contained stop
457         if (!stop) {
458             final Set<String> allMembers = allGroups.get(groupName).getMembers().keySet();
459             Set<String> membersOfTypeGroup = allMembers.stream().
460                     // Filter In Only Group members
461                             filter(allGroups::containsKey).
462                     // Collect
463                             collect(toSet());
464             stop = allGroupMembers.containsAll(membersOfTypeGroup);
465         }
466         return stop;
467     }
468
469     public Resource buildValidComplexVfc(Resource resource, CsarInfo csarInfo, String nodeName,
470                                           Map<String, NodeTypeInfo> nodesInfo) {
471
472         Resource complexVfc = buildComplexVfcMetadata(resource, csarInfo, nodeName, nodesInfo);
473         log.debug("************* Going to validate complex VFC from yaml {}", complexVfc.getName());
474         csarInfo.addNodeToQueue(nodeName);
475         return validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(),
476                 AuditingActionEnum.IMPORT_RESOURCE, true, csarInfo);
477     }
478
479     public Resource validateResourceBeforeCreate(Resource resource, User user, AuditingActionEnum actionEnum, boolean inTransaction, CsarInfo csarInfo) {
480
481         validateResourceFieldsBeforeCreate(user, resource, actionEnum, inTransaction);
482         validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), resource, actionEnum, inTransaction);
483         validateLifecycleTypesCreate(user, resource, actionEnum);
484         validateResourceType(user, resource, actionEnum);
485         resource.setCreatorUserId(user.getUserId());
486         resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
487         resource.setContactId(resource.getContactId().toLowerCase());
488         if (org.apache.commons.lang.StringUtils.isEmpty(resource.getToscaResourceName()) && !ModelConverter.isAtomicComponent(resource)) {
489             String resourceSystemName;
490             if (csarInfo != null && org.apache.commons.lang.StringUtils.isNotEmpty(csarInfo.getVfResourceName())) {
491                 resourceSystemName = ValidationUtils.convertToSystemName(csarInfo.getVfResourceName());
492             } else {
493                 resourceSystemName = resource.getSystemName();
494             }
495             resource.setToscaResourceName(CommonBeUtils
496                     .generateToscaResourceName(resource.getResourceType().name().toLowerCase(), resourceSystemName));
497         }
498
499         // Generate invariant UUID - must be here and not in operation since it
500         // should stay constant during clone
501         // TODO
502         String invariantUUID = UniqueIdBuilder.buildInvariantUUID();
503         resource.setInvariantUUID(invariantUUID);
504
505         return resource;
506     }
507
508     protected Either<Boolean, ResponseFormat> validateResourceType(User user, Resource resource,
509                                                                  AuditingActionEnum actionEnum) {
510         Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
511         if (resource.getResourceType() == null) {
512             log.debug("Invalid resource type for resource");
513             ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
514             eitherResult = Either.right(errorResponse);
515             componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
516         }
517         return eitherResult;
518     }
519
520     protected Either<Boolean, ResponseFormat> validateLifecycleTypesCreate(User user, Resource resource,
521                                                                          AuditingActionEnum actionEnum) {
522         Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
523         if (resource.getInterfaces() != null && resource.getInterfaces().size() > 0) {
524             log.debug("validate interface lifecycle Types Exist");
525             Iterator<InterfaceDefinition> intItr = resource.getInterfaces().values().iterator();
526             while (intItr.hasNext() && eitherResult.isLeft()) {
527                 InterfaceDefinition interfaceDefinition = intItr.next();
528                 String intType = interfaceDefinition.getUniqueId();
529                 Either<InterfaceDefinition, StorageOperationStatus> eitherCapTypeFound = interfaceTypeOperation
530                         .getInterface(intType);
531                 if (eitherCapTypeFound.isRight()) {
532                     if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
533                         BeEcompErrorManager.getInstance().logBeGraphObjectMissingError(
534                                 "Create Resource - validateLifecycleTypesCreate", "Interface", intType);
535                         log.debug("Lifecycle Type: {} is required by resource: {} but does not exist in the DB",
536                                 intType, resource.getName());
537                         BeEcompErrorManager.getInstance()
538                                 .logBeDaoSystemError("Create Resource - validateLifecycleTypesCreate");
539                         log.debug("request to data model failed with error: {}",
540                                 eitherCapTypeFound.right().value().name());
541                     }
542                     ResponseFormat errorResponse = componentsUtils
543                             .getResponseFormat(ActionStatus.MISSING_LIFECYCLE_TYPE, intType);
544                     eitherResult = Either.right(errorResponse);
545                     componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
546                 }
547             }
548         }
549         return eitherResult;
550     }
551
552     public Either<Boolean, ResponseFormat> validateCapabilityTypesCreate(User user,
553                                                                           ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum,
554                                                                           boolean inTransaction) {
555
556         Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
557         if (resource.getCapabilities() != null && resource.getCapabilities().size() > 0) {
558             log.debug("validate capability Types Exist - capabilities section");
559
560             for (Map.Entry<String, List<CapabilityDefinition>> typeEntry : resource.getCapabilities().entrySet()) {
561
562                 eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, actionEnum,
563                         eitherResult, typeEntry, inTransaction);
564                 if (eitherResult.isRight()) {
565                     return Either.right(eitherResult.right().value());
566                 }
567             }
568         }
569         if (resource.getRequirements() != null && resource.getRequirements().size() > 0) {
570             log.debug("validate capability Types Exist - requirements section");
571             for (String type : resource.getRequirements().keySet()) {
572                 eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource,
573                         resource.getRequirements().get(type), actionEnum, eitherResult, type, inTransaction);
574                 if (eitherResult.isRight()) {
575                     return Either.right(eitherResult.right().value());
576                 }
577             }
578         }
579         return eitherResult;
580     }
581
582     protected Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user,
583                                                                          ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum,
584                                                                          Either<Boolean, ResponseFormat> eitherResult, Map.Entry<String, List<CapabilityDefinition>> typeEntry,
585                                                                          boolean inTransaction) {
586         Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation
587                 .getCapabilityType(typeEntry.getKey(), inTransaction);
588         if (eitherCapTypeFound.isRight()) {
589             if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
590                 BeEcompErrorManager.getInstance().logBeGraphObjectMissingError(
591                         CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type", typeEntry.getKey());
592                 log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB",
593                         typeEntry.getKey(), resource.getName());
594                 BeEcompErrorManager.getInstance()
595                         .logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
596             }
597             log.debug("Trying to get capability type {} failed with error: {}", typeEntry.getKey(),
598                     eitherCapTypeFound.right().value().name());
599             ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE,
600                     typeEntry.getKey());
601             eitherResult = Either.right(errorResponse);
602             componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
603             return Either.right(eitherResult.right().value());
604         }
605         CapabilityTypeDefinition capabilityTypeDefinition = eitherCapTypeFound.left().value();
606         if (capabilityTypeDefinition.getProperties() != null) {
607             for (CapabilityDefinition capDef : typeEntry.getValue()) {
608                 List<ComponentInstanceProperty> properties = capDef.getProperties();
609                 if (properties == null || properties.isEmpty()) {
610                     properties = new ArrayList<>();
611                     for (Map.Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
612                         ComponentInstanceProperty newProp = new ComponentInstanceProperty(prop.getValue());
613                         properties.add(newProp);
614                     }
615                 } else {
616                     for (Map.Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
617                         PropertyDefinition porpFromDef = prop.getValue();
618                         List<ComponentInstanceProperty> propsToAdd = new ArrayList<>();
619                         for (ComponentInstanceProperty cip : properties) {
620                             if (!cip.getName().equals(porpFromDef.getName())) {
621                                 ComponentInstanceProperty newProp = new ComponentInstanceProperty(porpFromDef);
622                                 propsToAdd.add(newProp);
623                             }
624                         }
625                         if (!propsToAdd.isEmpty()) {
626                             properties.addAll(propsToAdd);
627                         }
628                     }
629                 }
630                 capDef.setProperties(properties);
631             }
632         }
633         return eitherResult;
634     }
635
636     protected Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user,
637                                                                          ICapabilityTypeOperation capabilityTypeOperation, Resource resource, List<?> validationObjects,
638                                                                          AuditingActionEnum actionEnum, Either<Boolean, ResponseFormat> eitherResult, String type,
639                                                                          boolean inTransaction) {
640         try {
641             Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation
642                 .getCapabilityType(type, inTransaction);
643             if (eitherCapTypeFound.isRight()) {
644                 if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
645                     BeEcompErrorManager.getInstance().logBeGraphObjectMissingError(
646                         CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type", type);
647                     log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", type,
648                         resource.getName());
649                     BeEcompErrorManager.getInstance()
650                         .logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
651                 }
652                 log.debug("Trying to get capability type {} failed with error: {}", type,
653                     eitherCapTypeFound.right().value().name());
654                 ResponseFormat errorResponse = null;
655                 if (type != null) {
656                     errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, type);
657                 } else {
658                     errorResponse = componentsUtils.getResponseFormatByElement(ActionStatus.MISSING_CAPABILITY_TYPE,
659                         validationObjects);
660                 }
661                 eitherResult = Either.right(errorResponse);
662                 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
663             }
664
665         } catch (Exception e) {
666             log.debug("Exception occured when validateCapabilityTypeExists, error is:{}", e.getMessage(), e);
667             throw new ComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE, resource.getName());
668         }
669         return eitherResult;
670     }
671
672     protected Either<Boolean, ResponseFormat> validateResourceFieldsBeforeCreate(User user, Resource resource,
673                                                                                AuditingActionEnum actionEnum, boolean inTransaction) {
674         serviceBusinessLogic.validateComponentFieldsBeforeCreate(user, resource, actionEnum);
675         // validate category
676         log.debug("validate category");
677         validateCategory(user, resource, actionEnum, inTransaction);
678         // validate vendor name & release & model number
679         log.debug("validate vendor name");
680         validateVendorName(user, resource, actionEnum);
681         log.debug("validate vendor release");
682         validateVendorReleaseName(user, resource, actionEnum);
683         log.debug("validate resource vendor model number");
684         validateResourceVendorModelNumber(user, resource, actionEnum);
685         // validate cost
686         log.debug("validate cost");
687         validateCost(resource);
688         // validate licenseType
689         log.debug("validate licenseType");
690         validateLicenseType(user, resource, actionEnum);
691         // validate template (derived from)
692         log.debug("validate derived from");
693         if (!ModelConverter.isAtomicComponent(resource) && resource.getResourceType() != ResourceTypeEnum.VF) {
694             resource.setDerivedFrom(null);
695         }
696         validateDerivedFromExist(user, resource, actionEnum);
697         serviceBusinessLogic.checkComponentFieldsForOverrideAttempt(resource);
698         String currentCreatorFullName = resource.getCreatorFullName();
699         if (currentCreatorFullName != null) {
700             log.debug("Resource Creator fullname is automatically set and cannot be updated");
701         }
702
703         String currentLastUpdaterFullName = resource.getLastUpdaterFullName();
704         if (currentLastUpdaterFullName != null) {
705             log.debug("Resource LastUpdater fullname is automatically set and cannot be updated");
706         }
707
708         Long currentLastUpdateDate = resource.getLastUpdateDate();
709         if (currentLastUpdateDate != null) {
710             log.debug("Resource last update date is automatically set and cannot be updated");
711         }
712
713         Boolean currentAbstract = resource.isAbstract();
714         if (currentAbstract != null) {
715             log.debug("Resource abstract is automatically set and cannot be updated");
716         }
717
718         return Either.left(true);
719     }
720
721     protected void validateDerivedFromExist(User user, Resource resource,  AuditingActionEnum actionEnum) {
722         if (resource.getDerivedFrom() == null || resource.getDerivedFrom().isEmpty()) {
723             return;
724         }
725         String templateName = resource.getDerivedFrom().get(0);
726         Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
727                 .validateToscaResourceNameExists(templateName);
728         if (dataModelResponse.isRight()) {
729             StorageOperationStatus storageStatus = dataModelResponse.right().value();
730             BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateDerivedFromExist");
731             log.debug("request to data model failed with error: {}", storageStatus);
732             ResponseFormat responseFormat = componentsUtils
733                     .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), resource);
734             log.trace("audit before sending response");
735             componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
736             throw new ComponentException(componentsUtils.convertFromStorageResponse(storageStatus));
737         } else if (!dataModelResponse.left().value()) {
738             log.info("resource template with name: {}, does not exists", templateName);
739             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
740             componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
741             throw new ComponentException(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
742         }
743     }
744
745     protected void validateLicenseType(User user, Resource resource,
746                                      AuditingActionEnum actionEnum) {
747         log.debug("validate licenseType");
748         String licenseType = resource.getLicenseType();
749         if (licenseType != null) {
750             List<String> licenseTypes = ConfigurationManager.getConfigurationManager().getConfiguration()
751                     .getLicenseTypes();
752             if (!licenseTypes.contains(licenseType)) {
753                 log.debug("License type {} isn't configured", licenseType);
754                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
755                 if (actionEnum != null) {
756                     // In update case, no audit is required
757                     componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
758                 }
759                 throw new ComponentException(ActionStatus.INVALID_CONTENT);
760             }
761         }
762     }
763
764     protected void validateCost(Resource resource) {
765         String cost = resource.getCost();
766         if (cost != null) {
767             if (!ValidationUtils.validateCost(cost)) {
768                 log.debug("resource cost is invalid.");
769                 throw new ComponentException(ActionStatus.INVALID_CONTENT);
770             }
771         }
772     }
773
774     protected void validateResourceVendorModelNumber(User user, Resource resource, AuditingActionEnum actionEnum) {
775         String resourceVendorModelNumber = resource.getResourceVendorModelNumber();
776         if (org.apache.commons.lang.StringUtils.isNotEmpty(resourceVendorModelNumber)) {
777             if (!ValidationUtils.validateResourceVendorModelNumberLength(resourceVendorModelNumber)) {
778                 log.info("resource vendor model number exceeds limit.");
779                 ResponseFormat errorResponse = componentsUtils.getResponseFormat(
780                         ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
781                         "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
782                 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
783                 throw new ComponentException(ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
784                         "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
785             }
786             // resource vendor model number is currently validated as vendor
787             // name
788             if (!ValidationUtils.validateVendorName(resourceVendorModelNumber)) {
789                 log.info("resource vendor model number  is not valid.");
790                 ResponseFormat errorResponse = componentsUtils
791                         .getResponseFormat(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
792                 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
793                 throw new ComponentException(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
794             }
795         }
796     }
797
798     public void validateVendorReleaseName(User user, Resource resource, AuditingActionEnum actionEnum) {
799         String vendorRelease = resource.getVendorRelease();
800         log.debug("validate vendor relese name");
801         if (!ValidationUtils.validateStringNotEmpty(vendorRelease)) {
802             log.info("vendor relese name is missing.");
803             ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_RELEASE);
804             componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
805             throw new ComponentException(ActionStatus.MISSING_VENDOR_RELEASE);
806         }
807
808         validateVendorReleaseName(vendorRelease, user, resource, actionEnum);
809     }
810
811     public void validateVendorReleaseName(String vendorRelease, User user, Resource resource, AuditingActionEnum actionEnum) {
812         if (vendorRelease != null) {
813             if (!ValidationUtils.validateVendorReleaseLength(vendorRelease)) {
814                 log.info("vendor release exceds limit.");
815                 ResponseFormat errorResponse = componentsUtils.getResponseFormat(
816                         ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
817                 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
818                 throw new ComponentException(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
819             }
820
821             if (!ValidationUtils.validateVendorRelease(vendorRelease)) {
822                 log.info("vendor release  is not valid.");
823                 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_RELEASE);
824                 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
825                 throw new ComponentException(ActionStatus.INVALID_VENDOR_RELEASE);
826             }
827         }
828     }
829
830     protected void validateCategory(User user, Resource resource,
831                                   AuditingActionEnum actionEnum, boolean inTransaction) {
832
833         List<CategoryDefinition> categories = resource.getCategories();
834         if (CollectionUtils.isEmpty(categories)) {
835             log.debug(CATEGORY_IS_EMPTY);
836             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY,
837                     ComponentTypeEnum.RESOURCE.getValue());
838             componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
839             throw new ComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY,
840                     ComponentTypeEnum.RESOURCE.getValue());
841         }
842         if (categories.size() > 1) {
843             log.debug("Must be only one category for resource");
844             throw new ComponentException(ActionStatus.COMPONENT_TOO_MUCH_CATEGORIES, ComponentTypeEnum.RESOURCE.getValue());
845         }
846         CategoryDefinition category = categories.get(0);
847         List<SubCategoryDefinition> subcategories = category.getSubcategories();
848         if (CollectionUtils.isEmpty(subcategories)) {
849             log.debug("Missinig subcategory for resource");
850             throw new ComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY);
851         }
852         if (subcategories.size() > 1) {
853             log.debug("Must be only one sub category for resource");
854             throw new ComponentException(ActionStatus.RESOURCE_TOO_MUCH_SUBCATEGORIES);
855         }
856
857         SubCategoryDefinition subcategory = subcategories.get(0);
858
859         if (!ValidationUtils.validateStringNotEmpty(category.getName())) {
860             log.debug(CATEGORY_IS_EMPTY);
861             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY,
862                     ComponentTypeEnum.RESOURCE.getValue());
863             componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
864             throw new ComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY,
865                     ComponentTypeEnum.RESOURCE.getValue());
866         }
867         if (!ValidationUtils.validateStringNotEmpty(subcategory.getName())) {
868             log.debug(CATEGORY_IS_EMPTY);
869             ResponseFormat responseFormat = componentsUtils.getResponseFormat(
870                     ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
871             componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
872             throw new ComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
873         }
874
875         validateCategoryListed(category, subcategory, user, resource, actionEnum, inTransaction);
876     }
877
878     protected void validateCategoryListed(CategoryDefinition category, SubCategoryDefinition subcategory,
879                                         User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
880         ResponseFormat responseFormat;
881         if (category != null && subcategory != null) {
882             try {
883                 log.debug("validating resource category {} against valid categories list", category);
884                 Either<List<CategoryDefinition>, ActionStatus> categories = serviceBusinessLogic.elementDao
885                     .getAllCategories(NodeTypeEnum.ResourceNewCategory, inTransaction);
886                 if (categories.isRight()) {
887                     log.debug("failed to retrieve resource categories from Titan");
888                     responseFormat = componentsUtils.getResponseFormat(categories.right().value());
889                     componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
890                     throw new ComponentException(categories.right().value());
891                 }
892                 List<CategoryDefinition> categoryList = categories.left().value();
893                 Optional<CategoryDefinition> foundCategory = categoryList.stream()
894                     .filter(cat -> cat.getName().equals(category.getName()))
895                     .findFirst();
896                 if (!foundCategory.isPresent()) {
897                     log.debug(
898                         "Category {} is not part of resource category group. Resource category valid values are {}",
899                         category, categoryList);
900                     failOnInvalidCategory(user, resource, actionEnum);
901                 }
902                 Optional<SubCategoryDefinition> foundSubcategory = foundCategory.get()
903                     .getSubcategories()
904                     .stream()
905                     .filter(subcat -> subcat.getName().equals(subcategory.getName()))
906                     .findFirst();
907                 if (!foundSubcategory.isPresent()) {
908                     log.debug(
909                         "SubCategory {} is not part of resource category group. Resource subcategory valid values are {}",
910                         subcategory, foundCategory.get().getSubcategories());
911                     failOnInvalidCategory(user, resource, actionEnum);
912                 }
913             }catch(Exception e){
914                 log.debug("Exception occured when validateCategoryListed, error is:{}", e.getMessage(), e);
915                 throw new ComponentException(ActionStatus.GENERAL_ERROR);
916             }
917         }
918     }
919
920     protected void failOnInvalidCategory(User user, Resource resource, AuditingActionEnum actionEnum) {
921         ResponseFormat responseFormat;
922         responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY,
923                 ComponentTypeEnum.RESOURCE.getValue());
924         componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
925         throw new ComponentException(ActionStatus.COMPONENT_INVALID_CATEGORY,
926                 ComponentTypeEnum.RESOURCE.getValue());
927     }
928
929     protected void validateVendorName(User user, Resource resource,
930                                     AuditingActionEnum actionEnum) {
931         String vendorName = resource.getVendorName();
932         if (!ValidationUtils.validateStringNotEmpty(vendorName)) {
933             log.info("vendor name is missing.");
934             ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_NAME);
935             componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
936             throw new ComponentException(ActionStatus.MISSING_VENDOR_NAME);
937         }
938         validateVendorName(vendorName, user, resource, actionEnum);
939     }
940
941     protected void validateVendorName(String vendorName, User user, Resource resource,
942                                     AuditingActionEnum actionEnum) {
943         if (vendorName != null) {
944             if (!ValidationUtils.validateVendorNameLength(vendorName)) {
945                 log.info("vendor name exceds limit.");
946                 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT,
947                         "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
948                 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
949                 throw new ComponentException(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT,
950                         "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
951             }
952
953             if (!ValidationUtils.validateVendorName(vendorName)) {
954                 log.info("vendor name  is not valid.");
955                 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_NAME);
956                 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
957                 throw new ComponentException(ActionStatus.INVALID_VENDOR_NAME);
958             }
959         }
960     }
961
962     private Resource buildComplexVfcMetadata(Resource resourceVf, CsarInfo csarInfo, String nodeName,
963                                              Map<String, NodeTypeInfo> nodesInfo) {
964         Resource cvfc = new Resource();
965         NodeTypeInfo nodeTypeInfo = nodesInfo.get(nodeName);
966         cvfc.setName(buildCvfcName(csarInfo.getVfResourceName(), nodeName));
967         cvfc.setNormalizedName(ValidationUtils.normaliseComponentName(cvfc.getName()));
968         cvfc.setSystemName(ValidationUtils.convertToSystemName(cvfc.getName()));
969         cvfc.setResourceType(ResourceTypeEnum.VF);
970         cvfc.setAbstract(true);
971         cvfc.setDerivedFrom(nodeTypeInfo.getDerivedFrom());
972         cvfc.setDescription(ImportUtils.Constants.CVFC_DESCRIPTION);
973         cvfc.setIcon(ImportUtils.Constants.DEFAULT_ICON);
974         cvfc.setContactId(csarInfo.getModifier().getUserId());
975         cvfc.setCreatorUserId(csarInfo.getModifier().getUserId());
976         cvfc.setVendorName(resourceVf.getVendorName());
977         cvfc.setVendorRelease(resourceVf.getVendorRelease());
978         cvfc.setResourceVendorModelNumber(resourceVf.getResourceVendorModelNumber());
979         cvfc.setToscaResourceName(
980                 buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), csarInfo.getVfResourceName(), nodeName)
981                         .getLeft());
982         cvfc.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID());
983
984         List<String> tags = new ArrayList<>();
985         tags.add(cvfc.getName());
986         cvfc.setTags(tags);
987
988         CategoryDefinition category = new CategoryDefinition();
989         category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
990         SubCategoryDefinition subCategory = new SubCategoryDefinition();
991         subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
992         category.addSubCategory(subCategory);
993         List<CategoryDefinition> categories = new ArrayList<>();
994         categories.add(category);
995         cvfc.setCategories(categories);
996
997         cvfc.setVersion(ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION);
998         cvfc.setLifecycleState(ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT);
999         cvfc.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION);
1000
1001         return cvfc;
1002     }
1003
1004     private String buildCvfcName(String resourceVfName, String nodeName) {
1005         String nameWithouNamespacePrefix = nodeName
1006                 .substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1007         String[] findTypes = nameWithouNamespacePrefix.split("\\.");
1008         String resourceType = findTypes[0];
1009         String resourceName = resourceVfName + "-" + nameWithouNamespacePrefix.substring(resourceType.length() + 1);
1010         return addCvfcSuffixToResourceName(resourceName);
1011     }
1012
1013     private String addCvfcSuffixToResourceName(String resourceName) {
1014         return resourceName + "VF";
1015     }
1016
1017     public UploadResourceInfo fillResourceMetadata(String yamlName, Resource resourceVf,
1018                                                     String nodeName, User user) {
1019         UploadResourceInfo resourceMetaData = new UploadResourceInfo();
1020
1021         // validate nodetype name prefix
1022         if (!nodeName.startsWith(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX)) {
1023             log.debug("invalid nodeName:{} does not start with {}.", nodeName,
1024                     Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
1025             throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE,
1026                     yamlName, resourceMetaData.getName(), nodeName);
1027         }
1028
1029         String actualName = this.getNodeTypeActualName(nodeName);
1030         String namePrefix = nodeName.replace(actualName, "");
1031         String resourceType = namePrefix.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1032
1033         // if we import from csar, the node_type name can be
1034         // org.openecomp.resource.abstract.node_name - in this case we always
1035         // create a vfc
1036         if (resourceType.equals(Constants.ABSTRACT)) {
1037             resourceType = ResourceTypeEnum.VFC.name().toLowerCase();
1038         }
1039         // validating type
1040         if (!ResourceTypeEnum.containsName(resourceType.toUpperCase())) {
1041             log.debug("invalid resourceType:{} the type is not one of the valide types:{}.", resourceType.toUpperCase(),
1042                     ResourceTypeEnum.values());
1043             throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE,
1044                     yamlName, resourceMetaData.getName(), nodeName);
1045         }
1046
1047         // Setting name
1048         resourceMetaData.setName(resourceVf.getSystemName() + actualName);
1049
1050         // Setting type from name
1051         String type = resourceType.toUpperCase();
1052         resourceMetaData.setResourceType(type);
1053
1054         resourceMetaData.setDescription(ImportUtils.Constants.INNER_VFC_DESCRIPTION);
1055         resourceMetaData.setIcon(ImportUtils.Constants.DEFAULT_ICON);
1056         resourceMetaData.setContactId(user.getUserId());
1057         resourceMetaData.setVendorName(resourceVf.getVendorName());
1058         resourceMetaData.setVendorRelease(resourceVf.getVendorRelease());
1059
1060         // Setting tag
1061         List<String> tags = new ArrayList<>();
1062         tags.add(resourceMetaData.getName());
1063         resourceMetaData.setTags(tags);
1064
1065         // Setting category
1066         CategoryDefinition category = new CategoryDefinition();
1067         category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
1068         SubCategoryDefinition subCategory = new SubCategoryDefinition();
1069         subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
1070         category.addSubCategory(subCategory);
1071         List<CategoryDefinition> categories = new ArrayList<>();
1072         categories.add(category);
1073         resourceMetaData.setCategories(categories);
1074
1075         return resourceMetaData;
1076     }
1077
1078     protected String getNodeTypeActualName(String fullName) {
1079         String nameWithouNamespacePrefix = fullName
1080                 .substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1081         String[] findTypes = nameWithouNamespacePrefix.split("\\.");
1082         String resourceType = findTypes[0];
1083         return nameWithouNamespacePrefix.substring(resourceType.length());
1084     }
1085
1086     public void addInput(Map<String, InputDefinition> currPropertiesMap, InputDefinition prop) {
1087         String propName = prop.getName();
1088         if (!currPropertiesMap.containsKey(propName)) {
1089             currPropertiesMap.put(propName, prop);
1090         }
1091     }
1092
1093     public Either<RequirementDefinition, ResponseFormat> findAviableRequiremen(String regName, String yamlName,
1094                                                                                 UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance,
1095                                                                                 String capName) {
1096         Map<String, List<RequirementDefinition>> comInstRegDefMap = currentCompInstance.getRequirements();
1097         List<RequirementDefinition> list = comInstRegDefMap.get(capName);
1098         RequirementDefinition validRegDef = null;
1099         if (list == null) {
1100             for (Map.Entry<String, List<RequirementDefinition>> entry : comInstRegDefMap.entrySet()) {
1101                 for (RequirementDefinition reqDef : entry.getValue()) {
1102                     if (reqDef.getName().equals(regName)) {
1103                         if (reqDef.getMaxOccurrences() != null
1104                                 && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
1105                             String leftOccurrences = reqDef.getLeftOccurrences();
1106                             if (leftOccurrences == null) {
1107                                 leftOccurrences = reqDef.getMaxOccurrences();
1108                             }
1109                             int left = Integer.parseInt(leftOccurrences);
1110                             if (left > 0) {
1111                                 --left;
1112                                 reqDef.setLeftOccurrences(String.valueOf(left));
1113                                 validRegDef = reqDef;
1114                                 break;
1115                             } else {
1116                                 continue;
1117                             }
1118                         } else {
1119                             validRegDef = reqDef;
1120                             break;
1121                         }
1122
1123                     }
1124                 }
1125                 if (validRegDef != null) {
1126                     break;
1127                 }
1128             }
1129         } else {
1130             for (RequirementDefinition reqDef : list) {
1131                 if (reqDef.getName().equals(regName)) {
1132                     if (reqDef.getMaxOccurrences() != null
1133                             && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
1134                         String leftOccurrences = reqDef.getLeftOccurrences();
1135                         if (leftOccurrences == null) {
1136                             leftOccurrences = reqDef.getMaxOccurrences();
1137                         }
1138                         int left = Integer.parseInt(leftOccurrences);
1139                         if (left > 0) {
1140                             --left;
1141                             reqDef.setLeftOccurrences(String.valueOf(left));
1142                             validRegDef = reqDef;
1143                             break;
1144                         } else {
1145                             continue;
1146                         }
1147                     } else {
1148                         validRegDef = reqDef;
1149                         break;
1150                     }
1151                 }
1152             }
1153         }
1154         if (validRegDef == null) {
1155             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE,
1156                     yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
1157             return Either.right(responseFormat);
1158         }
1159         return Either.left(validRegDef);
1160     }
1161
1162     public CapabilityDefinition findAvailableCapabilityByTypeOrName(RequirementDefinition validReq,
1163                                                                      ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
1164         try {
1165             if (null == uploadReqInfo.getCapabilityName()
1166                 || validReq.getCapability().equals(uploadReqInfo.getCapabilityName())) {
1167                 // get by capability type
1168                 return findAvailableCapability(validReq, currentCapCompInstance);
1169             }
1170             return findAvailableCapability(validReq, currentCapCompInstance, uploadReqInfo);
1171         }catch (Exception e){
1172             log.debug("Exception occured when findAvailableCapabilityByTypeOrName, error is:{}", e.getMessage(), e);
1173             throw new ComponentException(ActionStatus.GENERAL_ERROR);
1174         }
1175     }
1176
1177     protected CapabilityDefinition findAvailableCapability(RequirementDefinition validReq, ComponentInstance instance) {
1178         Map<String, List<CapabilityDefinition>> capMap = instance.getCapabilities();
1179         if (capMap.containsKey(validReq.getCapability())) {
1180             List<CapabilityDefinition> capList = capMap.get(validReq.getCapability());
1181
1182             for (CapabilityDefinition cap : capList) {
1183                 if (isBoundedByOccurrences(cap)) {
1184                     String leftOccurrences = cap.getLeftOccurrences() != null ?
1185                             cap.getLeftOccurrences() : cap.getMaxOccurrences();
1186                     int left = Integer.parseInt(leftOccurrences);
1187                     if (left > 0) {
1188                         --left;
1189                         cap.setLeftOccurrences(String.valueOf(left));
1190                         return cap;
1191                     }
1192                 } else {
1193                     return cap;
1194                 }
1195             }
1196         }
1197         return null;
1198     }
1199
1200     protected CapabilityDefinition findAvailableCapability(RequirementDefinition validReq,
1201                                                          ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
1202         CapabilityDefinition cap = null;
1203         Map<String, List<CapabilityDefinition>> capMap = currentCapCompInstance.getCapabilities();
1204         if (!capMap.containsKey(validReq.getCapability())) {
1205             return null;
1206         }
1207         Optional<CapabilityDefinition> capByName = capMap.get(validReq.getCapability()).stream()
1208                 .filter(p -> p.getName().equals(uploadReqInfo.getCapabilityName())).findAny();
1209         if (!capByName.isPresent()) {
1210             return null;
1211         }
1212         cap = capByName.get();
1213
1214         if (isBoundedByOccurrences(cap)) {
1215             String leftOccurrences = cap.getLeftOccurrences();
1216             int left = Integer.parseInt(leftOccurrences);
1217             if (left > 0) {
1218                 --left;
1219                 cap.setLeftOccurrences(String.valueOf(left));
1220
1221             }
1222
1223         }
1224         return cap;
1225     }
1226
1227     private boolean isBoundedByOccurrences(CapabilityDefinition cap) {
1228         return cap.getMaxOccurrences() != null && !cap.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES);
1229     }
1230
1231     public ComponentParametersView getComponentFilterAfterCreateRelations() {
1232         ComponentParametersView parametersView = new ComponentParametersView();
1233         parametersView.disableAll();
1234         parametersView.setIgnoreComponentInstances(false);
1235         parametersView.setIgnoreComponentInstancesProperties(false);
1236         parametersView.setIgnoreCapabilities(false);
1237         parametersView.setIgnoreRequirements(false);
1238         parametersView.setIgnoreGroups(false);
1239         return parametersView;
1240     }
1241
1242     public ComponentParametersView getComponentWithInstancesFilter() {
1243         ComponentParametersView parametersView = new ComponentParametersView();
1244         parametersView.disableAll();
1245         parametersView.setIgnoreComponentInstances(false);
1246         parametersView.setIgnoreInputs(false);
1247         // inputs are read when creating
1248         // property values on instances
1249         parametersView.setIgnoreUsers(false);
1250         return parametersView;
1251     }
1252
1253     protected void addValidComponentInstanceCapabilities(String key, List<UploadCapInfo> capabilities, String resourceId, Map<String, List<CapabilityDefinition>> defaultCapabilities, Map<String, List<CapabilityDefinition>> validCapabilitiesMap){
1254         String capabilityType = capabilities.get(0).getType();
1255         if (defaultCapabilities.containsKey(capabilityType)) {
1256             CapabilityDefinition defaultCapability = getCapability(resourceId, defaultCapabilities, capabilityType);
1257             validateCapabilityProperties(capabilities, resourceId, defaultCapability);
1258             List<CapabilityDefinition> validCapabilityList = new ArrayList<>();
1259             validCapabilityList.add(defaultCapability);
1260             validCapabilitiesMap.put(key, validCapabilityList);
1261         } else {
1262             throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, capabilityType));
1263         }
1264     }
1265
1266     protected CapabilityDefinition getCapability(String resourceId, Map<String, List<CapabilityDefinition>> defaultCapabilities, String capabilityType) {
1267         CapabilityDefinition defaultCapability;
1268         if (isNotEmpty(defaultCapabilities.get(capabilityType).get(0).getProperties())) {
1269             defaultCapability = defaultCapabilities.get(capabilityType).get(0);
1270         } else {
1271             Either<Component, StorageOperationStatus> getFullComponentRes = toscaOperationFacade
1272                     .getToscaFullElement(resourceId);
1273             if (getFullComponentRes.isRight()) {
1274                 log.debug("Failed to get full component {}. Status is {}. ", resourceId,
1275                         getFullComponentRes.right().value());
1276                 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NOT_FOUND,
1277                         resourceId));
1278             }
1279             defaultCapability = getFullComponentRes.left().value().getCapabilities().get(capabilityType).get(0);
1280         }
1281         return defaultCapability;
1282     }
1283
1284     protected void validateCapabilityProperties(List<UploadCapInfo> capabilities, String resourceId, CapabilityDefinition defaultCapability) {
1285         if (CollectionUtils.isEmpty(defaultCapability.getProperties())
1286                 && isNotEmpty(capabilities.get(0).getProperties())) {
1287             log.debug("Failed to validate capability {} of component {}. Property list is empty. ",
1288                     defaultCapability.getName(), resourceId);
1289             log.debug(
1290                     "Failed to update capability property values. Property list of fetched capability {} is empty. ",
1291                     defaultCapability.getName());
1292             throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, resourceId));
1293         } else if (isNotEmpty(capabilities.get(0).getProperties())) {
1294             validateUniquenessUpdateUploadedComponentInstanceCapability(defaultCapability, capabilities.get(0));
1295         }
1296     }
1297
1298     protected void validateUniquenessUpdateUploadedComponentInstanceCapability(
1299             CapabilityDefinition defaultCapability, UploadCapInfo uploadedCapability) {
1300         List<ComponentInstanceProperty> validProperties = new ArrayList<>();
1301         Map<String, PropertyDefinition> defaultProperties = defaultCapability.getProperties().stream()
1302                 .collect(toMap(PropertyDefinition::getName, Function
1303                         .identity()));
1304         List<UploadPropInfo> uploadedProperties = uploadedCapability.getProperties();
1305         for (UploadPropInfo property : uploadedProperties) {
1306             String propertyName = property.getName().toLowerCase();
1307             String propertyType = property.getType();
1308             ComponentInstanceProperty validProperty;
1309             if (defaultProperties.containsKey(propertyName) && propertTypeEqualsTo(defaultProperties, propertyName, propertyType)) {
1310                 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NAME_ALREADY_EXISTS,
1311                         propertyName));
1312             }
1313             validProperty = new ComponentInstanceProperty();
1314             validProperty.setName(propertyName);
1315             if (property.getValue() != null) {
1316                 validProperty.setValue(property.getValue().toString());
1317             }
1318             validProperty.setDescription(property.getDescription());
1319             validProperty.setPassword(property.isPassword());
1320             validProperties.add(validProperty);
1321         }
1322         defaultCapability.setProperties(validProperties);
1323     }
1324
1325     private boolean propertTypeEqualsTo(Map<String, PropertyDefinition> defaultProperties, String propertyName, String propertyType) {
1326         return propertyType != null && !defaultProperties.get(propertyName).getType().equals(propertyType);
1327     }
1328
1329     public void setDeploymentArtifactsPlaceHolder(Component component, User user) {
1330         if(component instanceof Service){
1331             Service service = (Service) component;
1332             Map<String, ArtifactDefinition> artifactMap = service.getDeploymentArtifacts();
1333             if (artifactMap == null) {
1334                 artifactMap = new HashMap<>();
1335             }
1336             service.setDeploymentArtifacts(artifactMap);
1337         }else if(component instanceof Resource){
1338             Resource resource = (Resource) component;
1339             Map<String, ArtifactDefinition> artifactMap = resource.getDeploymentArtifacts();
1340             if (artifactMap == null) {
1341                 artifactMap = new HashMap<>();
1342             }
1343             Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager()
1344                     .getConfiguration().getDeploymentResourceArtifacts();
1345             if (deploymentResourceArtifacts != null) {
1346                 Map<String, ArtifactDefinition> finalArtifactMap = artifactMap;
1347                 deploymentResourceArtifacts.forEach((k, v)->processDeploymentResourceArtifacts(user, resource, finalArtifactMap, k,v));
1348             }
1349             resource.setDeploymentArtifacts(artifactMap);
1350         }
1351
1352     }
1353
1354     protected void processDeploymentResourceArtifacts(User user, Resource resource, Map<String, ArtifactDefinition> artifactMap, String k, Object v) {
1355         boolean shouldCreateArtifact = true;
1356         Map<String, Object> artifactDetails = (Map<String, Object>) v;
1357         Object object = artifactDetails.get(PLACE_HOLDER_RESOURCE_TYPES);
1358         if (object != null) {
1359             List<String> artifactTypes = (List<String>) object;
1360             if (!artifactTypes.contains(resource.getResourceType().name())) {
1361                 return;
1362             }
1363         } else {
1364             log.info("resource types for artifact placeholder {} were not defined. default is all resources",
1365                     k);
1366         }
1367         if (shouldCreateArtifact) {
1368             if (serviceBusinessLogic.artifactsBusinessLogic != null) {
1369                 ArtifactDefinition artifactDefinition = serviceBusinessLogic.artifactsBusinessLogic.createArtifactPlaceHolderInfo(
1370                         resource.getUniqueId(), k, (Map<String, Object>) v,
1371                         user, ArtifactGroupTypeEnum.DEPLOYMENT);
1372                 if (artifactDefinition != null
1373                         && !artifactMap.containsKey(artifactDefinition.getArtifactLabel())) {
1374                     artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
1375                 }
1376             }
1377         }
1378     }
1379
1380     public void mergeOldResourceMetadataWithNew(Resource oldResource, Resource newResource) {
1381
1382         if (newResource.getTags() == null || newResource.getTags().isEmpty()) {
1383             newResource.setTags(oldResource.getTags());
1384         }
1385
1386         if (newResource.getDescription() == null) {
1387             newResource.setDescription(oldResource.getDescription());
1388         }
1389
1390
1391         if (newResource.getContactId() == null) {
1392             newResource.setContactId(oldResource.getContactId());
1393         }
1394
1395         newResource.setCategories(oldResource.getCategories());
1396
1397     }
1398
1399     protected Resource buildComplexVfcMetadata(CsarInfo csarInfo, String nodeName,
1400                                              Map<String, NodeTypeInfo> nodesInfo) {
1401         Resource cvfc = new Resource();
1402         NodeTypeInfo nodeTypeInfo = nodesInfo.get(nodeName);
1403         cvfc.setName(buildCvfcName(csarInfo.getVfResourceName(), nodeName));
1404         cvfc.setNormalizedName(ValidationUtils.normaliseComponentName(cvfc.getName()));
1405         cvfc.setSystemName(ValidationUtils.convertToSystemName(cvfc.getName()));
1406         cvfc.setResourceType(ResourceTypeEnum.VF);
1407         cvfc.setAbstract(true);
1408         cvfc.setDerivedFrom(nodeTypeInfo.getDerivedFrom());
1409         cvfc.setDescription(ImportUtils.Constants.VF_DESCRIPTION);
1410         cvfc.setIcon(ImportUtils.Constants.DEFAULT_ICON);
1411         cvfc.setContactId(csarInfo.getModifier().getUserId());
1412         cvfc.setCreatorUserId(csarInfo.getModifier().getUserId());
1413         cvfc.setVendorName("cmri");
1414         cvfc.setVendorRelease("1.0");
1415         cvfc.setResourceVendorModelNumber("");
1416         cvfc.setToscaResourceName(
1417                 buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), csarInfo.getVfResourceName(), nodeName)
1418                         .getLeft());
1419         cvfc.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID());
1420
1421         List<String> tags = new ArrayList<>();
1422         tags.add(cvfc.getName());
1423         cvfc.setTags(tags);
1424
1425         CategoryDefinition category = new CategoryDefinition();
1426         category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
1427         SubCategoryDefinition subCategory = new SubCategoryDefinition();
1428         subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
1429         category.addSubCategory(subCategory);
1430         List<CategoryDefinition> categories = new ArrayList<>();
1431         categories.add(category);
1432         cvfc.setCategories(categories);
1433
1434         cvfc.setVersion(ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION);
1435         cvfc.setLifecycleState(ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT);
1436         cvfc.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION);
1437
1438         return cvfc;
1439     }
1440
1441     public Boolean validateResourceCreationFromNodeType(Resource resource, User creator) {
1442         validateDerivedFromNotEmpty(creator, resource, AuditingActionEnum.CREATE_RESOURCE);
1443         return true;
1444     }
1445
1446     private void validateDerivedFromNotEmpty(User user, Resource resource, AuditingActionEnum actionEnum) {
1447         log.debug("validate resource derivedFrom field");
1448         if ((resource.getDerivedFrom() == null) || (resource.getDerivedFrom().isEmpty())
1449                 || (resource.getDerivedFrom().get(0)) == null || (resource.getDerivedFrom().get(0).trim().isEmpty())) {
1450             log.info("derived from (template) field is missing for the resource");
1451             ResponseFormat responseFormat = componentsUtils
1452                     .getResponseFormat(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
1453             componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
1454
1455             throw new ComponentException(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
1456         }
1457     }
1458
1459     public Service createInputsOnService(Service service, Map<String, InputDefinition> inputs) {
1460         List<InputDefinition> resourceProperties = service.getInputs();
1461         if (MapUtils.isNotEmpty(inputs)|| isNotEmpty(resourceProperties)) {
1462
1463             Either<List<InputDefinition>, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs,
1464                     service);
1465             if (createInputs.isRight()) {
1466                 throw new ComponentException(createInputs.right().value());
1467             }
1468         } else {
1469             return service;
1470         }
1471         Either<Service, StorageOperationStatus> updatedResource = toscaOperationFacade
1472                 .getToscaElement(service.getUniqueId());
1473         if (updatedResource.isRight()) {
1474             throw new ComponentException(componentsUtils.getResponseFormatByComponent(
1475                     componentsUtils.convertFromStorageResponse(updatedResource.right().value()), service, ComponentTypeEnum.SERVICE));
1476         }
1477         return updatedResource.left().value();
1478     }
1479
1480
1481     public Service createServiceTransaction(Service service, User user, boolean isNormative) {
1482         // validate resource name uniqueness
1483         log.debug("validate resource name");
1484         Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade.validateComponentNameExists(
1485                 service.getName(), null, service.getComponentType());
1486         if (eitherValidation.isRight()) {
1487             log.debug("Failed to validate component name {}. Status is {}. ", service.getName(),
1488                     eitherValidation.right().value());
1489             ResponseFormat errorResponse = componentsUtils
1490                     .getResponseFormat(componentsUtils.convertFromStorageResponse(eitherValidation.right().value()));
1491             throw new ComponentException(errorResponse);
1492         }
1493         if (eitherValidation.left().value()) {
1494             log.debug("resource with name: {}, already exists", service.getName());
1495             ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST,
1496                     ComponentTypeEnum.RESOURCE.getValue(), service.getName());
1497             throw new ComponentException(errorResponse);
1498         }
1499
1500         log.debug("send resource {} to dao for create", service.getName());
1501
1502         createArtifactsPlaceHolderData(service, user);
1503         // enrich object
1504         if (!isNormative) {
1505             log.debug("enrich resource with creator, version and state");
1506             service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
1507             service.setVersion(INITIAL_VERSION);
1508             service.setHighestVersion(true);
1509         }
1510         return toscaOperationFacade.createToscaComponent(service)
1511                 .left()
1512                 .on(r->throwComponentExceptionByResource(r, service));
1513     }
1514
1515     public Service throwComponentExceptionByResource(StorageOperationStatus status, Service service) {
1516         ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent(
1517                 componentsUtils.convertFromStorageResponse(status), service, ComponentTypeEnum.SERVICE);
1518         throw new ComponentException(responseFormat);
1519     }
1520
1521
1522     protected void createArtifactsPlaceHolderData(Service service, User user) {
1523         setInformationalArtifactsPlaceHolder(service, user);
1524         serviceBusinessLogic.setDeploymentArtifactsPlaceHolder(service, user);
1525         serviceBusinessLogic.setToscaArtifactsPlaceHolders(service, user);
1526     }
1527
1528     @SuppressWarnings("unchecked")
1529     protected void setInformationalArtifactsPlaceHolder(Service service, User user) {
1530         Map<String, ArtifactDefinition> artifactMap = service.getArtifacts();
1531         if (artifactMap == null) {
1532             artifactMap = new HashMap<>();
1533         }
1534         String resourceUniqueId = service.getUniqueId();
1535         List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration()
1536                 .getExcludeResourceCategory();
1537         List<String> exludeResourceType = ConfigurationManager.getConfigurationManager().getConfiguration()
1538                 .getExcludeResourceType();
1539         Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager()
1540                 .getConfiguration().getInformationalResourceArtifacts();
1541         List<CategoryDefinition> categories = service.getCategories();
1542         boolean isCreateArtifact = true;
1543         if (exludeResourceCategory != null) {
1544             String category = categories.get(0).getName();
1545             isCreateArtifact = exludeResourceCategory.stream().noneMatch(e->e.equalsIgnoreCase(category));
1546         }
1547
1548         if (informationalResourceArtifacts != null && isCreateArtifact) {
1549             Set<String> keys = informationalResourceArtifacts.keySet();
1550             for (String informationalResourceArtifactName : keys) {
1551                 Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts
1552                         .get(informationalResourceArtifactName);
1553                 ArtifactDefinition artifactDefinition = serviceBusinessLogic.artifactsBusinessLogic.createArtifactPlaceHolderInfo(
1554                         resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user,
1555                         ArtifactGroupTypeEnum.INFORMATIONAL);
1556                 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
1557
1558             }
1559         }
1560         service.setArtifacts(artifactMap);
1561     }
1562
1563     public void rollback(boolean inTransaction, Service service, List<ArtifactDefinition> createdArtifacts, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts) {
1564         if(!inTransaction) {
1565             serviceBusinessLogic.janusGraphDao.rollback();
1566         }
1567         if (isNotEmpty(createdArtifacts) && isNotEmpty(nodeTypesNewCreatedArtifacts)) {
1568             createdArtifacts.addAll(nodeTypesNewCreatedArtifacts);
1569             log.debug("Found {} newly created artifacts to deleted, the component name: {}",createdArtifacts.size(), service.getName());
1570         }
1571     }
1572
1573     public Map<String,Object> getNodeTypesFromTemplate(Map<String, Object> mappedToscaTemplate) {
1574         return ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES)
1575                 .left().orValue(HashMap::new);
1576     }
1577
1578     private Resource nodeForceCertification(Resource resource, User user,
1579                                             LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
1580         return lifecycleBusinessLogic.forceResourceCertification(resource, user, lifecycleChangeInfo, inTransaction,
1581                 needLock);
1582     }
1583
1584     private Resource nodeFullCertification(String uniqueId, User user,
1585                                            LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
1586         Either<Resource, ResponseFormat> resourceResponse = lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFY, lifecycleChangeInfo,
1587                 inTransaction, needLock);
1588         if(resourceResponse.isRight()){
1589             throw new ByResponseFormatComponentException(resourceResponse.right().value());
1590         }
1591         return resourceResponse.left().value();
1592     }
1593
1594     public Either<Boolean, ResponseFormat> validateNestedDerivedFromDuringUpdate(Resource currentResource,
1595                                                                                   Resource updateInfoResource, boolean hasBeenCertified) {
1596
1597         List<String> currentDerivedFrom = currentResource.getDerivedFrom();
1598         List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
1599         if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null
1600                 || updatedDerivedFrom.isEmpty()) {
1601             log.trace("Update normative types");
1602             return Either.left(true);
1603         }
1604
1605         String derivedFromCurrent = currentDerivedFrom.get(0);
1606         String derivedFromUpdated = updatedDerivedFrom.get(0);
1607
1608         if (!derivedFromCurrent.equals(derivedFromUpdated)) {
1609             if (!hasBeenCertified) {
1610                 validateDerivedFromExist(null, updateInfoResource, null);
1611             } else {
1612                 Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null,
1613                         currentResource, updateInfoResource, null);
1614
1615                 if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left().value()) {
1616                     log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
1617                     return validateDerivedFromExtending;
1618                 }
1619             }
1620         }
1621         return Either.left(true);
1622     }
1623
1624     protected Either<Boolean, ResponseFormat> validateDerivedFromExtending(User user, Resource currentResource,
1625                                                                          Resource updateInfoResource, AuditingActionEnum actionEnum) {
1626         String currentTemplateName = currentResource.getDerivedFrom().get(0);
1627         String updatedTemplateName = updateInfoResource.getDerivedFrom().get(0);
1628
1629         Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
1630                 .validateToscaResourceNameExtends(currentTemplateName, updatedTemplateName);
1631         if (dataModelResponse.isRight()) {
1632             StorageOperationStatus storageStatus = dataModelResponse.right().value();
1633             BeEcompErrorManager.getInstance()
1634                     .logBeDaoSystemError("Create/Update Resource - validateDerivingFromExtendingType");
1635             ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
1636                     componentsUtils.convertFromStorageResponse(storageStatus), currentResource);
1637             log.trace("audit before sending response");
1638             componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
1639             return Either.right(responseFormat);
1640         }
1641
1642         if (!dataModelResponse.left().value()) {
1643             log.info("resource template with name {} does not inherit as original {}", updatedTemplateName,
1644                     currentTemplateName);
1645             ResponseFormat responseFormat = componentsUtils
1646                     .getResponseFormat(ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND);
1647             componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
1648
1649             return Either.right(responseFormat);
1650
1651         }
1652         return Either.left(true);
1653     }
1654
1655     public void validateResourceFieldsBeforeUpdate(Resource currentResource, Resource updateInfoResource,
1656                                                     boolean inTransaction, boolean isNested) {
1657         validateFields(currentResource, updateInfoResource, inTransaction, isNested);
1658     }
1659
1660
1661     private void validateFields(Resource currentResource, Resource updateInfoResource, boolean inTransaction, boolean isNested) {
1662         boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentResource.getVersion());
1663         log.debug("validate resource name before update");
1664         validateResourceName(currentResource, updateInfoResource, hasBeenCertified, isNested);
1665         log.debug("validate description before update");
1666         serviceBusinessLogic.componentDescriptionValidator.validateAndCorrectField(null, updateInfoResource, null);
1667         log.debug("validate icon before update");
1668         log.debug("validate tags before update");
1669         serviceBusinessLogic.componentTagsValidator.validateAndCorrectField(null, updateInfoResource, null);
1670         log.debug("validate vendor name before update");
1671         log.debug("validate resource vendor model number before update");
1672         log.debug("validate vendor release before update");
1673         log.debug("validate contact info before update");
1674         serviceBusinessLogic.componentContactIdValidator.validateAndCorrectField(null, updateInfoResource, null);
1675         log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
1676         log.debug("validate category before update");
1677     }
1678
1679
1680     protected void validateResourceName(Resource currentResource, Resource updateInfoResource,
1681                                       boolean hasBeenCertified, boolean isNested) {
1682         String resourceNameUpdated = updateInfoResource.getName();
1683         if (!isResourceNameEquals(currentResource, updateInfoResource)) {
1684             if (isNested || !hasBeenCertified) {
1685                 serviceBusinessLogic.componentNameValidator.validateAndCorrectField(null, updateInfoResource, null);
1686                 currentResource.setName(resourceNameUpdated);
1687                 currentResource.setNormalizedName(ValidationUtils.normaliseComponentName(resourceNameUpdated));
1688                 currentResource.setSystemName(ValidationUtils.convertToSystemName(resourceNameUpdated));
1689
1690             } else {
1691                 log.info("Resource name: {}, cannot be updated once the resource has been certified once.",
1692                         resourceNameUpdated);
1693                 throw new ComponentException(ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED);
1694             }
1695         }
1696     }
1697
1698     protected boolean isResourceNameEquals(Resource currentResource, Resource updateInfoResource) {
1699         String resourceNameUpdated = updateInfoResource.getName();
1700         String resourceNameCurrent = currentResource.getName();
1701         if (resourceNameCurrent.equals(resourceNameUpdated)) {
1702             return true;
1703         }
1704         return currentResource.getResourceType().equals(ResourceTypeEnum.VF) &&
1705                 resourceNameUpdated.equals(addCvfcSuffixToResourceName(resourceNameCurrent));
1706     }
1707
1708     public Resource prepareResourceForUpdate(Resource oldResource, Resource newResource, User user,
1709                                               boolean inTransaction, boolean needLock) {
1710
1711         if (!ComponentValidationUtils.canWorkOnResource(oldResource, user.getUserId())) {
1712             // checkout
1713             return lifecycleBusinessLogic.changeState(
1714                     oldResource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
1715                     new LifecycleChangeInfoWithAction("update by import"), inTransaction, needLock)
1716                     .left()
1717                     .on(response -> failOnChangeState(response, user, oldResource, newResource));
1718         }
1719         return oldResource;
1720     }
1721
1722     protected Resource failOnChangeState(ResponseFormat response, User user, Resource oldResource, Resource newResource) {
1723         log.info("resource {} cannot be updated. reason={}", oldResource.getUniqueId(),
1724                 response.getFormattedMessage());
1725         componentsUtils.auditResource(response, user, newResource, AuditingActionEnum.IMPORT_RESOURCE,
1726                 ResourceVersionInfo.newBuilder()
1727                         .state(oldResource.getLifecycleState().name())
1728                         .version(oldResource.getVersion())
1729                         .build());
1730         throw new ComponentException(response);
1731     }
1732
1733     public Resource handleResourceGenericType(Resource resource) {
1734         Resource genericResource = serviceBusinessLogic.fetchAndSetDerivedFromGenericType(resource);
1735         if (resource.shouldGenerateInputs()) {
1736             serviceBusinessLogic.generateAndAddInputsFromGenericTypeProperties(resource, genericResource);
1737         }
1738         return genericResource;
1739     }
1740
1741     public Resource createInputsOnResource(Resource resource, Map<String, InputDefinition> inputs) {
1742         List<InputDefinition> resourceProperties = resource.getInputs();
1743         if (MapUtils.isNotEmpty(inputs)|| isNotEmpty(resourceProperties)) {
1744
1745             Either<List<InputDefinition>, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs,
1746                     resource);
1747             if (createInputs.isRight()) {
1748                 throw new ComponentException(createInputs.right().value());
1749             }
1750         } else {
1751             return resource;
1752         }
1753         Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade
1754                 .getToscaElement(resource.getUniqueId());
1755         if (updatedResource.isRight()) {
1756             throw new ComponentException(componentsUtils.getResponseFormatByResource(
1757                     componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource));
1758         }
1759         return updatedResource.left().value();
1760     }
1761
1762     protected void updateOrCreateGroups(Resource resource, Map<String, GroupDefinition> groups) {
1763         List<GroupDefinition> groupsFromResource = resource.getGroups();
1764         List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(groups, new Service());
1765         List<GroupDefinition> groupsToUpdate = new ArrayList<>();
1766         List<GroupDefinition> groupsToDelete = new ArrayList<>();
1767         List<GroupDefinition> groupsToCreate = new ArrayList<>();
1768         if (isNotEmpty(groupsFromResource)) {
1769             addGroupsToCreateOrUpdate(groupsFromResource, groupsAsList, groupsToUpdate, groupsToCreate);
1770             addGroupsToDelete(groupsFromResource, groupsAsList, groupsToDelete);
1771         } else {
1772             groupsToCreate.addAll(groupsAsList);
1773         }
1774         if (isNotEmpty(groupsToCreate)) {
1775             fillGroupsFinalFields(groupsToCreate);
1776             if (isNotEmpty(groupsFromResource)) {
1777                 serviceBusinessLogic.groupBusinessLogic.addGroups(resource,
1778                         groupsToCreate, true)
1779                         .left()
1780                         .on(serviceBusinessLogic::throwComponentException);
1781             } else {
1782                 serviceBusinessLogic.groupBusinessLogic.createGroups(resource,
1783                         groupsToCreate, true)
1784                         .left()
1785                         .on(serviceBusinessLogic::throwComponentException);
1786             }
1787         }
1788         if (isNotEmpty(groupsToDelete)) {
1789             serviceBusinessLogic.groupBusinessLogic.deleteGroups(resource, groupsToDelete)
1790                     .left()
1791                     .on(serviceBusinessLogic::throwComponentException);
1792         }
1793         if (isNotEmpty(groupsToUpdate)) {
1794             serviceBusinessLogic.groupBusinessLogic.updateGroups(resource, groupsToUpdate, true)
1795                     .left()
1796                     .on(serviceBusinessLogic::throwComponentException);
1797         }
1798     }
1799
1800     protected void addGroupsToCreateOrUpdate(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList, List<GroupDefinition> groupsToUpdate, List<GroupDefinition> groupsToCreate) {
1801         for (GroupDefinition group : groupsAsList) {
1802             Optional<GroupDefinition> op = groupsFromResource.stream()
1803                     .filter(p -> p.getInvariantName().equalsIgnoreCase(group.getInvariantName())).findAny();
1804             if (op.isPresent()) {
1805                 GroupDefinition groupToUpdate = op.get();
1806                 groupToUpdate.setMembers(group.getMembers());
1807                 groupToUpdate.setCapabilities(group.getCapabilities());
1808                 groupToUpdate.setProperties(group.getProperties());
1809                 groupsToUpdate.add(groupToUpdate);
1810             } else {
1811                 groupsToCreate.add(group);
1812             }
1813         }
1814     }
1815
1816     protected void addGroupsToDelete(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList, List<GroupDefinition> groupsToDelete) {
1817         for (GroupDefinition group : groupsFromResource) {
1818             Optional<GroupDefinition> op = groupsAsList.stream()
1819                     .filter(p -> p.getName().equalsIgnoreCase(group.getName())).findAny();
1820             if (!op.isPresent() && (group.getArtifacts() == null || group.getArtifacts().isEmpty())) {
1821                 groupsToDelete.add(group);
1822             }
1823         }
1824     }
1825
1826     protected List<GroupDefinition> updateGroupsMembersUsingResource(Map<String, GroupDefinition> groups, Service component) {
1827
1828         List<GroupDefinition> result = new ArrayList<>();
1829         List<ComponentInstance> componentInstances = component.getComponentInstances();
1830
1831         if (groups != null) {
1832             Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies = validateCyclicGroupsDependencies(groups);
1833             if (validateCyclicGroupsDependencies.isRight()) {
1834                 throw new ComponentException(validateCyclicGroupsDependencies.right().value());
1835             }
1836             for (Map.Entry<String, GroupDefinition> entry : groups.entrySet()) {
1837                 String groupName = entry.getKey();
1838                 GroupDefinition groupDefinition = entry.getValue();
1839                 GroupDefinition updatedGroupDefinition = new GroupDefinition(groupDefinition);
1840                 updatedGroupDefinition.setMembers(null);
1841                 Map<String, String> members = groupDefinition.getMembers();
1842                 if (members != null) {
1843                     updateGroupMembers(groups, updatedGroupDefinition, component, componentInstances, groupName, members);
1844                 }
1845                 result.add(updatedGroupDefinition);
1846             }
1847         }
1848         return result;
1849     }
1850
1851     public void updateGroupMembers(Map<String, GroupDefinition> groups, GroupDefinition updatedGroupDefinition, Service component, List<ComponentInstance> componentInstances, String groupName, Map<String, String> members) {
1852         Set<String> compInstancesNames = members.keySet();
1853
1854         if (CollectionUtils.isEmpty(componentInstances)) {
1855             String membersAstString = compInstancesNames.stream().collect(joining(","));
1856             log.debug("The members: {}, in group: {}, cannot be found in component {}. There are no component instances.",
1857                     membersAstString, groupName, component.getNormalizedName());
1858             throw new ComponentException(componentsUtils.getResponseFormat(
1859                     ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName,
1860                     component.getNormalizedName(), getComponentTypeForResponse(component)));
1861         }
1862         // Find all component instances with the member names
1863         Map<String, String> memberNames = componentInstances.stream()
1864                 .collect(toMap(ComponentInstance::getName, ComponentInstance::getUniqueId));
1865         memberNames.putAll(groups.keySet().stream().collect(toMap(g -> g, g -> "")));
1866         Map<String, String> relevantInstances = memberNames.entrySet().stream()
1867                 .filter(n -> compInstancesNames.contains(n.getKey()))
1868                 .collect(toMap(Map.Entry::getKey, Map.Entry::getValue));
1869
1870         if (relevantInstances == null || relevantInstances.size() != compInstancesNames.size()) {
1871
1872             List<String> foundMembers = new ArrayList<>();
1873             if (relevantInstances != null) {
1874                 foundMembers = relevantInstances.keySet().stream().collect(toList());
1875             }
1876             compInstancesNames.removeAll(foundMembers);
1877             String membersAstString = compInstancesNames.stream().collect(joining(","));
1878             log.debug("The members: {}, in group: {}, cannot be found in component: {}", membersAstString,
1879                     groupName, component.getNormalizedName());
1880             throw new ComponentException(componentsUtils.getResponseFormat(
1881                     ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName,
1882                     component.getNormalizedName(), getComponentTypeForResponse(component)));
1883         }
1884         updatedGroupDefinition.setMembers(relevantInstances);
1885     }
1886
1887     public Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies(Map<String, GroupDefinition> allGroups) {
1888
1889         Either<Boolean, ResponseFormat> result = Either.left(true);
1890         try {
1891             Iterator<Map.Entry<String, GroupDefinition>> allGroupsItr = allGroups.entrySet().iterator();
1892             while (allGroupsItr.hasNext() && result.isLeft()) {
1893                 Map.Entry<String, GroupDefinition> groupAEntry = allGroupsItr.next();
1894                 // Fetches a group member A
1895                 String groupAName = groupAEntry.getKey();
1896                 // Finds all group members in group A
1897                 Set<String> allGroupAMembersNames = new HashSet<>();
1898                 fillAllGroupMemebersRecursivly(groupAEntry.getKey(), allGroups, allGroupAMembersNames);
1899                 // If A is a group member of itself found cyclic dependency
1900                 if (allGroupAMembersNames.contains(groupAName)) {
1901                     ResponseFormat responseFormat = componentsUtils
1902                             .getResponseFormat(ActionStatus.GROUP_HAS_CYCLIC_DEPENDENCY, groupAName);
1903                     result = Either.right(responseFormat);
1904                 }
1905             }
1906         } catch (Exception e) {
1907             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1908             result = Either.right(responseFormat);
1909             log.debug("Exception occured when validateCyclicGroupsDependencies, error is:{}", e.getMessage(), e);
1910         }
1911         return result;
1912     }
1913
1914     protected void fillAllGroupMemebersRecursivly(String groupName, Map<String, GroupDefinition> allGroups,
1915                                                 Set<String> allGroupMembers) {
1916
1917         // Found Cyclic dependency
1918         if (isfillGroupMemebersRecursivlyStopCondition(groupName, allGroups, allGroupMembers)) {
1919             return;
1920         }
1921         GroupDefinition groupDefinition = allGroups.get(groupName);
1922         // All Members Of Current Group Resource Instances & Other Groups
1923         Set<String> currGroupMembers = groupDefinition.getMembers().keySet();
1924         // Filtered Members Of Current Group containing only members which
1925         // are groups
1926         List<String> currGroupFilteredMembers = currGroupMembers.stream().
1927                 // Keep Only Elements of type group and not Resource Instances
1928                         filter(allGroups::containsKey).
1929                 // Add Filtered Elements to main Set
1930                         peek(allGroupMembers::add).
1931                 // Collect results
1932                         collect(toList());
1933
1934         // Recursively call the method for all the filtered group members
1935         for (String innerGroupName : currGroupFilteredMembers) {
1936             fillAllGroupMemebersRecursivly(innerGroupName, allGroups, allGroupMembers);
1937         }
1938     }
1939
1940     public ImmutablePair<Resource, ActionStatus> createResourceFromNodeType(String nodeTypeYaml, UploadResourceInfo resourceMetaData, User creator, boolean isInTransaction, boolean needLock,
1941                                                                             Map<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
1942                                                                             List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo,
1943                                                                             String nodeName, boolean isNested) {
1944
1945         LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
1946                 LifecycleChangeInfoWithAction.LifecycleChanceActionEnum.CREATE_FROM_CSAR);
1947
1948         Function<Resource, Boolean> validator = resource -> validateResourceCreationFromNodeType(
1949                 resource, creator);
1950
1951         return resourceImportManager.importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator,
1952                 lifecycleChangeInfo, isInTransaction, true, needLock, nodeTypeArtifactsToHandle,
1953                 nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeName, isNested);
1954     }
1955
1956     public ImmutablePair<Resource, ActionStatus> createNodeTypeResourceFromYaml(
1957             String yamlName, Map.Entry<String, Object> nodeNameValue, User user, Map<String, Object> mapToConvert,
1958             Service resourceVf, boolean needLock,
1959             Map<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
1960             List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo,
1961             boolean isNested) {
1962
1963         UploadResourceInfo resourceMetaData = fillResourceMetadata(yamlName, resourceVf, nodeNameValue.getKey(), user);
1964
1965         String singleVfcYaml = buildNodeTypeYaml(nodeNameValue, mapToConvert,
1966                 resourceMetaData.getResourceType(), csarInfo);
1967         user = serviceBusinessLogic.validateUser(user, "CheckIn Resource", resourceVf, AuditingActionEnum.CHECKIN_RESOURCE, true);
1968         return createResourceFromNodeType(singleVfcYaml, resourceMetaData, user, true, needLock,
1969                 nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo,
1970                 nodeNameValue.getKey(), isNested);
1971     }
1972
1973     protected UploadResourceInfo fillResourceMetadata(String yamlName, Service resourceVf,
1974                                                     String nodeName, User user) {
1975         UploadResourceInfo resourceMetaData = new UploadResourceInfo();
1976
1977         // validate nodetype name prefix
1978         if (!nodeName.startsWith(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX)) {
1979             log.debug("invalid nodeName:{} does not start with {}.", nodeName,
1980                     Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
1981             throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE,
1982                     yamlName, resourceMetaData.getName(), nodeName);
1983         }
1984
1985         String actualName = this.getNodeTypeActualName(nodeName);
1986         String namePrefix = nodeName.replace(actualName, "");
1987         String resourceType = namePrefix.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1988
1989         // if we import from csar, the node_type name can be
1990         // org.openecomp.resource.abstract.node_name - in this case we always
1991         // create a vfc
1992         if (resourceType.equals(Constants.ABSTRACT)) {
1993             resourceType = ResourceTypeEnum.VFC.name().toLowerCase();
1994         }
1995         // validating type
1996         if (!ResourceTypeEnum.containsName(resourceType.toUpperCase())) {
1997             log.debug("invalid resourceType:{} the type is not one of the valide types:{}.", resourceType.toUpperCase(),
1998                     ResourceTypeEnum.values());
1999             throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE,
2000                     yamlName, resourceMetaData.getName(), nodeName);
2001         }
2002
2003         // Setting name
2004         resourceMetaData.setName(resourceVf.getSystemName() + actualName);
2005
2006         // Setting type from name
2007         String type = resourceType.toUpperCase();
2008         resourceMetaData.setResourceType(type);
2009
2010         resourceMetaData.setDescription(ImportUtils.Constants.INNER_VFC_DESCRIPTION);
2011         resourceMetaData.setIcon(ImportUtils.Constants.DEFAULT_ICON);
2012         resourceMetaData.setContactId(user.getUserId());
2013
2014         // Setting tag
2015         List<String> tags = new ArrayList<>();
2016         tags.add(resourceMetaData.getName());
2017         resourceMetaData.setTags(tags);
2018
2019         // Setting category
2020         CategoryDefinition category = new CategoryDefinition();
2021         category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
2022         SubCategoryDefinition subCategory = new SubCategoryDefinition();
2023         subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
2024         category.addSubCategory(subCategory);
2025         List<CategoryDefinition> categories = new ArrayList<>();
2026         categories.add(category);
2027         resourceMetaData.setCategories(categories);
2028
2029         return resourceMetaData;
2030     }
2031
2032
2033     public Resource propagateStateToCertified(User user, Resource resource,
2034                                               LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock,
2035                                               boolean forceCertificationAllowed) {
2036
2037         Either<Resource, ResponseFormat> result = null;
2038         try {
2039             if (resource.getLifecycleState() != LifecycleStateEnum.CERTIFIED && forceCertificationAllowed
2040                     && lifecycleBusinessLogic.isFirstCertification(resource.getVersion())) {
2041                 nodeForceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock);
2042             }
2043             if (resource.getLifecycleState() == LifecycleStateEnum.CERTIFIED) {
2044                 Either<ArtifactDefinition, Operation> eitherPopulated = serviceBusinessLogic.populateToscaArtifacts(
2045                         resource, user, false, inTransaction, needLock);
2046                 return resource;
2047             }
2048             return nodeFullCertification(resource.getUniqueId(), user, lifecycleChangeInfo, inTransaction, needLock);
2049         } catch (Exception e) {
2050             log.debug("The exception has occurred upon certification of resource {}. ", resource.getName(), e);
2051             throw e;
2052         } finally {
2053             if (result == null || result.isRight()) {
2054                 BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
2055                 if (!inTransaction) {
2056                     serviceBusinessLogic.janusGraphDao.rollback();
2057                 }
2058             } else if (!inTransaction) {
2059                 serviceBusinessLogic.janusGraphDao.commit();
2060             }
2061         }
2062     }
2063
2064     public Resource buildValidComplexVfc(CsarInfo csarInfo, String nodeName,
2065                                           Map<String, NodeTypeInfo> nodesInfo) {
2066
2067         Resource complexVfc = buildComplexVfcMetadata(csarInfo, nodeName, nodesInfo);
2068         log.debug("************* Going to validate complex VFC from yaml {}", complexVfc.getName());
2069         csarInfo.addNodeToQueue(nodeName);
2070         return validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(),
2071                 AuditingActionEnum.IMPORT_RESOURCE, true, csarInfo);
2072     }
2073
2074     public Resource updateGroupsOnResource(Resource resource, Map<String, GroupDefinition> groups) {
2075         if (MapUtils.isEmpty(groups)) {
2076             return resource;
2077         } else {
2078             updateOrCreateGroups(resource, groups);
2079         }
2080         Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade
2081                 .getToscaElement(resource.getUniqueId());
2082         if (updatedResource.isRight()) {
2083             throw new ComponentException(componentsUtils.getResponseFormatByResource(
2084                     componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource));
2085         }
2086         return updatedResource.left().value();
2087     }
2088
2089     protected void setInformationalArtifactsPlaceHolder(Resource resource, User user) {
2090         Map<String, ArtifactDefinition> artifactMap = resource.getArtifacts();
2091         if (artifactMap == null) {
2092             artifactMap = new HashMap<>();
2093         }
2094         String resourceUniqueId = resource.getUniqueId();
2095         List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration()
2096                 .getExcludeResourceCategory();
2097         List<String> exludeResourceType = ConfigurationManager.getConfigurationManager().getConfiguration()
2098                 .getExcludeResourceType();
2099         Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager()
2100                 .getConfiguration().getInformationalResourceArtifacts();
2101         List<CategoryDefinition> categories = resource.getCategories();
2102         boolean isCreateArtifact = true;
2103         if (exludeResourceCategory != null) {
2104             String category = categories.get(0).getName();
2105             isCreateArtifact = exludeResourceCategory.stream().noneMatch(e->e.equalsIgnoreCase(category));
2106         }
2107         if (isCreateArtifact && exludeResourceType != null) {
2108             String resourceType = resource.getResourceType().name();
2109             isCreateArtifact = exludeResourceType.stream().noneMatch(e->e.equalsIgnoreCase(resourceType));
2110         }
2111         if (informationalResourceArtifacts != null && isCreateArtifact) {
2112             Set<String> keys = informationalResourceArtifacts.keySet();
2113             for (String informationalResourceArtifactName : keys) {
2114                 Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts
2115                         .get(informationalResourceArtifactName);
2116                 ArtifactDefinition artifactDefinition = serviceBusinessLogic.artifactsBusinessLogic.createArtifactPlaceHolderInfo(
2117                         resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user,
2118                         ArtifactGroupTypeEnum.INFORMATIONAL);
2119                 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
2120
2121             }
2122         }
2123         resource.setArtifacts(artifactMap);
2124     }
2125
2126     public void rollback(boolean inTransaction, Resource resource, List<ArtifactDefinition> createdArtifacts, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts) {
2127         if(!inTransaction) {
2128             serviceBusinessLogic.janusGraphDao.rollback();
2129         }
2130         if (isNotEmpty(createdArtifacts) && isNotEmpty(nodeTypesNewCreatedArtifacts)) {
2131             createdArtifacts.addAll(nodeTypesNewCreatedArtifacts);
2132             log.debug("Found {} newly created artifacts to deleted, the component name: {}",createdArtifacts.size(), resource.getName());
2133         }
2134     }
2135
2136     public void createArtifactsPlaceHolderData(Resource resource, User user) {
2137         setInformationalArtifactsPlaceHolder(resource, user);
2138         setDeploymentArtifactsPlaceHolder(resource, user);
2139         serviceBusinessLogic.setToscaArtifactsPlaceHolders(resource, user);
2140     }
2141
2142     public void handleGroupsProperties(Service service, Map<String, GroupDefinition> groups) {
2143         List<InputDefinition> inputs = service.getInputs();
2144         if (MapUtils.isNotEmpty(groups)) {
2145             groups.values()
2146                     .stream()
2147                     .filter(g -> isNotEmpty(g.getProperties()))
2148                     .flatMap(g -> g.getProperties().stream())
2149                     .forEach(p -> handleGetInputs(p, inputs));
2150         }
2151     }
2152
2153     public void handleGroupsProperties(Resource resource, Map<String, GroupDefinition> groups) {
2154         List<InputDefinition> inputs = resource.getInputs();
2155         if (MapUtils.isNotEmpty(groups)) {
2156             groups.values()
2157                     .stream()
2158                     .filter(g -> isNotEmpty(g.getProperties()))
2159                     .flatMap(g -> g.getProperties().stream())
2160                     .forEach(p -> handleGetInputs(p, inputs));
2161         }
2162     }
2163
2164     protected void handleGetInputs(PropertyDataDefinition property, List<InputDefinition> inputs) {
2165         if (isNotEmpty(property.getGetInputValues())) {
2166             if (inputs == null || inputs.isEmpty()) {
2167                 log.debug("Failed to add property {} to group. Inputs list is empty ", property);
2168                 serviceBusinessLogic.rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, property.getGetInputValues()
2169                         .stream()
2170                         .map(GetInputValueDataDefinition::getInputName)
2171                         .collect(toList()).toString());
2172             }
2173             ListIterator<GetInputValueDataDefinition> getInputValuesIter = property.getGetInputValues().listIterator();
2174             while (getInputValuesIter.hasNext()) {
2175                 GetInputValueDataDefinition getInput = getInputValuesIter.next();
2176                 InputDefinition input = findInputByName(inputs, getInput);
2177                 getInput.setInputId(input.getUniqueId());
2178                 if (getInput.getGetInputIndex() != null) {
2179                     GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
2180                     input = findInputByName(inputs, getInputIndex);
2181                     getInputIndex.setInputId(input.getUniqueId());
2182                     getInputValuesIter.add(getInputIndex);
2183                 }
2184             }
2185         }
2186     }
2187
2188     public InputDefinition findInputByName(List<InputDefinition> inputs, GetInputValueDataDefinition getInput) {
2189         Optional<InputDefinition> inputOpt = inputs.stream()
2190                 .filter(p -> p.getName().equals(getInput.getInputName()))
2191                 .findFirst();
2192         if (!inputOpt.isPresent()) {
2193             log.debug("#findInputByName - Failed to find the input {} ", getInput.getInputName());
2194             serviceBusinessLogic.rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, getInput.getInputName());
2195         }
2196         return inputOpt.get();
2197     }
2198
2199     public void associateComponentInstancePropertiesToComponent(String yamlName, Resource resource, Map<String, List<ComponentInstanceProperty>> instProperties) {
2200         try {
2201             Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade
2202                     .associateComponentInstancePropertiesToComponent(instProperties, resource.getUniqueId());
2203             if (addPropToInst.isRight()) {
2204                 log.debug("failed to associate properties of resource {} status is {}", resource.getUniqueId(),
2205                         addPropToInst.right().value());
2206                 throw new ComponentException(componentsUtils.getResponseFormat(
2207                         componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName));
2208             }
2209         } catch (Exception e) {
2210             log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage());
2211             throw new ComponentException(ActionStatus.GENERAL_ERROR);
2212         }
2213     }
2214
2215     public void associateComponentInstanceInputsToComponent(String yamlName, Resource resource, Map<String, List<ComponentInstanceInput>> instInputs) {
2216         if (MapUtils.isNotEmpty(instInputs)) {
2217             Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addInputToInst = toscaOperationFacade
2218                     .associateComponentInstanceInputsToComponent(instInputs, resource.getUniqueId());
2219             if (addInputToInst.isRight()) {
2220                 log.debug("failed to associate inputs value of resource {} status is {}", resource.getUniqueId(),
2221                         addInputToInst.right().value());
2222                 throw new ComponentException(componentsUtils.getResponseFormat(
2223                         componentsUtils.convertFromStorageResponse(addInputToInst.right().value()), yamlName));
2224             }
2225         }
2226     }
2227
2228     public void associateDeploymentArtifactsToInstances(User user, String yamlName, Resource resource, Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts) {
2229         StorageOperationStatus addArtToInst = toscaOperationFacade
2230                 .associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource, user);
2231         if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2232             log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2233             throw new ComponentException(componentsUtils
2234                     .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2235         }
2236     }
2237
2238     public void associateArtifactsToInstances(String yamlName, Resource resource, Map<String, Map<String, ArtifactDefinition>> instArtifacts) {
2239
2240         StorageOperationStatus addArtToInst;
2241
2242         addArtToInst = toscaOperationFacade.associateArtifactsToInstances(instArtifacts, resource);
2243         if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2244             log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2245             throw new ComponentException(componentsUtils
2246                     .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2247         }
2248     }
2249
2250     public void associateOrAddCalculatedCapReq(String yamlName, Resource resource, Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities, Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements) {
2251
2252         StorageOperationStatus addArtToInst;
2253         addArtToInst = toscaOperationFacade.associateOrAddCalculatedCapReq(instCapabilities, instRequirements,
2254                 resource);
2255         if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2256             log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(),
2257                     addArtToInst);
2258             throw new ComponentException(componentsUtils
2259                     .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2260         }
2261     }
2262
2263     public void associateInstAttributeToComponentToInstances(String yamlName, Resource resource, Map<String, List<AttributeDataDefinition>> instAttributes) {
2264
2265         StorageOperationStatus addArtToInst;
2266         addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes,
2267                 resource);
2268         if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2269             log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(),
2270                     addArtToInst);
2271             throw new ComponentException(componentsUtils
2272                     .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2273         }
2274     }
2275
2276     public Resource getResourceAfterCreateRelations(Resource resource) {
2277         ComponentParametersView parametersView = getComponentFilterAfterCreateRelations();
2278         Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade
2279                 .getToscaElement(resource.getUniqueId(), parametersView);
2280
2281         if (eitherGetResource.isRight()) {
2282             throwComponentExceptionByResource(eitherGetResource.right().value(),resource);
2283         }
2284         return eitherGetResource.left().value();
2285     }
2286
2287     public Resource throwComponentExceptionByResource(StorageOperationStatus status, Resource resource) {
2288         ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
2289                 componentsUtils.convertFromStorageResponse(status), resource);
2290         throw new ComponentException(responseFormat);
2291     }
2292
2293     public void setCapabilityNamesTypes(Map<String, List<CapabilityDefinition>> originCapabilities,
2294                                          Map<String, List<UploadCapInfo>> uploadedCapabilities) {
2295         for (Map.Entry<String, List<UploadCapInfo>> currEntry : uploadedCapabilities.entrySet()) {
2296             if (originCapabilities.containsKey(currEntry.getKey())) {
2297                 currEntry.getValue().stream().forEach(cap -> cap.setType(currEntry.getKey()));
2298             }
2299         }
2300         for (Map.Entry<String, List<CapabilityDefinition>> capabilities : originCapabilities.entrySet()) {
2301             capabilities.getValue().stream().forEach(cap -> {
2302                 if (uploadedCapabilities.containsKey(cap.getName())) {
2303                     uploadedCapabilities.get(cap.getName()).stream().forEach(c -> {
2304                         c.setName(cap.getName());
2305                         c.setType(cap.getType());
2306                     });
2307                 }
2308             });
2309         }
2310     }
2311
2312     public Map<String, List<CapabilityDefinition>> getValidComponentInstanceCapabilities(
2313             String resourceId, Map<String, List<CapabilityDefinition>> defaultCapabilities,
2314             Map<String, List<UploadCapInfo>> uploadedCapabilities) {
2315
2316         Map<String, List<CapabilityDefinition>> validCapabilitiesMap = new HashMap<>();
2317         uploadedCapabilities.forEach((k,v)->addValidComponentInstanceCapabilities(k,v,resourceId,defaultCapabilities,validCapabilitiesMap));
2318         return validCapabilitiesMap;
2319     }
2320
2321     public void associateComponentInstanceInputsToComponent(String yamlName, Service service, Map<String, List<ComponentInstanceInput>> instInputs) {
2322         if (MapUtils.isNotEmpty(instInputs)) {
2323             Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addInputToInst = toscaOperationFacade
2324                     .associateComponentInstanceInputsToComponent(instInputs, service.getUniqueId());
2325             if (addInputToInst.isRight()) {
2326                 log.debug("failed to associate inputs value of resource {} status is {}", service.getUniqueId(),
2327                         addInputToInst.right().value());
2328                 throw new ComponentException(componentsUtils.getResponseFormat(
2329                         componentsUtils.convertFromStorageResponse(addInputToInst.right().value()), yamlName));
2330             }
2331         }
2332     }
2333
2334     public void associateComponentInstancePropertiesToComponent(String yamlName, Service service, Map<String, List<ComponentInstanceProperty>> instProperties) {
2335         Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade
2336                 .associateComponentInstancePropertiesToComponent(instProperties, service.getUniqueId());
2337         if (addPropToInst.isRight()) {
2338             throw new ComponentException(componentsUtils.getResponseFormat(
2339                     componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName));
2340         }
2341     }
2342
2343     public void associateDeploymentArtifactsToInstances(User user, String yamlName, Service resource, Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts) {
2344         StorageOperationStatus addArtToInst = toscaOperationFacade
2345                 .associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource, user);
2346         if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2347             log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2348             throw new ComponentException(componentsUtils
2349                     .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2350         }
2351     }
2352
2353     public void associateArtifactsToInstances(String yamlName, Service resource, Map<String, Map<String, ArtifactDefinition>> instArtifacts) {
2354         StorageOperationStatus addArtToInst;
2355
2356         addArtToInst = toscaOperationFacade.associateArtifactsToInstances(instArtifacts, resource);
2357         if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2358             log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2359             throw new ComponentException(componentsUtils
2360                     .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2361         }
2362     }
2363
2364     public void associateOrAddCalculatedCapReq(String yamlName, Service resource, Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities, Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements) {
2365         StorageOperationStatus addArtToInst;
2366         addArtToInst = toscaOperationFacade.associateOrAddCalculatedCapReq(instCapabilities, instRequirements,
2367                 resource);
2368         log.debug("enter associateOrAddCalculatedCapReq,get instCapabilities:{},get instRequirements:{}",
2369                 instCapabilities, instRequirements);
2370         if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2371             log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(),
2372                     addArtToInst);
2373             throw new ComponentException(componentsUtils
2374                     .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2375         }
2376     }
2377
2378     public void associateInstAttributeToComponentToInstances(String yamlName, Service resource, Map<String, List<AttributeDataDefinition>> instAttributes) {
2379         StorageOperationStatus addArtToInst;
2380
2381         addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes,
2382                 resource);
2383         if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2384             log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(),
2385                     addArtToInst);
2386             throw new ComponentException(componentsUtils
2387                     .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2388         }
2389     }
2390
2391     public void associateRequirementsToService(String yamlName, Service resource, Map<String, ListRequirementDataDefinition> requirements) {
2392         StorageOperationStatus addReqToService;
2393         addReqToService = toscaOperationFacade.associateRequirementsToService(requirements,
2394                 resource.getUniqueId());
2395         if (addReqToService != StorageOperationStatus.OK && addReqToService != StorageOperationStatus.NOT_FOUND) {
2396             log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(),
2397                     addReqToService);
2398             throw new ComponentException(componentsUtils
2399                     .getResponseFormat(componentsUtils.convertFromStorageResponse(addReqToService), yamlName));
2400         }
2401     }
2402
2403     public void associateCapabilitiesToService(String yamlName, Service resource, Map<String,ListCapabilityDataDefinition> capabilities) {
2404         StorageOperationStatus addCapToService;
2405         addCapToService = toscaOperationFacade.associateCapabilitiesToService(capabilities,
2406                 resource.getUniqueId());
2407         if (addCapToService != StorageOperationStatus.OK && addCapToService != StorageOperationStatus.NOT_FOUND) {
2408             log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(),
2409                     addCapToService);
2410             throw new ComponentException(componentsUtils
2411                     .getResponseFormat(componentsUtils.convertFromStorageResponse(addCapToService), yamlName));
2412         }
2413     }
2414
2415     public void associateResourceInstances(String yamlName, Service service, List<RequirementCapabilityRelDef> relations) {
2416         Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> relationsEither = toscaOperationFacade.associateResourceInstances(service, service.getUniqueId(), relations);
2417
2418         if (relationsEither.isRight() && relationsEither.right().value() != StorageOperationStatus.NOT_FOUND) {
2419             StorageOperationStatus status = relationsEither.right().value();
2420             log.debug("failed to associate instances of service {} status is {}", service.getUniqueId(),
2421                     status);
2422             throw new ComponentException(componentsUtils
2423                     .getResponseFormat(componentsUtils.convertFromStorageResponse(status), yamlName));
2424         }
2425     }
2426
2427     public void addCapabilities(Map<String, List<CapabilityDefinition>> originCapabilities, String type, List<CapabilityDefinition> capabilities) {
2428         List<CapabilityDefinition> list = capabilities.stream().map(CapabilityDefinition::new)
2429                 .collect(toList());
2430         originCapabilities.put(type, list);
2431     }
2432
2433     public void addCapabilitiesProperties(Map<String, Map<String, UploadPropInfo>> newPropertiesMap, List<UploadCapInfo> capabilities) {
2434         for (UploadCapInfo capability : capabilities) {
2435             if (isNotEmpty(capability.getProperties())) {
2436                 newPropertiesMap.put(capability.getName(), capability.getProperties().stream()
2437                         .collect(toMap(UploadInfo::getName, p -> p)));
2438             }
2439         }
2440     }
2441
2442     public Service getServiceWithGroups(String resourceId) {
2443
2444         ComponentParametersView filter = new ComponentParametersView();
2445         filter.setIgnoreGroups(false);
2446         Either<Service, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resourceId, filter);
2447         if (updatedResource.isRight()) {
2448             serviceBusinessLogic.rollbackWithException(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resourceId);
2449         }
2450         return updatedResource.left().value();
2451     }
2452
2453     public Resource getResourceWithGroups(String resourceId) {
2454
2455         ComponentParametersView filter = new ComponentParametersView();
2456         filter.setIgnoreGroups(false);
2457         Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resourceId, filter);
2458         if (updatedResource.isRight()) {
2459             serviceBusinessLogic.rollbackWithException(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resourceId);
2460         }
2461         return updatedResource.left().value();
2462     }
2463
2464     public void associateResourceInstances(String yamlName, Resource resource, List<RequirementCapabilityRelDef> relations) {
2465
2466         Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> relationsEither = toscaOperationFacade.associateResourceInstances(resource, resource.getUniqueId(), relations);
2467         if (relationsEither.isRight() && relationsEither.right().value() != StorageOperationStatus.NOT_FOUND) {
2468             StorageOperationStatus status = relationsEither.right().value();
2469             log.debug("failed to associate instances of resource {} status is {}", resource.getUniqueId(),
2470                     status);
2471             throw new ComponentException(componentsUtils
2472                     .getResponseFormat(componentsUtils.convertFromStorageResponse(status), yamlName));
2473         }
2474     }
2475
2476     public void addRelationsToRI(String yamlName, Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, List<ComponentInstance> componentInstancesList, List<RequirementCapabilityRelDef> relations) {
2477         for (Map.Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) {
2478             UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
2479             ComponentInstance currentCompInstance = null;
2480             for (ComponentInstance compInstance : componentInstancesList) {
2481
2482                 if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
2483                     currentCompInstance = compInstance;
2484                     break;
2485                 }
2486             }
2487             if (currentCompInstance == null) {
2488                 log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(),
2489                         resource.getUniqueId());
2490                 BeEcompErrorManager.getInstance().logInternalDataError(
2491                         COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE,
2492                         resource.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR);
2493                 ResponseFormat responseFormat = componentsUtils
2494                         .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2495                 throw new ComponentException(responseFormat);
2496             }
2497
2498             ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, resource, entry.getValue(), relations);
2499             if (addRelationToRiRes.getStatus() != 200) {
2500                 throw new ComponentException(addRelationToRiRes);
2501             }
2502         }
2503     }
2504
2505     protected ResponseFormat addRelationToRI(String yamlName, Resource resource,
2506                                            UploadComponentInstanceInfo nodesInfoValue, List<RequirementCapabilityRelDef> relations) {
2507         List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
2508         ComponentInstance currentCompInstance = null;
2509
2510         for (ComponentInstance compInstance : componentInstancesList) {
2511
2512             if (compInstance.getName().equals(nodesInfoValue.getName())) {
2513                 currentCompInstance = compInstance;
2514                 break;
2515             }
2516         }
2517         if (currentCompInstance == null) {
2518             log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, nodesInfoValue.getName(),
2519                     resource.getUniqueId());
2520             BeEcompErrorManager.getInstance().logInternalDataError(
2521                     COMPONENT_INSTANCE_WITH_NAME + nodesInfoValue.getName() + IN_RESOURCE,
2522                     resource.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR);
2523             return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE,
2524                     yamlName);
2525         }
2526         String resourceInstanceId = currentCompInstance.getUniqueId();
2527         Map<String, List<UploadReqInfo>> regMap = nodesInfoValue.getRequirements();
2528
2529         if (regMap != null) {
2530             Iterator<Map.Entry<String, List<UploadReqInfo>>> nodesRegValue = regMap.entrySet().iterator();
2531             while (nodesRegValue.hasNext()) {
2532                 Map.Entry<String, List<UploadReqInfo>> nodesRegInfoEntry = nodesRegValue.next();
2533                 List<UploadReqInfo> uploadRegInfoList = nodesRegInfoEntry.getValue();
2534                 for (UploadReqInfo uploadRegInfo : uploadRegInfoList) {
2535                     log.debug("Going to create  relation {}", uploadRegInfo.getName());
2536                     String regName = uploadRegInfo.getName();
2537                     RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef();
2538                     regCapRelDef.setFromNode(resourceInstanceId);
2539                     log.debug("try to find available requirement {} ", regName);
2540                     Either<RequirementDefinition, ResponseFormat> eitherReqStatus = findAviableRequiremen(regName,
2541                             yamlName, nodesInfoValue, currentCompInstance,
2542                             uploadRegInfo.getCapabilityName());
2543                     if (eitherReqStatus.isRight()) {
2544                         return eitherReqStatus.right().value();
2545                     }
2546
2547                     RequirementDefinition validReq = eitherReqStatus.left().value();
2548                     List<CapabilityRequirementRelationship> reqAndRelationshipPairList = regCapRelDef
2549                             .getRelationships();
2550                     if (reqAndRelationshipPairList == null) {
2551                         reqAndRelationshipPairList = new ArrayList<>();
2552                     }
2553                     RelationshipInfo reqAndRelationshipPair = new RelationshipInfo();
2554                     reqAndRelationshipPair.setRequirement(regName);
2555                     reqAndRelationshipPair.setRequirementOwnerId(validReq.getOwnerId());
2556                     reqAndRelationshipPair.setRequirementUid(validReq.getUniqueId());
2557                     RelationshipImpl relationship = new RelationshipImpl();
2558                     relationship.setType(validReq.getCapability());
2559                     reqAndRelationshipPair.setRelationships(relationship);
2560
2561                     ComponentInstance currentCapCompInstance = null;
2562                     for (ComponentInstance compInstance : componentInstancesList) {
2563                         if (compInstance.getName().equals(uploadRegInfo.getNode())) {
2564                             currentCapCompInstance = compInstance;
2565                             break;
2566                         }
2567                     }
2568
2569                     if (currentCapCompInstance == null) {
2570                         log.debug("The component instance  with name {} not found on resource {} ",
2571                                 uploadRegInfo.getNode(), resource.getUniqueId());
2572                         BeEcompErrorManager.getInstance().logInternalDataError(
2573                                 COMPONENT_INSTANCE_WITH_NAME + uploadRegInfo.getNode() + IN_RESOURCE,
2574                                 resource.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR);
2575                         return componentsUtils
2576                                 .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2577                     }
2578                     regCapRelDef.setToNode(currentCapCompInstance.getUniqueId());
2579                     log.debug("try to find aviable Capability  req name is {} ", validReq.getName());
2580                     CapabilityDefinition aviableCapForRel = findAvailableCapabilityByTypeOrName(validReq,
2581                             currentCapCompInstance, uploadRegInfo);
2582                     reqAndRelationshipPair.setCapability(aviableCapForRel.getName());
2583                     reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId());
2584                     reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId());
2585                     if (aviableCapForRel == null) {
2586                         BeEcompErrorManager.getInstance().logInternalDataError(
2587                                 "aviable capability was not found. req name is " + validReq.getName()
2588                                         + " component instance is " + currentCapCompInstance.getUniqueId(),
2589                                 resource.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR);
2590                         return componentsUtils
2591                                 .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2592                     }
2593                     CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship();
2594                     capReqRel.setRelation(reqAndRelationshipPair);
2595                     reqAndRelationshipPairList.add(capReqRel);
2596                     regCapRelDef.setRelationships(reqAndRelationshipPairList);
2597                     relations.add(regCapRelDef);
2598                 }
2599             }
2600         } else if (resource.getResourceType() != ResourceTypeEnum.VF) {
2601             return componentsUtils.getResponseFormat(ActionStatus.OK, yamlName);
2602         }
2603         return componentsUtils.getResponseFormat(ActionStatus.OK);
2604     }
2605
2606 }