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