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