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