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