Add test code for Test Topology Auto Design- Service Import
[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                 shouldCreateArtifact = false;
1362                 return;
1363             }
1364         } else {
1365             log.info("resource types for artifact placeholder {} were not defined. default is all resources",
1366                     k);
1367         }
1368         if (shouldCreateArtifact) {
1369             if (serviceBusinessLogic.artifactsBusinessLogic != null) {
1370                 ArtifactDefinition artifactDefinition = serviceBusinessLogic.artifactsBusinessLogic.createArtifactPlaceHolderInfo(
1371                         resource.getUniqueId(), k, (Map<String, Object>) v,
1372                         user, ArtifactGroupTypeEnum.DEPLOYMENT);
1373                 if (artifactDefinition != null
1374                         && !artifactMap.containsKey(artifactDefinition.getArtifactLabel())) {
1375                     artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
1376                 }
1377             }
1378         }
1379     }
1380
1381     public void mergeOldResourceMetadataWithNew(Resource oldResource, Resource newResource) {
1382
1383         if (newResource.getTags() == null || newResource.getTags().isEmpty()) {
1384             newResource.setTags(oldResource.getTags());
1385         }
1386
1387         if (newResource.getDescription() == null) {
1388             newResource.setDescription(oldResource.getDescription());
1389         }
1390
1391
1392         if (newResource.getContactId() == null) {
1393             newResource.setContactId(oldResource.getContactId());
1394         }
1395
1396         newResource.setCategories(oldResource.getCategories());
1397
1398     }
1399
1400     protected Resource buildComplexVfcMetadata(CsarInfo csarInfo, String nodeName,
1401                                              Map<String, NodeTypeInfo> nodesInfo) {
1402         Resource cvfc = new Resource();
1403         NodeTypeInfo nodeTypeInfo = nodesInfo.get(nodeName);
1404         cvfc.setName(buildCvfcName(csarInfo.getVfResourceName(), nodeName));
1405         cvfc.setNormalizedName(ValidationUtils.normaliseComponentName(cvfc.getName()));
1406         cvfc.setSystemName(ValidationUtils.convertToSystemName(cvfc.getName()));
1407         cvfc.setResourceType(ResourceTypeEnum.VF);
1408         cvfc.setAbstract(true);
1409         cvfc.setDerivedFrom(nodeTypeInfo.getDerivedFrom());
1410         cvfc.setDescription(ImportUtils.Constants.VF_DESCRIPTION);
1411         cvfc.setIcon(ImportUtils.Constants.DEFAULT_ICON);
1412         cvfc.setContactId(csarInfo.getModifier().getUserId());
1413         cvfc.setCreatorUserId(csarInfo.getModifier().getUserId());
1414         cvfc.setVendorName("cmri");
1415         cvfc.setVendorRelease("1.0");
1416         cvfc.setResourceVendorModelNumber("");
1417         cvfc.setToscaResourceName(
1418                 buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), csarInfo.getVfResourceName(), nodeName)
1419                         .getLeft());
1420         cvfc.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID());
1421
1422         List<String> tags = new ArrayList<>();
1423         tags.add(cvfc.getName());
1424         cvfc.setTags(tags);
1425
1426         CategoryDefinition category = new CategoryDefinition();
1427         category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
1428         SubCategoryDefinition subCategory = new SubCategoryDefinition();
1429         subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
1430         category.addSubCategory(subCategory);
1431         List<CategoryDefinition> categories = new ArrayList<>();
1432         categories.add(category);
1433         cvfc.setCategories(categories);
1434
1435         cvfc.setVersion(ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION);
1436         cvfc.setLifecycleState(ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT);
1437         cvfc.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION);
1438
1439         return cvfc;
1440     }
1441
1442     public Boolean validateResourceCreationFromNodeType(Resource resource, User creator) {
1443         validateDerivedFromNotEmpty(creator, resource, AuditingActionEnum.CREATE_RESOURCE);
1444         return true;
1445     }
1446
1447     private void validateDerivedFromNotEmpty(User user, Resource resource, AuditingActionEnum actionEnum) {
1448         log.debug("validate resource derivedFrom field");
1449         if ((resource.getDerivedFrom() == null) || (resource.getDerivedFrom().isEmpty())
1450                 || (resource.getDerivedFrom().get(0)) == null || (resource.getDerivedFrom().get(0).trim().isEmpty())) {
1451             log.info("derived from (template) field is missing for the resource");
1452             ResponseFormat responseFormat = componentsUtils
1453                     .getResponseFormat(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
1454             componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
1455
1456             throw new ComponentException(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
1457         }
1458     }
1459
1460     public Service createInputsOnService(Service service, Map<String, InputDefinition> inputs) {
1461         List<InputDefinition> resourceProperties = service.getInputs();
1462         if (MapUtils.isNotEmpty(inputs)|| isNotEmpty(resourceProperties)) {
1463
1464             Either<List<InputDefinition>, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs,
1465                     service);
1466             if (createInputs.isRight()) {
1467                 throw new ComponentException(createInputs.right().value());
1468             }
1469         } else {
1470             return service;
1471         }
1472         Either<Service, StorageOperationStatus> updatedResource = toscaOperationFacade
1473                 .getToscaElement(service.getUniqueId());
1474         if (updatedResource.isRight()) {
1475             throw new ComponentException(componentsUtils.getResponseFormatByComponent(
1476                     componentsUtils.convertFromStorageResponse(updatedResource.right().value()), service, ComponentTypeEnum.SERVICE));
1477         }
1478         return updatedResource.left().value();
1479     }
1480
1481
1482     public Service createServiceTransaction(Service service, User user, boolean isNormative) {
1483         // validate resource name uniqueness
1484         log.debug("validate resource name");
1485         Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade.validateComponentNameExists(
1486                 service.getName(), null, service.getComponentType());
1487         if (eitherValidation.isRight()) {
1488             log.debug("Failed to validate component name {}. Status is {}. ", service.getName(),
1489                     eitherValidation.right().value());
1490             ResponseFormat errorResponse = componentsUtils
1491                     .getResponseFormat(componentsUtils.convertFromStorageResponse(eitherValidation.right().value()));
1492             throw new ComponentException(errorResponse);
1493         }
1494         if (eitherValidation.left().value()) {
1495             log.debug("resource with name: {}, already exists", service.getName());
1496             ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST,
1497                     ComponentTypeEnum.RESOURCE.getValue(), service.getName());
1498             throw new ComponentException(errorResponse);
1499         }
1500
1501         log.debug("send resource {} to dao for create", service.getName());
1502
1503         createArtifactsPlaceHolderData(service, user);
1504         // enrich object
1505         if (!isNormative) {
1506             log.debug("enrich resource with creator, version and state");
1507             service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
1508             service.setVersion(INITIAL_VERSION);
1509             service.setHighestVersion(true);
1510         }
1511         return toscaOperationFacade.createToscaComponent(service)
1512                 .left()
1513                 .on(r->throwComponentExceptionByResource(r, service));
1514     }
1515
1516     public Service throwComponentExceptionByResource(StorageOperationStatus status, Service service) {
1517         ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent(
1518                 componentsUtils.convertFromStorageResponse(status), service, ComponentTypeEnum.SERVICE);
1519         throw new ComponentException(responseFormat);
1520     }
1521
1522
1523     protected void createArtifactsPlaceHolderData(Service service, User user) {
1524         setInformationalArtifactsPlaceHolder(service, user);
1525         serviceBusinessLogic.setDeploymentArtifactsPlaceHolder(service, user);
1526         serviceBusinessLogic.setToscaArtifactsPlaceHolders(service, user);
1527     }
1528
1529     @SuppressWarnings("unchecked")
1530     protected void setInformationalArtifactsPlaceHolder(Service service, User user) {
1531         Map<String, ArtifactDefinition> artifactMap = service.getArtifacts();
1532         if (artifactMap == null) {
1533             artifactMap = new HashMap<>();
1534         }
1535         String resourceUniqueId = service.getUniqueId();
1536         List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration()
1537                 .getExcludeResourceCategory();
1538         List<String> exludeResourceType = ConfigurationManager.getConfigurationManager().getConfiguration()
1539                 .getExcludeResourceType();
1540         Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager()
1541                 .getConfiguration().getInformationalResourceArtifacts();
1542         List<CategoryDefinition> categories = service.getCategories();
1543         boolean isCreateArtifact = true;
1544         if (exludeResourceCategory != null) {
1545             String category = categories.get(0).getName();
1546             isCreateArtifact = exludeResourceCategory.stream().noneMatch(e->e.equalsIgnoreCase(category));
1547         }
1548
1549         if (informationalResourceArtifacts != null && isCreateArtifact) {
1550             Set<String> keys = informationalResourceArtifacts.keySet();
1551             for (String informationalResourceArtifactName : keys) {
1552                 Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts
1553                         .get(informationalResourceArtifactName);
1554                 ArtifactDefinition artifactDefinition = serviceBusinessLogic.artifactsBusinessLogic.createArtifactPlaceHolderInfo(
1555                         resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user,
1556                         ArtifactGroupTypeEnum.INFORMATIONAL);
1557                 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
1558
1559             }
1560         }
1561         service.setArtifacts(artifactMap);
1562     }
1563
1564     public void rollback(boolean inTransaction, Service service, List<ArtifactDefinition> createdArtifacts, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts) {
1565         if(!inTransaction) {
1566             serviceBusinessLogic.janusGraphDao.rollback();
1567         }
1568         if (isNotEmpty(createdArtifacts) && isNotEmpty(nodeTypesNewCreatedArtifacts)) {
1569             createdArtifacts.addAll(nodeTypesNewCreatedArtifacts);
1570             log.debug("Found {} newly created artifacts to deleted, the component name: {}",createdArtifacts.size(), service.getName());
1571         }
1572     }
1573
1574     public Map<String,Object> getNodeTypesFromTemplate(Map<String, Object> mappedToscaTemplate) {
1575         return ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES)
1576                 .left().orValue(HashMap::new);
1577     }
1578
1579     private Resource nodeForceCertification(Resource resource, User user,
1580                                             LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
1581         return lifecycleBusinessLogic.forceResourceCertification(resource, user, lifecycleChangeInfo, inTransaction,
1582                 needLock);
1583     }
1584
1585     private Resource nodeFullCertification(String uniqueId, User user,
1586                                            LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
1587         Either<Resource, ResponseFormat> resourceResponse = lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFY, lifecycleChangeInfo,
1588                 inTransaction, needLock);
1589         if(resourceResponse.isRight()){
1590             throw new ByResponseFormatComponentException(resourceResponse.right().value());
1591         }
1592         return resourceResponse.left().value();
1593     }
1594
1595     public Either<Boolean, ResponseFormat> validateNestedDerivedFromDuringUpdate(Resource currentResource,
1596                                                                                   Resource updateInfoResource, boolean hasBeenCertified) {
1597
1598         List<String> currentDerivedFrom = currentResource.getDerivedFrom();
1599         List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
1600         if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null
1601                 || updatedDerivedFrom.isEmpty()) {
1602             log.trace("Update normative types");
1603             return Either.left(true);
1604         }
1605
1606         String derivedFromCurrent = currentDerivedFrom.get(0);
1607         String derivedFromUpdated = updatedDerivedFrom.get(0);
1608
1609         if (!derivedFromCurrent.equals(derivedFromUpdated)) {
1610             if (!hasBeenCertified) {
1611                 validateDerivedFromExist(null, updateInfoResource, null);
1612             } else {
1613                 Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null,
1614                         currentResource, updateInfoResource, null);
1615
1616                 if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left().value()) {
1617                     log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
1618                     return validateDerivedFromExtending;
1619                 }
1620             }
1621         }
1622         return Either.left(true);
1623     }
1624
1625     protected Either<Boolean, ResponseFormat> validateDerivedFromExtending(User user, Resource currentResource,
1626                                                                          Resource updateInfoResource, AuditingActionEnum actionEnum) {
1627         String currentTemplateName = currentResource.getDerivedFrom().get(0);
1628         String updatedTemplateName = updateInfoResource.getDerivedFrom().get(0);
1629
1630         Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
1631                 .validateToscaResourceNameExtends(currentTemplateName, updatedTemplateName);
1632         if (dataModelResponse.isRight()) {
1633             StorageOperationStatus storageStatus = dataModelResponse.right().value();
1634             BeEcompErrorManager.getInstance()
1635                     .logBeDaoSystemError("Create/Update Resource - validateDerivingFromExtendingType");
1636             ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
1637                     componentsUtils.convertFromStorageResponse(storageStatus), currentResource);
1638             log.trace("audit before sending response");
1639             componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
1640             return Either.right(responseFormat);
1641         }
1642
1643         if (!dataModelResponse.left().value()) {
1644             log.info("resource template with name {} does not inherit as original {}", updatedTemplateName,
1645                     currentTemplateName);
1646             ResponseFormat responseFormat = componentsUtils
1647                     .getResponseFormat(ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND);
1648             componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
1649
1650             return Either.right(responseFormat);
1651
1652         }
1653         return Either.left(true);
1654     }
1655
1656     public void validateResourceFieldsBeforeUpdate(Resource currentResource, Resource updateInfoResource,
1657                                                     boolean inTransaction, boolean isNested) {
1658         validateFields(currentResource, updateInfoResource, inTransaction, isNested);
1659     }
1660
1661
1662     private void validateFields(Resource currentResource, Resource updateInfoResource, boolean inTransaction, boolean isNested) {
1663         boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentResource.getVersion());
1664         log.debug("validate resource name before update");
1665         validateResourceName(currentResource, updateInfoResource, hasBeenCertified, isNested);
1666         log.debug("validate description before update");
1667         serviceBusinessLogic.componentDescriptionValidator.validateAndCorrectField(null, updateInfoResource, null);
1668         log.debug("validate icon before update");
1669         log.debug("validate tags before update");
1670         serviceBusinessLogic.componentTagsValidator.validateAndCorrectField(null, updateInfoResource, null);
1671         log.debug("validate vendor name before update");
1672         log.debug("validate resource vendor model number before update");
1673         log.debug("validate vendor release before update");
1674         log.debug("validate contact info before update");
1675         serviceBusinessLogic.componentContactIdValidator.validateAndCorrectField(null, updateInfoResource, null);
1676         log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
1677         log.debug("validate category before update");
1678     }
1679
1680
1681     protected void validateResourceName(Resource currentResource, Resource updateInfoResource,
1682                                       boolean hasBeenCertified, boolean isNested) {
1683         String resourceNameUpdated = updateInfoResource.getName();
1684         if (!isResourceNameEquals(currentResource, updateInfoResource)) {
1685             if (isNested || !hasBeenCertified) {
1686                 serviceBusinessLogic.componentNameValidator.validateAndCorrectField(null, updateInfoResource, null);
1687                 currentResource.setName(resourceNameUpdated);
1688                 currentResource.setNormalizedName(ValidationUtils.normaliseComponentName(resourceNameUpdated));
1689                 currentResource.setSystemName(ValidationUtils.convertToSystemName(resourceNameUpdated));
1690
1691             } else {
1692                 log.info("Resource name: {}, cannot be updated once the resource has been certified once.",
1693                         resourceNameUpdated);
1694                 throw new ComponentException(ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED);
1695             }
1696         }
1697     }
1698
1699     protected boolean isResourceNameEquals(Resource currentResource, Resource updateInfoResource) {
1700         String resourceNameUpdated = updateInfoResource.getName();
1701         String resourceNameCurrent = currentResource.getName();
1702         if (resourceNameCurrent.equals(resourceNameUpdated)) {
1703             return true;
1704         }
1705         return currentResource.getResourceType().equals(ResourceTypeEnum.VF) &&
1706                 resourceNameUpdated.equals(addCvfcSuffixToResourceName(resourceNameCurrent));
1707     }
1708
1709     public Resource prepareResourceForUpdate(Resource oldResource, Resource newResource, User user,
1710                                               boolean inTransaction, boolean needLock) {
1711
1712         if (!ComponentValidationUtils.canWorkOnResource(oldResource, user.getUserId())) {
1713             // checkout
1714             return lifecycleBusinessLogic.changeState(
1715                     oldResource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
1716                     new LifecycleChangeInfoWithAction("update by import"), inTransaction, needLock)
1717                     .left()
1718                     .on(response -> failOnChangeState(response, user, oldResource, newResource));
1719         }
1720         return oldResource;
1721     }
1722
1723     protected Resource failOnChangeState(ResponseFormat response, User user, Resource oldResource, Resource newResource) {
1724         log.info("resource {} cannot be updated. reason={}", oldResource.getUniqueId(),
1725                 response.getFormattedMessage());
1726         componentsUtils.auditResource(response, user, newResource, AuditingActionEnum.IMPORT_RESOURCE,
1727                 ResourceVersionInfo.newBuilder()
1728                         .state(oldResource.getLifecycleState().name())
1729                         .version(oldResource.getVersion())
1730                         .build());
1731         throw new ComponentException(response);
1732     }
1733
1734     public Resource handleResourceGenericType(Resource resource) {
1735         Resource genericResource = serviceBusinessLogic.fetchAndSetDerivedFromGenericType(resource);
1736         if (resource.shouldGenerateInputs()) {
1737             serviceBusinessLogic.generateAndAddInputsFromGenericTypeProperties(resource, genericResource);
1738         }
1739         return genericResource;
1740     }
1741
1742     public Resource createInputsOnResource(Resource resource, Map<String, InputDefinition> inputs) {
1743         List<InputDefinition> resourceProperties = resource.getInputs();
1744         if (MapUtils.isNotEmpty(inputs)|| isNotEmpty(resourceProperties)) {
1745
1746             Either<List<InputDefinition>, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs,
1747                     resource);
1748             if (createInputs.isRight()) {
1749                 throw new ComponentException(createInputs.right().value());
1750             }
1751         } else {
1752             return resource;
1753         }
1754         Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade
1755                 .getToscaElement(resource.getUniqueId());
1756         if (updatedResource.isRight()) {
1757             throw new ComponentException(componentsUtils.getResponseFormatByResource(
1758                     componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource));
1759         }
1760         return updatedResource.left().value();
1761     }
1762
1763     protected void updateOrCreateGroups(Resource resource, Map<String, GroupDefinition> groups) {
1764         List<GroupDefinition> groupsFromResource = resource.getGroups();
1765         List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(groups, new Service());
1766         List<GroupDefinition> groupsToUpdate = new ArrayList<>();
1767         List<GroupDefinition> groupsToDelete = new ArrayList<>();
1768         List<GroupDefinition> groupsToCreate = new ArrayList<>();
1769         if (isNotEmpty(groupsFromResource)) {
1770             addGroupsToCreateOrUpdate(groupsFromResource, groupsAsList, groupsToUpdate, groupsToCreate);
1771             addGroupsToDelete(groupsFromResource, groupsAsList, groupsToDelete);
1772         } else {
1773             groupsToCreate.addAll(groupsAsList);
1774         }
1775         if (isNotEmpty(groupsToCreate)) {
1776             fillGroupsFinalFields(groupsToCreate);
1777             if (isNotEmpty(groupsFromResource)) {
1778                 serviceBusinessLogic.groupBusinessLogic.addGroups(resource,
1779                         groupsToCreate, true)
1780                         .left()
1781                         .on(serviceBusinessLogic::throwComponentException);
1782             } else {
1783                 serviceBusinessLogic.groupBusinessLogic.createGroups(resource,
1784                         groupsToCreate, true)
1785                         .left()
1786                         .on(serviceBusinessLogic::throwComponentException);
1787             }
1788         }
1789         if (isNotEmpty(groupsToDelete)) {
1790             serviceBusinessLogic.groupBusinessLogic.deleteGroups(resource, groupsToDelete)
1791                     .left()
1792                     .on(serviceBusinessLogic::throwComponentException);
1793         }
1794         if (isNotEmpty(groupsToUpdate)) {
1795             serviceBusinessLogic.groupBusinessLogic.updateGroups(resource, groupsToUpdate, true)
1796                     .left()
1797                     .on(serviceBusinessLogic::throwComponentException);
1798         }
1799     }
1800
1801     protected void addGroupsToCreateOrUpdate(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList, List<GroupDefinition> groupsToUpdate, List<GroupDefinition> groupsToCreate) {
1802         for (GroupDefinition group : groupsAsList) {
1803             Optional<GroupDefinition> op = groupsFromResource.stream()
1804                     .filter(p -> p.getInvariantName().equalsIgnoreCase(group.getInvariantName())).findAny();
1805             if (op.isPresent()) {
1806                 GroupDefinition groupToUpdate = op.get();
1807                 groupToUpdate.setMembers(group.getMembers());
1808                 groupToUpdate.setCapabilities(group.getCapabilities());
1809                 groupToUpdate.setProperties(group.getProperties());
1810                 groupsToUpdate.add(groupToUpdate);
1811             } else {
1812                 groupsToCreate.add(group);
1813             }
1814         }
1815     }
1816
1817     protected void addGroupsToDelete(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList, List<GroupDefinition> groupsToDelete) {
1818         for (GroupDefinition group : groupsFromResource) {
1819             Optional<GroupDefinition> op = groupsAsList.stream()
1820                     .filter(p -> p.getName().equalsIgnoreCase(group.getName())).findAny();
1821             if (!op.isPresent() && (group.getArtifacts() == null || group.getArtifacts().isEmpty())) {
1822                 groupsToDelete.add(group);
1823             }
1824         }
1825     }
1826
1827     protected List<GroupDefinition> updateGroupsMembersUsingResource(Map<String, GroupDefinition> groups, Service component) {
1828
1829         List<GroupDefinition> result = new ArrayList<>();
1830         List<ComponentInstance> componentInstances = component.getComponentInstances();
1831
1832         if (groups != null) {
1833             Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies = validateCyclicGroupsDependencies(groups);
1834             if (validateCyclicGroupsDependencies.isRight()) {
1835                 throw new ComponentException(validateCyclicGroupsDependencies.right().value());
1836             }
1837             for (Map.Entry<String, GroupDefinition> entry : groups.entrySet()) {
1838                 String groupName = entry.getKey();
1839                 GroupDefinition groupDefinition = entry.getValue();
1840                 GroupDefinition updatedGroupDefinition = new GroupDefinition(groupDefinition);
1841                 updatedGroupDefinition.setMembers(null);
1842                 Map<String, String> members = groupDefinition.getMembers();
1843                 if (members != null) {
1844                     updateGroupMembers(groups, updatedGroupDefinition, component, componentInstances, groupName, members);
1845                 }
1846                 result.add(updatedGroupDefinition);
1847             }
1848         }
1849         return result;
1850     }
1851
1852     public void updateGroupMembers(Map<String, GroupDefinition> groups, GroupDefinition updatedGroupDefinition, Service component, List<ComponentInstance> componentInstances, String groupName, Map<String, String> members) {
1853         Set<String> compInstancesNames = members.keySet();
1854
1855         if (CollectionUtils.isEmpty(componentInstances)) {
1856             String membersAstString = compInstancesNames.stream().collect(joining(","));
1857             log.debug("The members: {}, in group: {}, cannot be found in component {}. There are no component instances.",
1858                     membersAstString, groupName, component.getNormalizedName());
1859             throw new ComponentException(componentsUtils.getResponseFormat(
1860                     ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName,
1861                     component.getNormalizedName(), getComponentTypeForResponse(component)));
1862         }
1863         // Find all component instances with the member names
1864         Map<String, String> memberNames = componentInstances.stream()
1865                 .collect(toMap(ComponentInstance::getName, ComponentInstance::getUniqueId));
1866         memberNames.putAll(groups.keySet().stream().collect(toMap(g -> g, g -> "")));
1867         Map<String, String> relevantInstances = memberNames.entrySet().stream()
1868                 .filter(n -> compInstancesNames.contains(n.getKey()))
1869                 .collect(toMap(Map.Entry::getKey, Map.Entry::getValue));
1870
1871         if (relevantInstances == null || relevantInstances.size() != compInstancesNames.size()) {
1872
1873             List<String> foundMembers = new ArrayList<>();
1874             if (relevantInstances != null) {
1875                 foundMembers = relevantInstances.keySet().stream().collect(toList());
1876             }
1877             compInstancesNames.removeAll(foundMembers);
1878             String membersAstString = compInstancesNames.stream().collect(joining(","));
1879             log.debug("The members: {}, in group: {}, cannot be found in component: {}", membersAstString,
1880                     groupName, component.getNormalizedName());
1881             throw new ComponentException(componentsUtils.getResponseFormat(
1882                     ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName,
1883                     component.getNormalizedName(), getComponentTypeForResponse(component)));
1884         }
1885         updatedGroupDefinition.setMembers(relevantInstances);
1886     }
1887
1888     public Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies(Map<String, GroupDefinition> allGroups) {
1889
1890         Either<Boolean, ResponseFormat> result = Either.left(true);
1891         try {
1892             Iterator<Map.Entry<String, GroupDefinition>> allGroupsItr = allGroups.entrySet().iterator();
1893             while (allGroupsItr.hasNext() && result.isLeft()) {
1894                 Map.Entry<String, GroupDefinition> groupAEntry = allGroupsItr.next();
1895                 // Fetches a group member A
1896                 String groupAName = groupAEntry.getKey();
1897                 // Finds all group members in group A
1898                 Set<String> allGroupAMembersNames = new HashSet<>();
1899                 fillAllGroupMemebersRecursivly(groupAEntry.getKey(), allGroups, allGroupAMembersNames);
1900                 // If A is a group member of itself found cyclic dependency
1901                 if (allGroupAMembersNames.contains(groupAName)) {
1902                     ResponseFormat responseFormat = componentsUtils
1903                             .getResponseFormat(ActionStatus.GROUP_HAS_CYCLIC_DEPENDENCY, groupAName);
1904                     result = Either.right(responseFormat);
1905                 }
1906             }
1907         } catch (Exception e) {
1908             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1909             result = Either.right(responseFormat);
1910             log.debug("Exception occured when validateCyclicGroupsDependencies, error is:{}", e.getMessage(), e);
1911         }
1912         return result;
1913     }
1914
1915     protected void fillAllGroupMemebersRecursivly(String groupName, Map<String, GroupDefinition> allGroups,
1916                                                 Set<String> allGroupMembers) {
1917
1918         // Found Cyclic dependency
1919         if (isfillGroupMemebersRecursivlyStopCondition(groupName, allGroups, allGroupMembers)) {
1920             return;
1921         }
1922         GroupDefinition groupDefinition = allGroups.get(groupName);
1923         // All Members Of Current Group Resource Instances & Other Groups
1924         Set<String> currGroupMembers = groupDefinition.getMembers().keySet();
1925         // Filtered Members Of Current Group containing only members which
1926         // are groups
1927         List<String> currGroupFilteredMembers = currGroupMembers.stream().
1928                 // Keep Only Elements of type group and not Resource Instances
1929                         filter(allGroups::containsKey).
1930                 // Add Filtered Elements to main Set
1931                         peek(allGroupMembers::add).
1932                 // Collect results
1933                         collect(toList());
1934
1935         // Recursively call the method for all the filtered group members
1936         for (String innerGroupName : currGroupFilteredMembers) {
1937             fillAllGroupMemebersRecursivly(innerGroupName, allGroups, allGroupMembers);
1938         }
1939     }
1940
1941     public ImmutablePair<Resource, ActionStatus> createResourceFromNodeType(String nodeTypeYaml, UploadResourceInfo resourceMetaData, User creator, boolean isInTransaction, boolean needLock,
1942                                                                             Map<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
1943                                                                             List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo,
1944                                                                             String nodeName, boolean isNested) {
1945
1946         LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
1947                 LifecycleChangeInfoWithAction.LifecycleChanceActionEnum.CREATE_FROM_CSAR);
1948
1949         Function<Resource, Boolean> validator = resource -> validateResourceCreationFromNodeType(
1950                 resource, creator);
1951
1952         return resourceImportManager.importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator,
1953                 lifecycleChangeInfo, isInTransaction, true, needLock, nodeTypeArtifactsToHandle,
1954                 nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeName, isNested);
1955     }
1956
1957     public ImmutablePair<Resource, ActionStatus> createNodeTypeResourceFromYaml(
1958             String yamlName, Map.Entry<String, Object> nodeNameValue, User user, Map<String, Object> mapToConvert,
1959             Service resourceVf, boolean needLock,
1960             Map<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
1961             List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo,
1962             boolean isNested) {
1963
1964         UploadResourceInfo resourceMetaData = fillResourceMetadata(yamlName, resourceVf, nodeNameValue.getKey(), user);
1965
1966         String singleVfcYaml = buildNodeTypeYaml(nodeNameValue, mapToConvert,
1967                 resourceMetaData.getResourceType(), csarInfo);
1968         user = serviceBusinessLogic.validateUser(user, "CheckIn Resource", resourceVf, AuditingActionEnum.CHECKIN_RESOURCE, true);
1969         return createResourceFromNodeType(singleVfcYaml, resourceMetaData, user, true, needLock,
1970                 nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo,
1971                 nodeNameValue.getKey(), isNested);
1972     }
1973
1974     protected UploadResourceInfo fillResourceMetadata(String yamlName, Service resourceVf,
1975                                                     String nodeName, User user) {
1976         UploadResourceInfo resourceMetaData = new UploadResourceInfo();
1977
1978         // validate nodetype name prefix
1979         if (!nodeName.startsWith(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX)) {
1980             log.debug("invalid nodeName:{} does not start with {}.", nodeName,
1981                     Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
1982             throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE,
1983                     yamlName, resourceMetaData.getName(), nodeName);
1984         }
1985
1986         String actualName = this.getNodeTypeActualName(nodeName);
1987         String namePrefix = nodeName.replace(actualName, "");
1988         String resourceType = namePrefix.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1989
1990         // if we import from csar, the node_type name can be
1991         // org.openecomp.resource.abstract.node_name - in this case we always
1992         // create a vfc
1993         if (resourceType.equals(Constants.ABSTRACT)) {
1994             resourceType = ResourceTypeEnum.VFC.name().toLowerCase();
1995         }
1996         // validating type
1997         if (!ResourceTypeEnum.containsName(resourceType.toUpperCase())) {
1998             log.debug("invalid resourceType:{} the type is not one of the valide types:{}.", resourceType.toUpperCase(),
1999                     ResourceTypeEnum.values());
2000             throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE,
2001                     yamlName, resourceMetaData.getName(), nodeName);
2002         }
2003
2004         // Setting name
2005         resourceMetaData.setName(resourceVf.getSystemName() + actualName);
2006
2007         // Setting type from name
2008         String type = resourceType.toUpperCase();
2009         resourceMetaData.setResourceType(type);
2010
2011         resourceMetaData.setDescription(ImportUtils.Constants.INNER_VFC_DESCRIPTION);
2012         resourceMetaData.setIcon(ImportUtils.Constants.DEFAULT_ICON);
2013         resourceMetaData.setContactId(user.getUserId());
2014
2015         // Setting tag
2016         List<String> tags = new ArrayList<>();
2017         tags.add(resourceMetaData.getName());
2018         resourceMetaData.setTags(tags);
2019
2020         // Setting category
2021         CategoryDefinition category = new CategoryDefinition();
2022         category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
2023         SubCategoryDefinition subCategory = new SubCategoryDefinition();
2024         subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
2025         category.addSubCategory(subCategory);
2026         List<CategoryDefinition> categories = new ArrayList<>();
2027         categories.add(category);
2028         resourceMetaData.setCategories(categories);
2029
2030         return resourceMetaData;
2031     }
2032
2033
2034     public Resource propagateStateToCertified(User user, Resource resource,
2035                                               LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock,
2036                                               boolean forceCertificationAllowed) {
2037
2038         Either<Resource, ResponseFormat> result = null;
2039         try {
2040             if (resource.getLifecycleState() != LifecycleStateEnum.CERTIFIED && forceCertificationAllowed
2041                     && lifecycleBusinessLogic.isFirstCertification(resource.getVersion())) {
2042                 nodeForceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock);
2043             }
2044             if (resource.getLifecycleState() == LifecycleStateEnum.CERTIFIED) {
2045                 Either<ArtifactDefinition, Operation> eitherPopulated = serviceBusinessLogic.populateToscaArtifacts(
2046                         resource, user, false, inTransaction, needLock);
2047                 return resource;
2048             }
2049             return nodeFullCertification(resource.getUniqueId(), user, lifecycleChangeInfo, inTransaction, needLock);
2050         } catch (Exception e) {
2051             log.debug("The exception has occurred upon certification of resource {}. ", resource.getName(), e);
2052             throw e;
2053         } finally {
2054             if (result == null || result.isRight()) {
2055                 BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
2056                 if (!inTransaction) {
2057                     serviceBusinessLogic.janusGraphDao.rollback();
2058                 }
2059             } else if (!inTransaction) {
2060                 serviceBusinessLogic.janusGraphDao.commit();
2061             }
2062         }
2063     }
2064
2065     public Resource buildValidComplexVfc(CsarInfo csarInfo, String nodeName,
2066                                           Map<String, NodeTypeInfo> nodesInfo) {
2067
2068         Resource complexVfc = buildComplexVfcMetadata(csarInfo, nodeName, nodesInfo);
2069         log.debug("************* Going to validate complex VFC from yaml {}", complexVfc.getName());
2070         csarInfo.addNodeToQueue(nodeName);
2071         return validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(),
2072                 AuditingActionEnum.IMPORT_RESOURCE, true, csarInfo);
2073     }
2074
2075     public Resource updateGroupsOnResource(Resource resource, Map<String, GroupDefinition> groups) {
2076         if (MapUtils.isEmpty(groups)) {
2077             return resource;
2078         } else {
2079             updateOrCreateGroups(resource, groups);
2080         }
2081         Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade
2082                 .getToscaElement(resource.getUniqueId());
2083         if (updatedResource.isRight()) {
2084             throw new ComponentException(componentsUtils.getResponseFormatByResource(
2085                     componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource));
2086         }
2087         return updatedResource.left().value();
2088     }
2089
2090     protected void setInformationalArtifactsPlaceHolder(Resource resource, User user) {
2091         Map<String, ArtifactDefinition> artifactMap = resource.getArtifacts();
2092         if (artifactMap == null) {
2093             artifactMap = new HashMap<>();
2094         }
2095         String resourceUniqueId = resource.getUniqueId();
2096         List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration()
2097                 .getExcludeResourceCategory();
2098         List<String> exludeResourceType = ConfigurationManager.getConfigurationManager().getConfiguration()
2099                 .getExcludeResourceType();
2100         Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager()
2101                 .getConfiguration().getInformationalResourceArtifacts();
2102         List<CategoryDefinition> categories = resource.getCategories();
2103         boolean isCreateArtifact = true;
2104         if (exludeResourceCategory != null) {
2105             String category = categories.get(0).getName();
2106             isCreateArtifact = exludeResourceCategory.stream().noneMatch(e->e.equalsIgnoreCase(category));
2107         }
2108         if (isCreateArtifact && exludeResourceType != null) {
2109             String resourceType = resource.getResourceType().name();
2110             isCreateArtifact = exludeResourceType.stream().noneMatch(e->e.equalsIgnoreCase(resourceType));
2111         }
2112         if (informationalResourceArtifacts != null && isCreateArtifact) {
2113             Set<String> keys = informationalResourceArtifacts.keySet();
2114             for (String informationalResourceArtifactName : keys) {
2115                 Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts
2116                         .get(informationalResourceArtifactName);
2117                 ArtifactDefinition artifactDefinition = serviceBusinessLogic.artifactsBusinessLogic.createArtifactPlaceHolderInfo(
2118                         resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user,
2119                         ArtifactGroupTypeEnum.INFORMATIONAL);
2120                 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
2121
2122             }
2123         }
2124         resource.setArtifacts(artifactMap);
2125     }
2126
2127     public void rollback(boolean inTransaction, Resource resource, List<ArtifactDefinition> createdArtifacts, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts) {
2128         if(!inTransaction) {
2129             serviceBusinessLogic.janusGraphDao.rollback();
2130         }
2131         if (isNotEmpty(createdArtifacts) && isNotEmpty(nodeTypesNewCreatedArtifacts)) {
2132             createdArtifacts.addAll(nodeTypesNewCreatedArtifacts);
2133             log.debug("Found {} newly created artifacts to deleted, the component name: {}",createdArtifacts.size(), resource.getName());
2134         }
2135     }
2136
2137     public void createArtifactsPlaceHolderData(Resource resource, User user) {
2138         setInformationalArtifactsPlaceHolder(resource, user);
2139         setDeploymentArtifactsPlaceHolder(resource, user);
2140         serviceBusinessLogic.setToscaArtifactsPlaceHolders(resource, user);
2141     }
2142
2143     public void handleGroupsProperties(Service service, Map<String, GroupDefinition> groups) {
2144         List<InputDefinition> inputs = service.getInputs();
2145         if (MapUtils.isNotEmpty(groups)) {
2146             groups.values()
2147                     .stream()
2148                     .filter(g -> isNotEmpty(g.getProperties()))
2149                     .flatMap(g -> g.getProperties().stream())
2150                     .forEach(p -> handleGetInputs(p, inputs));
2151         }
2152     }
2153
2154     public void handleGroupsProperties(Resource resource, Map<String, GroupDefinition> groups) {
2155         List<InputDefinition> inputs = resource.getInputs();
2156         if (MapUtils.isNotEmpty(groups)) {
2157             groups.values()
2158                     .stream()
2159                     .filter(g -> isNotEmpty(g.getProperties()))
2160                     .flatMap(g -> g.getProperties().stream())
2161                     .forEach(p -> handleGetInputs(p, inputs));
2162         }
2163     }
2164
2165     protected void handleGetInputs(PropertyDataDefinition property, List<InputDefinition> inputs) {
2166         if (isNotEmpty(property.getGetInputValues())) {
2167             if (inputs == null || inputs.isEmpty()) {
2168                 log.debug("Failed to add property {} to group. Inputs list is empty ", property);
2169                 serviceBusinessLogic.rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, property.getGetInputValues()
2170                         .stream()
2171                         .map(GetInputValueDataDefinition::getInputName)
2172                         .collect(toList()).toString());
2173             }
2174             ListIterator<GetInputValueDataDefinition> getInputValuesIter = property.getGetInputValues().listIterator();
2175             while (getInputValuesIter.hasNext()) {
2176                 GetInputValueDataDefinition getInput = getInputValuesIter.next();
2177                 InputDefinition input = findInputByName(inputs, getInput);
2178                 getInput.setInputId(input.getUniqueId());
2179                 if (getInput.getGetInputIndex() != null) {
2180                     GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
2181                     input = findInputByName(inputs, getInputIndex);
2182                     getInputIndex.setInputId(input.getUniqueId());
2183                     getInputValuesIter.add(getInputIndex);
2184                 }
2185             }
2186         }
2187     }
2188
2189     public InputDefinition findInputByName(List<InputDefinition> inputs, GetInputValueDataDefinition getInput) {
2190         Optional<InputDefinition> inputOpt = inputs.stream()
2191                 .filter(p -> p.getName().equals(getInput.getInputName()))
2192                 .findFirst();
2193         if (!inputOpt.isPresent()) {
2194             log.debug("#findInputByName - Failed to find the input {} ", getInput.getInputName());
2195             serviceBusinessLogic.rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, getInput.getInputName());
2196         }
2197         return inputOpt.get();
2198     }
2199
2200     public void associateComponentInstancePropertiesToComponent(String yamlName, Resource resource, Map<String, List<ComponentInstanceProperty>> instProperties) {
2201         try {
2202             Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade
2203                     .associateComponentInstancePropertiesToComponent(instProperties, resource.getUniqueId());
2204             if (addPropToInst.isRight()) {
2205                 log.debug("failed to associate properties of resource {} status is {}", resource.getUniqueId(),
2206                         addPropToInst.right().value());
2207                 throw new ComponentException(componentsUtils.getResponseFormat(
2208                         componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName));
2209             }
2210         } catch (Exception e) {
2211             log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage());
2212             throw new ComponentException(ActionStatus.GENERAL_ERROR);
2213         }
2214     }
2215
2216     public void associateComponentInstanceInputsToComponent(String yamlName, Resource resource, Map<String, List<ComponentInstanceInput>> instInputs) {
2217         if (MapUtils.isNotEmpty(instInputs)) {
2218             Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addInputToInst = toscaOperationFacade
2219                     .associateComponentInstanceInputsToComponent(instInputs, resource.getUniqueId());
2220             if (addInputToInst.isRight()) {
2221                 log.debug("failed to associate inputs value of resource {} status is {}", resource.getUniqueId(),
2222                         addInputToInst.right().value());
2223                 throw new ComponentException(componentsUtils.getResponseFormat(
2224                         componentsUtils.convertFromStorageResponse(addInputToInst.right().value()), yamlName));
2225             }
2226         }
2227     }
2228
2229     public void associateDeploymentArtifactsToInstances(User user, String yamlName, Resource resource, Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts) {
2230         StorageOperationStatus addArtToInst = toscaOperationFacade
2231                 .associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource, user);
2232         if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2233             log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2234             throw new ComponentException(componentsUtils
2235                     .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2236         }
2237     }
2238
2239     public void associateArtifactsToInstances(String yamlName, Resource resource, Map<String, Map<String, ArtifactDefinition>> instArtifacts) {
2240
2241         StorageOperationStatus addArtToInst;
2242
2243         addArtToInst = toscaOperationFacade.associateArtifactsToInstances(instArtifacts, resource);
2244         if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2245             log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2246             throw new ComponentException(componentsUtils
2247                     .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2248         }
2249     }
2250
2251     public void associateOrAddCalculatedCapReq(String yamlName, Resource resource, Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities, Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements) {
2252
2253         StorageOperationStatus addArtToInst;
2254         addArtToInst = toscaOperationFacade.associateOrAddCalculatedCapReq(instCapabilities, instRequirements,
2255                 resource);
2256         if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2257             log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(),
2258                     addArtToInst);
2259             throw new ComponentException(componentsUtils
2260                     .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2261         }
2262     }
2263
2264     public void associateInstAttributeToComponentToInstances(String yamlName, Resource resource, Map<String, List<AttributeDataDefinition>> instAttributes) {
2265
2266         StorageOperationStatus addArtToInst;
2267         addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes,
2268                 resource);
2269         if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2270             log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(),
2271                     addArtToInst);
2272             throw new ComponentException(componentsUtils
2273                     .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2274         }
2275     }
2276
2277     public Resource getResourceAfterCreateRelations(Resource resource) {
2278         ComponentParametersView parametersView = getComponentFilterAfterCreateRelations();
2279         Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade
2280                 .getToscaElement(resource.getUniqueId(), parametersView);
2281
2282         if (eitherGetResource.isRight()) {
2283             throwComponentExceptionByResource(eitherGetResource.right().value(),resource);
2284         }
2285         return eitherGetResource.left().value();
2286     }
2287
2288     public Resource throwComponentExceptionByResource(StorageOperationStatus status, Resource resource) {
2289         ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
2290                 componentsUtils.convertFromStorageResponse(status), resource);
2291         throw new ComponentException(responseFormat);
2292     }
2293
2294     public void setCapabilityNamesTypes(Map<String, List<CapabilityDefinition>> originCapabilities,
2295                                          Map<String, List<UploadCapInfo>> uploadedCapabilities) {
2296         for (Map.Entry<String, List<UploadCapInfo>> currEntry : uploadedCapabilities.entrySet()) {
2297             if (originCapabilities.containsKey(currEntry.getKey())) {
2298                 currEntry.getValue().stream().forEach(cap -> cap.setType(currEntry.getKey()));
2299             }
2300         }
2301         for (Map.Entry<String, List<CapabilityDefinition>> capabilities : originCapabilities.entrySet()) {
2302             capabilities.getValue().stream().forEach(cap -> {
2303                 if (uploadedCapabilities.containsKey(cap.getName())) {
2304                     uploadedCapabilities.get(cap.getName()).stream().forEach(c -> {
2305                         c.setName(cap.getName());
2306                         c.setType(cap.getType());
2307                     });
2308                 }
2309             });
2310         }
2311     }
2312
2313     public Map<String, List<CapabilityDefinition>> getValidComponentInstanceCapabilities(
2314             String resourceId, Map<String, List<CapabilityDefinition>> defaultCapabilities,
2315             Map<String, List<UploadCapInfo>> uploadedCapabilities) {
2316
2317         Map<String, List<CapabilityDefinition>> validCapabilitiesMap = new HashMap<>();
2318         uploadedCapabilities.forEach((k,v)->addValidComponentInstanceCapabilities(k,v,resourceId,defaultCapabilities,validCapabilitiesMap));
2319         return validCapabilitiesMap;
2320     }
2321
2322     public void associateComponentInstanceInputsToComponent(String yamlName, Service service, Map<String, List<ComponentInstanceInput>> instInputs) {
2323         if (MapUtils.isNotEmpty(instInputs)) {
2324             Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addInputToInst = toscaOperationFacade
2325                     .associateComponentInstanceInputsToComponent(instInputs, service.getUniqueId());
2326             if (addInputToInst.isRight()) {
2327                 log.debug("failed to associate inputs value of resource {} status is {}", service.getUniqueId(),
2328                         addInputToInst.right().value());
2329                 throw new ComponentException(componentsUtils.getResponseFormat(
2330                         componentsUtils.convertFromStorageResponse(addInputToInst.right().value()), yamlName));
2331             }
2332         }
2333     }
2334
2335     public void associateComponentInstancePropertiesToComponent(String yamlName, Service service, Map<String, List<ComponentInstanceProperty>> instProperties) {
2336         Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade
2337                 .associateComponentInstancePropertiesToComponent(instProperties, service.getUniqueId());
2338         if (addPropToInst.isRight()) {
2339             throw new ComponentException(componentsUtils.getResponseFormat(
2340                     componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName));
2341         }
2342     }
2343
2344     public void associateDeploymentArtifactsToInstances(User user, String yamlName, Service resource, Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts) {
2345         StorageOperationStatus addArtToInst = toscaOperationFacade
2346                 .associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource, user);
2347         if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2348             log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2349             throw new ComponentException(componentsUtils
2350                     .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2351         }
2352     }
2353
2354     public void associateArtifactsToInstances(String yamlName, Service resource, Map<String, Map<String, ArtifactDefinition>> instArtifacts) {
2355         StorageOperationStatus addArtToInst;
2356
2357         addArtToInst = toscaOperationFacade.associateArtifactsToInstances(instArtifacts, resource);
2358         if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2359             log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2360             throw new ComponentException(componentsUtils
2361                     .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2362         }
2363     }
2364
2365     public void associateOrAddCalculatedCapReq(String yamlName, Service resource, Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities, Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements) {
2366         StorageOperationStatus addArtToInst;
2367         addArtToInst = toscaOperationFacade.associateOrAddCalculatedCapReq(instCapabilities, instRequirements,
2368                 resource);
2369         log.debug("enter associateOrAddCalculatedCapReq,get instCapabilities:{},get instRequirements:{}",
2370                 instCapabilities, instRequirements);
2371         if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2372             log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(),
2373                     addArtToInst);
2374             throw new ComponentException(componentsUtils
2375                     .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2376         }
2377     }
2378
2379     public void associateInstAttributeToComponentToInstances(String yamlName, Service resource, Map<String, List<AttributeDataDefinition>> instAttributes) {
2380         StorageOperationStatus addArtToInst;
2381
2382         addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes,
2383                 resource);
2384         if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2385             log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(),
2386                     addArtToInst);
2387             throw new ComponentException(componentsUtils
2388                     .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2389         }
2390     }
2391
2392     public void associateRequirementsToService(String yamlName, Service resource, Map<String, ListRequirementDataDefinition> requirements) {
2393         StorageOperationStatus addReqToService;
2394         addReqToService = toscaOperationFacade.associateRequirementsToService(requirements,
2395                 resource.getUniqueId());
2396         if (addReqToService != StorageOperationStatus.OK && addReqToService != StorageOperationStatus.NOT_FOUND) {
2397             log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(),
2398                     addReqToService);
2399             throw new ComponentException(componentsUtils
2400                     .getResponseFormat(componentsUtils.convertFromStorageResponse(addReqToService), yamlName));
2401         }
2402     }
2403
2404     public void associateCapabilitiesToService(String yamlName, Service resource, Map<String,ListCapabilityDataDefinition> capabilities) {
2405         StorageOperationStatus addCapToService;
2406         addCapToService = toscaOperationFacade.associateCapabilitiesToService(capabilities,
2407                 resource.getUniqueId());
2408         if (addCapToService != StorageOperationStatus.OK && addCapToService != StorageOperationStatus.NOT_FOUND) {
2409             log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(),
2410                     addCapToService);
2411             throw new ComponentException(componentsUtils
2412                     .getResponseFormat(componentsUtils.convertFromStorageResponse(addCapToService), yamlName));
2413         }
2414     }
2415
2416     public void associateResourceInstances(String yamlName, Service service, List<RequirementCapabilityRelDef> relations) {
2417         Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> relationsEither = toscaOperationFacade.associateResourceInstances(service, service.getUniqueId(), relations);
2418
2419         if (relationsEither.isRight() && relationsEither.right().value() != StorageOperationStatus.NOT_FOUND) {
2420             StorageOperationStatus status = relationsEither.right().value();
2421             log.debug("failed to associate instances of service {} status is {}", service.getUniqueId(),
2422                     status);
2423             throw new ComponentException(componentsUtils
2424                     .getResponseFormat(componentsUtils.convertFromStorageResponse(status), yamlName));
2425         }
2426     }
2427
2428     public void addCapabilities(Map<String, List<CapabilityDefinition>> originCapabilities, String type, List<CapabilityDefinition> capabilities) {
2429         List<CapabilityDefinition> list = capabilities.stream().map(CapabilityDefinition::new)
2430                 .collect(toList());
2431         originCapabilities.put(type, list);
2432     }
2433
2434     public void addCapabilitiesProperties(Map<String, Map<String, UploadPropInfo>> newPropertiesMap, List<UploadCapInfo> capabilities) {
2435         for (UploadCapInfo capability : capabilities) {
2436             if (isNotEmpty(capability.getProperties())) {
2437                 newPropertiesMap.put(capability.getName(), capability.getProperties().stream()
2438                         .collect(toMap(UploadInfo::getName, p -> p)));
2439             }
2440         }
2441     }
2442
2443     public Service getServiceWithGroups(String resourceId) {
2444
2445         ComponentParametersView filter = new ComponentParametersView();
2446         filter.setIgnoreGroups(false);
2447         Either<Service, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resourceId, filter);
2448         if (updatedResource.isRight()) {
2449             serviceBusinessLogic.rollbackWithException(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resourceId);
2450         }
2451         return updatedResource.left().value();
2452     }
2453
2454     public Resource getResourceWithGroups(String resourceId) {
2455
2456         ComponentParametersView filter = new ComponentParametersView();
2457         filter.setIgnoreGroups(false);
2458         Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resourceId, filter);
2459         if (updatedResource.isRight()) {
2460             serviceBusinessLogic.rollbackWithException(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resourceId);
2461         }
2462         return updatedResource.left().value();
2463     }
2464
2465     public void associateResourceInstances(String yamlName, Resource resource, List<RequirementCapabilityRelDef> relations) {
2466
2467         Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> relationsEither = toscaOperationFacade.associateResourceInstances(resource, resource.getUniqueId(), relations);
2468         if (relationsEither.isRight() && relationsEither.right().value() != StorageOperationStatus.NOT_FOUND) {
2469             StorageOperationStatus status = relationsEither.right().value();
2470             log.debug("failed to associate instances of resource {} status is {}", resource.getUniqueId(),
2471                     status);
2472             throw new ComponentException(componentsUtils
2473                     .getResponseFormat(componentsUtils.convertFromStorageResponse(status), yamlName));
2474         }
2475     }
2476
2477     public void addRelationsToRI(String yamlName, Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, List<ComponentInstance> componentInstancesList, List<RequirementCapabilityRelDef> relations) {
2478         for (Map.Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) {
2479             UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
2480             ComponentInstance currentCompInstance = null;
2481             for (ComponentInstance compInstance : componentInstancesList) {
2482
2483                 if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
2484                     currentCompInstance = compInstance;
2485                     break;
2486                 }
2487             }
2488             if (currentCompInstance == null) {
2489                 log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(),
2490                         resource.getUniqueId());
2491                 BeEcompErrorManager.getInstance().logInternalDataError(
2492                         COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE,
2493                         resource.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR);
2494                 ResponseFormat responseFormat = componentsUtils
2495                         .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2496                 throw new ComponentException(responseFormat);
2497             }
2498
2499             ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, resource, entry.getValue(), relations);
2500             if (addRelationToRiRes.getStatus() != 200) {
2501                 throw new ComponentException(addRelationToRiRes);
2502             }
2503         }
2504     }
2505
2506     protected ResponseFormat addRelationToRI(String yamlName, Resource resource,
2507                                            UploadComponentInstanceInfo nodesInfoValue, List<RequirementCapabilityRelDef> relations) {
2508         List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
2509         ComponentInstance currentCompInstance = null;
2510
2511         for (ComponentInstance compInstance : componentInstancesList) {
2512
2513             if (compInstance.getName().equals(nodesInfoValue.getName())) {
2514                 currentCompInstance = compInstance;
2515                 break;
2516             }
2517         }
2518         if (currentCompInstance == null) {
2519             log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, nodesInfoValue.getName(),
2520                     resource.getUniqueId());
2521             BeEcompErrorManager.getInstance().logInternalDataError(
2522                     COMPONENT_INSTANCE_WITH_NAME + nodesInfoValue.getName() + IN_RESOURCE,
2523                     resource.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR);
2524             return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE,
2525                     yamlName);
2526         }
2527         String resourceInstanceId = currentCompInstance.getUniqueId();
2528         Map<String, List<UploadReqInfo>> regMap = nodesInfoValue.getRequirements();
2529
2530         if (regMap != null) {
2531             Iterator<Map.Entry<String, List<UploadReqInfo>>> nodesRegValue = regMap.entrySet().iterator();
2532             while (nodesRegValue.hasNext()) {
2533                 Map.Entry<String, List<UploadReqInfo>> nodesRegInfoEntry = nodesRegValue.next();
2534                 List<UploadReqInfo> uploadRegInfoList = nodesRegInfoEntry.getValue();
2535                 for (UploadReqInfo uploadRegInfo : uploadRegInfoList) {
2536                     log.debug("Going to create  relation {}", uploadRegInfo.getName());
2537                     String regName = uploadRegInfo.getName();
2538                     RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef();
2539                     regCapRelDef.setFromNode(resourceInstanceId);
2540                     log.debug("try to find available requirement {} ", regName);
2541                     Either<RequirementDefinition, ResponseFormat> eitherReqStatus = findAviableRequiremen(regName,
2542                             yamlName, nodesInfoValue, currentCompInstance,
2543                             uploadRegInfo.getCapabilityName());
2544                     if (eitherReqStatus.isRight()) {
2545                         return eitherReqStatus.right().value();
2546                     }
2547
2548                     RequirementDefinition validReq = eitherReqStatus.left().value();
2549                     List<CapabilityRequirementRelationship> reqAndRelationshipPairList = regCapRelDef
2550                             .getRelationships();
2551                     if (reqAndRelationshipPairList == null) {
2552                         reqAndRelationshipPairList = new ArrayList<>();
2553                     }
2554                     RelationshipInfo reqAndRelationshipPair = new RelationshipInfo();
2555                     reqAndRelationshipPair.setRequirement(regName);
2556                     reqAndRelationshipPair.setRequirementOwnerId(validReq.getOwnerId());
2557                     reqAndRelationshipPair.setRequirementUid(validReq.getUniqueId());
2558                     RelationshipImpl relationship = new RelationshipImpl();
2559                     relationship.setType(validReq.getCapability());
2560                     reqAndRelationshipPair.setRelationships(relationship);
2561
2562                     ComponentInstance currentCapCompInstance = null;
2563                     for (ComponentInstance compInstance : componentInstancesList) {
2564                         if (compInstance.getName().equals(uploadRegInfo.getNode())) {
2565                             currentCapCompInstance = compInstance;
2566                             break;
2567                         }
2568                     }
2569
2570                     if (currentCapCompInstance == null) {
2571                         log.debug("The component instance  with name {} not found on resource {} ",
2572                                 uploadRegInfo.getNode(), resource.getUniqueId());
2573                         BeEcompErrorManager.getInstance().logInternalDataError(
2574                                 COMPONENT_INSTANCE_WITH_NAME + uploadRegInfo.getNode() + IN_RESOURCE,
2575                                 resource.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR);
2576                         return componentsUtils
2577                                 .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2578                     }
2579                     regCapRelDef.setToNode(currentCapCompInstance.getUniqueId());
2580                     log.debug("try to find aviable Capability  req name is {} ", validReq.getName());
2581                     CapabilityDefinition aviableCapForRel = findAvailableCapabilityByTypeOrName(validReq,
2582                             currentCapCompInstance, uploadRegInfo);
2583                     reqAndRelationshipPair.setCapability(aviableCapForRel.getName());
2584                     reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId());
2585                     reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId());
2586                     if (aviableCapForRel == null) {
2587                         BeEcompErrorManager.getInstance().logInternalDataError(
2588                                 "aviable capability was not found. req name is " + validReq.getName()
2589                                         + " component instance is " + currentCapCompInstance.getUniqueId(),
2590                                 resource.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR);
2591                         return componentsUtils
2592                                 .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2593                     }
2594                     CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship();
2595                     capReqRel.setRelation(reqAndRelationshipPair);
2596                     reqAndRelationshipPairList.add(capReqRel);
2597                     regCapRelDef.setRelationships(reqAndRelationshipPairList);
2598                     relations.add(regCapRelDef);
2599                 }
2600             }
2601         } else if (resource.getResourceType() != ResourceTypeEnum.VF) {
2602             return componentsUtils.getResponseFormat(ActionStatus.OK, yamlName);
2603         }
2604         return componentsUtils.getResponseFormat(ActionStatus.OK);
2605     }
2606
2607 }