Service import - Import unknown node types
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / components / impl / ServiceImportBusinessLogic.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 import static org.openecomp.sdc.be.components.impl.ImportUtils.findFirstToscaStringElement;
23 import static org.openecomp.sdc.be.components.impl.ImportUtils.getPropertyJsonStringValue;
24 import static org.openecomp.sdc.be.tosca.CsarUtils.VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN;
25
26 import com.google.gson.Gson;
27 import fj.data.Either;
28 import java.util.ArrayList;
29 import java.util.Collection;
30 import java.util.EnumMap;
31 import java.util.HashMap;
32 import java.util.HashSet;
33 import java.util.Iterator;
34 import java.util.List;
35 import java.util.Map;
36 import java.util.Map.Entry;
37 import java.util.Optional;
38 import java.util.Set;
39 import java.util.regex.Pattern;
40 import lombok.Getter;
41 import lombok.Setter;
42 import org.apache.commons.collections.CollectionUtils;
43 import org.apache.commons.collections.MapUtils;
44 import org.apache.commons.lang3.StringUtils;
45 import org.apache.commons.lang3.tuple.ImmutablePair;
46 import org.openecomp.sdc.be.components.csar.CsarArtifactsAndGroupsBusinessLogic;
47 import org.openecomp.sdc.be.components.csar.CsarBusinessLogic;
48 import org.openecomp.sdc.be.components.csar.CsarInfo;
49 import org.openecomp.sdc.be.components.csar.ServiceCsarInfo;
50 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum;
51 import org.openecomp.sdc.be.components.impl.artifact.ArtifactOperationInfo;
52 import org.openecomp.sdc.be.components.impl.exceptions.BusinessLogicException;
53 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
54 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
55 import org.openecomp.sdc.be.components.impl.utils.CINodeFilterUtils;
56 import org.openecomp.sdc.be.components.impl.utils.CreateServiceFromYamlParameter;
57 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
58 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
59 import org.openecomp.sdc.be.components.merge.resource.ResourceDataMergeBusinessLogic;
60 import org.openecomp.sdc.be.config.BeEcompErrorManager;
61 import org.openecomp.sdc.be.config.ConfigurationManager;
62 import org.openecomp.sdc.be.dao.api.ActionStatus;
63 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphDao;
64 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
65 import org.openecomp.sdc.be.datamodel.utils.ArtifactUtils;
66 import org.openecomp.sdc.be.datamodel.utils.UiComponentDataConverter;
67 import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
68 import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition;
69 import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition;
70 import org.openecomp.sdc.be.datatypes.elements.ListRequirementDataDefinition;
71 import org.openecomp.sdc.be.datatypes.elements.PolicyDataDefinition;
72 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
73 import org.openecomp.sdc.be.datatypes.elements.RequirementSubstitutionFilterPropertyDataDefinition;
74 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
75 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
76 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
77 import org.openecomp.sdc.be.impl.ComponentsUtils;
78 import org.openecomp.sdc.be.info.NodeTypeInfoToUpdateArtifacts;
79 import org.openecomp.sdc.be.model.ArtifactDefinition;
80 import org.openecomp.sdc.be.model.AttributeDefinition;
81 import org.openecomp.sdc.be.model.CapabilityDefinition;
82 import org.openecomp.sdc.be.model.CapabilityRequirementRelationship;
83 import org.openecomp.sdc.be.model.Component;
84 import org.openecomp.sdc.be.model.ComponentInstance;
85 import org.openecomp.sdc.be.model.ComponentInstanceInput;
86 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
87 import org.openecomp.sdc.be.model.ComponentParametersView;
88 import org.openecomp.sdc.be.model.DataTypeDefinition;
89 import org.openecomp.sdc.be.model.DistributionStatusEnum;
90 import org.openecomp.sdc.be.model.GroupDefinition;
91 import org.openecomp.sdc.be.model.InputDefinition;
92 import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
93 import org.openecomp.sdc.be.model.LifecycleStateEnum;
94 import org.openecomp.sdc.be.model.NodeTypeDefinition;
95 import org.openecomp.sdc.be.model.NodeTypeInfo;
96 import org.openecomp.sdc.be.model.NodeTypeMetadata;
97 import org.openecomp.sdc.be.model.NodeTypesMetadataList;
98 import org.openecomp.sdc.be.model.Operation;
99 import org.openecomp.sdc.be.model.OutputDefinition;
100 import org.openecomp.sdc.be.model.ParsedToscaYamlInfo;
101 import org.openecomp.sdc.be.model.PolicyDefinition;
102 import org.openecomp.sdc.be.model.PropertyDefinition;
103 import org.openecomp.sdc.be.model.RelationshipImpl;
104 import org.openecomp.sdc.be.model.RelationshipInfo;
105 import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
106 import org.openecomp.sdc.be.model.RequirementDefinition;
107 import org.openecomp.sdc.be.model.Resource;
108 import org.openecomp.sdc.be.model.Service;
109 import org.openecomp.sdc.be.model.UploadAttributeInfo;
110 import org.openecomp.sdc.be.model.UploadComponentInstanceInfo;
111 import org.openecomp.sdc.be.model.UploadNodeFilterInfo;
112 import org.openecomp.sdc.be.model.UploadPropInfo;
113 import org.openecomp.sdc.be.model.UploadReqInfo;
114 import org.openecomp.sdc.be.model.UploadResourceInfo;
115 import org.openecomp.sdc.be.model.User;
116 import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
117 import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElement;
118 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade;
119 import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter;
120 import org.openecomp.sdc.be.model.operations.StorageException;
121 import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation;
122 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
123 import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
124 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
125 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
126 import org.openecomp.sdc.be.tosca.CsarUtils;
127 import org.openecomp.sdc.be.ui.model.OperationUi;
128 import org.openecomp.sdc.be.utils.TypeUtils;
129 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
130 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
131 import org.openecomp.sdc.common.api.Constants;
132 import org.openecomp.sdc.common.datastructure.Wrapper;
133 import org.openecomp.sdc.common.kpi.api.ASDCKpiApi;
134 import org.openecomp.sdc.common.log.wrappers.Logger;
135 import org.openecomp.sdc.common.util.ValidationUtils;
136 import org.openecomp.sdc.exception.ResponseFormat;
137 import org.springframework.beans.factory.annotation.Autowired;
138 import org.yaml.snakeyaml.Yaml;
139
140 @Getter
141 @Setter
142 @org.springframework.stereotype.Component("serviceImportBusinessLogic")
143 public class ServiceImportBusinessLogic {
144
145     protected static final String CREATE_RESOURCE = "Create Resource";
146     private static final String INITIAL_VERSION = "0.1";
147     private static final String IN_RESOURCE = " in resource {} ";
148     private static final String COMPONENT_INSTANCE_WITH_NAME = "component instance with name ";
149     private static final String COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE = "component instance with name {}  in resource {} ";
150     private static final String CERTIFICATION_ON_IMPORT = "certification on import";
151     private static final String VALIDATE_DERIVED_BEFORE_UPDATE = "validate derived before update";
152     private static final String PLACE_HOLDER_RESOURCE_TYPES = "validForResourceTypes";
153     private static final String CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES = "Create Resource - validateCapabilityTypesCreate";
154     private static final String CATEGORY_IS_EMPTY = "Resource category is empty";
155     private static final Logger log = Logger.getLogger(ServiceImportBusinessLogic.class);
156
157     private final ComponentsUtils componentsUtils;
158     private final ToscaOperationFacade toscaOperationFacade;
159     private final UiComponentDataConverter uiComponentDataConverter;
160     private final ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
161     private final ServiceBusinessLogic serviceBusinessLogic;
162     private final CsarBusinessLogic csarBusinessLogic;
163     private final CsarArtifactsAndGroupsBusinessLogic csarArtifactsAndGroupsBusinessLogic;
164     private final LifecycleBusinessLogic lifecycleBusinessLogic;
165     private final CompositionBusinessLogic compositionBusinessLogic;
166     private final ResourceDataMergeBusinessLogic resourceDataMergeBusinessLogic;
167     private final ServiceImportParseLogic serviceImportParseLogic;
168     private final ComponentNodeFilterBusinessLogic componentNodeFilterBusinessLogic;
169     private final GroupBusinessLogic groupBusinessLogic;
170     private final PolicyBusinessLogic policyBusinessLogic;
171     private final ResourceImportManager resourceImportManager;
172     private final JanusGraphDao janusGraphDao;
173     private final ArtifactsBusinessLogic artifactsBusinessLogic;
174     private final IGraphLockOperation graphLockOperation;
175     private final ToscaFunctionService toscaFunctionService;
176     private final PropertyOperation propertyOperation;
177     private final DataTypeBusinessLogic dataTypeBusinessLogic;
178     private ApplicationDataTypeCache applicationDataTypeCache;
179
180     public ServiceImportBusinessLogic(final GroupBusinessLogic groupBusinessLogic,
181                                       final ArtifactsBusinessLogic artifactsBusinessLogic,
182                                       final ComponentInstanceBusinessLogic componentInstanceBusinessLogic,
183                                       final UiComponentDataConverter uiComponentDataConverter, final ComponentsUtils componentsUtils,
184                                       final ToscaOperationFacade toscaOperationFacade, final ServiceBusinessLogic serviceBusinessLogic,
185                                       final CsarBusinessLogic csarBusinessLogic,
186                                       final CsarArtifactsAndGroupsBusinessLogic csarArtifactsAndGroupsBusinessLogic,
187                                       final LifecycleBusinessLogic lifecycleBusinessLogic, final CompositionBusinessLogic compositionBusinessLogic,
188                                       final ResourceDataMergeBusinessLogic resourceDataMergeBusinessLogic,
189                                       final ServiceImportParseLogic serviceImportParseLogic,
190                                       final ComponentNodeFilterBusinessLogic componentNodeFilterBusinessLogic,
191                                       final PolicyBusinessLogic policyBusinessLogic, final JanusGraphDao janusGraphDao,
192                                       final IGraphLockOperation graphLockOperation, final ToscaFunctionService toscaFunctionService,
193                                       final PropertyOperation propertyOperation, final DataTypeBusinessLogic dataTypeBusinessLogic,
194                                       ResourceImportManager resourceImportManager) {
195         this.resourceImportManager = resourceImportManager;
196         this.componentInstanceBusinessLogic = componentInstanceBusinessLogic;
197         this.uiComponentDataConverter = uiComponentDataConverter;
198         this.componentsUtils = componentsUtils;
199         this.toscaOperationFacade = toscaOperationFacade;
200         this.serviceBusinessLogic = serviceBusinessLogic;
201         this.csarBusinessLogic = csarBusinessLogic;
202         this.csarArtifactsAndGroupsBusinessLogic = csarArtifactsAndGroupsBusinessLogic;
203         this.lifecycleBusinessLogic = lifecycleBusinessLogic;
204         this.compositionBusinessLogic = compositionBusinessLogic;
205         this.resourceDataMergeBusinessLogic = resourceDataMergeBusinessLogic;
206         this.serviceImportParseLogic = serviceImportParseLogic;
207         this.componentNodeFilterBusinessLogic = componentNodeFilterBusinessLogic;
208         this.groupBusinessLogic = groupBusinessLogic;
209         this.policyBusinessLogic = policyBusinessLogic;
210         this.janusGraphDao = janusGraphDao;
211         this.artifactsBusinessLogic = artifactsBusinessLogic;
212         this.graphLockOperation = graphLockOperation;
213         this.toscaFunctionService = toscaFunctionService;
214         this.propertyOperation = propertyOperation;
215         this.dataTypeBusinessLogic = dataTypeBusinessLogic;
216     }
217
218     @Autowired
219     public void setApplicationDataTypeCache(ApplicationDataTypeCache applicationDataTypeCache) {
220         this.applicationDataTypeCache = applicationDataTypeCache;
221     }
222
223     public Service createService(Service service, AuditingActionEnum auditingAction, User user, Map<String, byte[]> csarUIPayload,
224                                  String payloadName) {
225         log.debug("enter createService");
226         service.setCreatorUserId(user.getUserId());
227         service.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
228         service.setVersion(INITIAL_VERSION);
229         service.setConformanceLevel(ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel());
230         service.setDistributionStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED);
231         try {
232             final var serviceBeforeCreate = serviceBusinessLogic.validateServiceBeforeCreate(service, user, auditingAction);
233             if (serviceBeforeCreate.isRight()) {
234                 throw new ComponentException(ActionStatus.GENERAL_ERROR);
235             }
236             log.debug("enter createService,validateServiceBeforeCreate success");
237             String csarUUID = payloadName == null ? service.getCsarUUID() : payloadName;
238             log.debug("enter createService,get csarUUID:{}", csarUUID);
239             csarBusinessLogic.validateCsarBeforeCreate(service, csarUUID);
240             log.debug("CsarUUID is {} - going to create resource from CSAR", csarUUID);
241             return createServiceFromCsar(service, user, csarUIPayload, csarUUID);
242         } catch (final ComponentException e) {
243             log.debug("Exception occurred when createService: {}", e.getMessage(), e);
244             throw e;
245         } catch (final Exception e) {
246             log.debug("Exception occurred when createService: {}", e.getMessage(), e);
247             throw new ComponentException(ActionStatus.GENERAL_ERROR);
248         }
249     }
250
251     protected Service createServiceFromCsar(Service service, User user, Map<String, byte[]> csarUIPayload, String csarUUID) {
252         log.trace("************* created successfully from YAML, resource TOSCA ");
253         try {
254             ServiceCsarInfo csarInfo = csarBusinessLogic.getCsarInfo(service, null, user, csarUIPayload, csarUUID);
255
256             final Map<String, Object> dataTypesToCreate = getDatatypesToCreate(service.getModel(), csarInfo);
257             if (MapUtils.isNotEmpty(dataTypesToCreate)) {
258                 dataTypeBusinessLogic.createDataTypeFromYaml(new Yaml().dump(dataTypesToCreate), service.getModel(), true);
259             }
260             final List<NodeTypeDefinition> nodeTypesToCreate = getNodeTypesToCreate(service.getModel(), csarInfo);
261             if (CollectionUtils.isNotEmpty(nodeTypesToCreate)) {
262                 createNodeTypes(nodeTypesToCreate, csarInfo);
263             }
264             Map<String, NodeTypeInfo> nodeTypesInfo = csarInfo.extractTypesInfo();
265             Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = serviceImportParseLogic
266                 .findNodeTypesArtifactsToHandle(nodeTypesInfo, csarInfo, service);
267             if (findNodeTypesArtifactsToHandleRes.isRight()) {
268                 log.debug("failed to find node types for update with artifacts during import csar {}. ", csarInfo.getCsarUUID());
269                 throw new ComponentException(findNodeTypesArtifactsToHandleRes.right().value());
270             }
271             return createServiceFromYaml(service, csarInfo.getMainTemplateContent(), csarInfo.getMainTemplateName(), nodeTypesInfo, csarInfo,
272                 findNodeTypesArtifactsToHandleRes.left().value(), true, false, null, user.getUserId());
273         } catch (final ComponentException e) {
274             log.debug("Exception occurred when createServiceFromCsar,error is:{}", e.getMessage(), e);
275             throw e;
276         } catch (final Exception e) {
277             log.debug("Exception occurred when createServiceFromCsar,error is:{}", e.getMessage(), e);
278             throw new ComponentException(ActionStatus.GENERAL_ERROR);
279         }
280     }
281
282     private Map<String, Object> getDatatypesToCreate(final String model, final CsarInfo csarInfo) {
283         final Map<String, Object> dataTypesToCreate = new HashMap<>();
284
285         for (final Entry<String, Object> dataTypeEntry : csarInfo.getDataTypes().entrySet()){
286             final Either<DataTypeDefinition, JanusGraphOperationStatus> result = applicationDataTypeCache.get(model, UniqueIdBuilder.buildDataTypeUid(model, dataTypeEntry.getKey()));
287             if (result.isRight() && result.right().value().equals(JanusGraphOperationStatus.NOT_FOUND)) {
288                 dataTypesToCreate.put(dataTypeEntry.getKey(), dataTypeEntry.getValue());
289                 log.info("Deploying unknown type " + dataTypeEntry.getKey() + " to model " + model + " from package " + csarInfo.getCsarUUID());
290             }
291         }
292         return dataTypesToCreate;
293     }
294
295     private void createNodeTypes(List<NodeTypeDefinition> nodeTypesToCreate, ServiceCsarInfo csarInfo) {
296         NodeTypesMetadataList nodeTypesMetadataList = new NodeTypesMetadataList();
297         List<NodeTypeMetadata> nodeTypeMetadataList = new ArrayList<>();
298
299         final Map<String, Object> allTypesToCreate = new HashMap<>();
300         nodeTypesToCreate.stream().forEach(nodeType -> {
301             allTypesToCreate.put(nodeType.getMappedNodeType().getKey(), nodeType.getMappedNodeType().getValue());
302             nodeTypeMetadataList.add(nodeType.getNodeTypeMetadata());
303         });
304
305         nodeTypesMetadataList.setNodeMetadataList(nodeTypeMetadataList);
306         resourceImportManager.importAllNormativeResource(allTypesToCreate, nodeTypesMetadataList, csarInfo.getModifier(), true, false);
307     }
308
309     private List<NodeTypeDefinition> getNodeTypesToCreate(final String model, final ServiceCsarInfo csarInfo) {
310         List<NodeTypeDefinition> namesOfNodeTypesToCreate = new ArrayList<>();
311
312         for (final NodeTypeDefinition nodeTypeDefinition : csarInfo.getNodeTypesUsed()) {
313             Either<Component, StorageOperationStatus> result = toscaOperationFacade
314                 .getLatestByToscaResourceName(nodeTypeDefinition.getMappedNodeType().getKey(), model);
315             if (result.isRight() && result.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
316                 namesOfNodeTypesToCreate.add(nodeTypeDefinition);
317             }
318         }
319         return namesOfNodeTypesToCreate;
320     }
321
322     protected Service createServiceFromYaml(Service service, String topologyTemplateYaml, String yamlName, Map<String, NodeTypeInfo> nodeTypesInfo,
323                                             CsarInfo csarInfo,
324                                             Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
325                                             boolean shouldLock, boolean inTransaction, String nodeName, final String userId)
326         throws BusinessLogicException {
327         List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
328         Service createdService;
329         CreateServiceFromYamlParameter csfyp = new CreateServiceFromYamlParameter();
330         try {
331             ParsedToscaYamlInfo parsedToscaYamlInfo = csarBusinessLogic
332                 .getParsedToscaYamlInfo(topologyTemplateYaml, yamlName, nodeTypesInfo, csarInfo, nodeName, service);
333             log.debug("#createResourceFromYaml - Going to create resource {} and RIs ", service.getName());
334             csfyp.setYamlName(yamlName);
335             csfyp.setParsedToscaYamlInfo(parsedToscaYamlInfo);
336             csfyp.setCreatedArtifacts(createdArtifacts);
337             csfyp.setTopologyTemplateYaml(topologyTemplateYaml);
338             csfyp.setNodeTypesInfo(nodeTypesInfo);
339             csfyp.setCsarInfo(csarInfo);
340             csfyp.setNodeName(nodeName);
341             createdService = createServiceAndRIsFromYaml(service, false, nodeTypesArtifactsToCreate, shouldLock, inTransaction, csfyp, userId);
342             log.debug("#createResourceFromYaml - The resource {} has been created ", service.getName());
343         } catch (ComponentException | BusinessLogicException e) {
344             log.debug("Create Service from yaml failed", e);
345             throw e;
346         } catch (StorageException e) {
347             log.debug("create Service From Yaml failed,get StorageException:{}", e);
348             throw e;
349         }
350         return createdService;
351     }
352
353     protected Service createServiceAndRIsFromYaml(Service service, boolean isNormative,
354                                                   Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
355                                                   boolean shouldLock, boolean inTransaction, CreateServiceFromYamlParameter csfyp,
356                                                   final String userId)
357         throws BusinessLogicException {
358         List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>();
359         String yamlName = csfyp.getYamlName();
360         ParsedToscaYamlInfo parsedToscaYamlInfo = csfyp.getParsedToscaYamlInfo();
361         List<ArtifactDefinition> createdArtifacts = csfyp.getCreatedArtifacts();
362         String topologyTemplateYaml = csfyp.getTopologyTemplateYaml();
363         Map<String, NodeTypeInfo> nodeTypesInfo = csfyp.getNodeTypesInfo();
364         CsarInfo csarInfo = csfyp.getCsarInfo();
365         String nodeName = csfyp.getNodeName();
366         if (shouldLock) {
367             Either<Boolean, ResponseFormat> lockResult = serviceBusinessLogic.lockComponentByName(service.getSystemName(), service, CREATE_RESOURCE);
368             if (lockResult.isRight()) {
369                 serviceImportParseLogic.rollback(inTransaction, service, createdArtifacts, nodeTypesNewCreatedArtifacts);
370                 throw new ComponentException(lockResult.right().value());
371             }
372             log.debug("name is locked {} status = {}", service.getSystemName(), lockResult);
373         }
374         try {
375             log.trace("************* Adding properties to service from interface yaml {}", yamlName);
376             Map<String, PropertyDefinition> properties = parsedToscaYamlInfo.getProperties();
377             if (properties != null && !properties.isEmpty()) {
378                 final List<PropertyDefinition> propertiesList = new ArrayList<>();
379                 properties.forEach((propertyName, propertyDefinition) -> {
380                     propertyDefinition.setName(propertyName);
381                     propertiesList.add(propertyDefinition);
382                 });
383                 service.setProperties(propertiesList);
384             }
385             log.trace("************* createResourceFromYaml before full create resource {}", yamlName);
386             service = serviceImportParseLogic.createServiceTransaction(service, csarInfo.getModifier(), isNormative);
387             log.trace("************* Going to add inputs from yaml {}", yamlName);
388             Map<String, InputDefinition> inputs = parsedToscaYamlInfo.getInputs();
389             service = serviceImportParseLogic.createInputsOnService(service, inputs);
390             log.trace("************* Finished to add inputs from yaml {}", yamlName);
391             ListDataDefinition<RequirementSubstitutionFilterPropertyDataDefinition> substitutionFilterProperties = parsedToscaYamlInfo.getSubstitutionFilterProperties();
392             service = serviceImportParseLogic.createSubstitutionFilterOnService(service, substitutionFilterProperties);
393             log.trace("************* Added Substitution filter from interface yaml {}", yamlName);
394             Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap = parsedToscaYamlInfo.getInstances();
395             log.trace("************* Going to create nodes, RI's and Relations  from yaml {}", yamlName);
396             service = createRIAndRelationsFromYaml(yamlName, service, uploadComponentInstanceInfoMap, topologyTemplateYaml,
397                 nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, nodeName);
398             log.trace("************* Finished to create nodes, RI and Relation  from yaml {}", yamlName);
399             log.trace("************* Going to add outputs from yaml {}", yamlName);
400             Map<String, OutputDefinition> outputs = parsedToscaYamlInfo.getOutputs();
401             service = serviceImportParseLogic.createOutputsOnService(service, outputs, userId);
402             log.trace("************* Finished to add outputs from yaml {}", yamlName);
403
404             Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes
405                 = groupBusinessLogic.validateUpdateVfGroupNames(parsedToscaYamlInfo.getGroups(), service.getSystemName());
406             if (validateUpdateVfGroupNamesRes.isRight()) {
407                 serviceImportParseLogic.rollback(inTransaction, service, createdArtifacts, nodeTypesNewCreatedArtifacts);
408                 throw new ComponentException(validateUpdateVfGroupNamesRes.right().value());
409             }
410             Map<String, GroupDefinition> groups;
411             log.trace("************* Going to add groups from yaml {}", yamlName);
412             if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
413                 groups = validateUpdateVfGroupNamesRes.left().value();
414             } else {
415                 groups = parsedToscaYamlInfo.getGroups();
416             }
417             Either<Service, ResponseFormat> createGroupsOnResource = createGroupsOnResource(service, groups);
418             if (createGroupsOnResource.isRight()) {
419                 serviceImportParseLogic.rollback(inTransaction, service, createdArtifacts, nodeTypesNewCreatedArtifacts);
420                 throw new ComponentException(createGroupsOnResource.right().value());
421             }
422             service = createGroupsOnResource.left().value();
423
424             Either<Service, ResponseFormat> createPoliciesOnResource = createPoliciesOnResource(service, parsedToscaYamlInfo.getPolicies());
425             if (createPoliciesOnResource.isRight()) {
426                 serviceImportParseLogic.rollback(inTransaction, service, createdArtifacts, nodeTypesNewCreatedArtifacts);
427                 throw new ComponentException(createPoliciesOnResource.right().value());
428             }
429             service = createPoliciesOnResource.left().value();
430             log.trace("************* Going to add artifacts from yaml {}", yamlName);
431             NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName, nodeTypesArtifactsToCreate);
432             Either<Service, ResponseFormat> createArtifactsEither = createOrUpdateArtifacts(ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE,
433                 createdArtifacts, yamlName, csarInfo, service, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
434             if (createArtifactsEither.isRight()) {
435                 serviceImportParseLogic.rollback(inTransaction, service, createdArtifacts, nodeTypesNewCreatedArtifacts);
436                 throw new ComponentException(createArtifactsEither.right().value());
437             }
438             service = serviceImportParseLogic.getServiceWithGroups(createArtifactsEither.left().value().getUniqueId());
439             ASDCKpiApi.countCreatedResourcesKPI();
440             return service;
441         } catch (ComponentException | StorageException | BusinessLogicException e) {
442             serviceImportParseLogic.rollback(inTransaction, service, createdArtifacts, nodeTypesNewCreatedArtifacts);
443             throw e;
444         } finally {
445             if (!inTransaction) {
446                 janusGraphDao.commit();
447             }
448             if (shouldLock) {
449                 graphLockOperation.unlockComponentByName(service.getSystemName(), service.getUniqueId(), NodeTypeEnum.Resource);
450             }
451         }
452     }
453
454     protected Either<Resource, ResponseFormat> createOrUpdateArtifacts(ArtifactsBusinessLogic.ArtifactOperationEnum operation,
455                                                                        List<ArtifactDefinition> createdArtifacts, String yamlFileName,
456                                                                        CsarInfo csarInfo, Resource preparedResource,
457                                                                        NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts,
458                                                                        boolean inTransaction, boolean shouldLock) {
459         String nodeName = nodeTypeInfoToUpdateArtifacts.getNodeName();
460         Resource resource = preparedResource;
461         Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = nodeTypeInfoToUpdateArtifacts
462             .getNodeTypesArtifactsToHandle();
463         if (preparedResource.getResourceType() == ResourceTypeEnum.VF) {
464             if (nodeName != null && nodeTypesArtifactsToHandle.get(nodeName) != null && !nodeTypesArtifactsToHandle.get(nodeName).isEmpty()) {
465                 Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = handleNodeTypeArtifacts(preparedResource,
466                     nodeTypesArtifactsToHandle.get(nodeName), createdArtifacts, csarInfo.getModifier(), inTransaction, true);
467                 if (handleNodeTypeArtifactsRes.isRight()) {
468                     return Either.right(handleNodeTypeArtifactsRes.right().value());
469                 }
470             }
471         } else {
472             Either<Resource, ResponseFormat> createdCsarArtifactsEither = handleVfCsarArtifacts(preparedResource, csarInfo, createdArtifacts,
473                 new ArtifactOperationInfo(false, false, operation), shouldLock, inTransaction);
474             log.trace("************* Finished to add artifacts from yaml {}", yamlFileName);
475             if (createdCsarArtifactsEither.isRight()) {
476                 return createdCsarArtifactsEither;
477             }
478             resource = createdCsarArtifactsEither.left().value();
479         }
480         return Either.left(resource);
481     }
482
483     protected Either<Resource, ResponseFormat> handleVfCsarArtifacts(Resource resource, CsarInfo csarInfo, List<ArtifactDefinition> createdArtifacts,
484                                                                      ArtifactOperationInfo artifactOperation, boolean shouldLock,
485                                                                      boolean inTransaction) {
486         if (csarInfo.getCsar() != null) {
487             createOrUpdateSingleNonMetaArtifactToComstants(resource, csarInfo, artifactOperation, shouldLock, inTransaction);
488             Either<Resource, ResponseFormat> eitherCreateResult = createOrUpdateNonMetaArtifacts(csarInfo, resource, createdArtifacts, shouldLock,
489                 inTransaction, artifactOperation);
490             if (eitherCreateResult.isRight()) {
491                 return Either.right(eitherCreateResult.right().value());
492             }
493             Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
494             if (eitherGerResource.isRight()) {
495                 ResponseFormat responseFormat = componentsUtils
496                     .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
497                 return Either.right(responseFormat);
498             }
499             resource = eitherGerResource.left().value();
500             Either<ImmutablePair<String, String>, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils
501                 .getArtifactsMeta(csarInfo.getCsar(), csarInfo.getCsarUUID(), componentsUtils);
502             if (artifacsMetaCsarStatus.isLeft()) {
503                 return getResourceResponseFormatEither(resource, csarInfo, createdArtifacts, artifactOperation, shouldLock, inTransaction,
504                     artifacsMetaCsarStatus);
505             } else {
506                 return csarArtifactsAndGroupsBusinessLogic.deleteVFModules(resource, csarInfo, shouldLock, inTransaction);
507             }
508         }
509         return Either.left(resource);
510     }
511
512     protected void createOrUpdateSingleNonMetaArtifactToComstants(Resource resource, CsarInfo csarInfo, ArtifactOperationInfo artifactOperation,
513                                                                   boolean shouldLock, boolean inTransaction) {
514         String vendorLicenseModelId = null;
515         String vfLicenseModelId = null;
516         if (artifactOperation.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE) {
517             Map<String, ArtifactDefinition> deploymentArtifactsMap = resource.getDeploymentArtifacts();
518             if (deploymentArtifactsMap != null && !deploymentArtifactsMap.isEmpty()) {
519                 for (Map.Entry<String, ArtifactDefinition> artifactEntry : deploymentArtifactsMap.entrySet()) {
520                     if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VENDOR_LICENSE_MODEL)) {
521                         vendorLicenseModelId = artifactEntry.getValue().getUniqueId();
522                     }
523                     if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VF_LICENSE_MODEL)) {
524                         vfLicenseModelId = artifactEntry.getValue().getUniqueId();
525                     }
526                 }
527             }
528         }
529         createOrUpdateSingleNonMetaArtifact(resource, csarInfo, CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL,
530             Constants.VENDOR_LICENSE_MODEL, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
531             Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME, Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId,
532             artifactOperation, null, true, shouldLock, inTransaction);
533         createOrUpdateSingleNonMetaArtifact(resource, csarInfo, CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL,
534             ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, Constants.VF_LICENSE_LABEL, Constants.VF_LICENSE_DISPLAY_NAME,
535             Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId, artifactOperation, null, true, shouldLock, inTransaction);
536     }
537
538     private Either<Resource, ResponseFormat> getResourceResponseFormatEither(Resource resource, CsarInfo csarInfo,
539                                                                              List<ArtifactDefinition> createdArtifacts,
540                                                                              ArtifactOperationInfo artifactOperation, boolean shouldLock,
541                                                                              boolean inTransaction,
542                                                                              Either<ImmutablePair<String, String>, ResponseFormat> artifacsMetaCsarStatus) {
543         try {
544             String artifactsFileName = artifacsMetaCsarStatus.left().value().getKey();
545             String artifactsContents = artifacsMetaCsarStatus.left().value().getValue();
546             Either<Resource, ResponseFormat> createArtifactsFromCsar;
547             if (ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) {
548                 createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic
549                     .createResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts);
550             } else {
551                 Either<Component, ResponseFormat> result = csarArtifactsAndGroupsBusinessLogic
552                     .updateResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock,
553                         inTransaction);
554                 if ((result.left().value() instanceof Resource) && result.isLeft()) {
555                     Resource service1 = (Resource) result.left().value();
556                     createArtifactsFromCsar = Either.left(service1);
557                 } else {
558                     createArtifactsFromCsar = Either.right(result.right().value());
559                 }
560             }
561             if (createArtifactsFromCsar.isRight()) {
562                 log.debug("Couldn't create artifacts from artifacts.meta");
563                 return Either.right(createArtifactsFromCsar.right().value());
564             }
565             return Either.left(createArtifactsFromCsar.left().value());
566         } catch (Exception e) {
567             log.debug("Exception occured in getResourceResponseFormatEither, message:{}", e.getMessage(), e);
568             return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
569         }
570     }
571
572     private <T extends Component> Either<T, ResponseFormat> createOrUpdateNonMetaArtifactsComp(CsarInfo csarInfo, T component,
573                                                                                                List<ArtifactDefinition> createdArtifacts,
574                                                                                                boolean shouldLock, boolean inTransaction,
575                                                                                                ArtifactOperationInfo artifactOperation) {
576         Either<T, ResponseFormat> resStatus = null;
577         Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
578         try {
579             Either<List<CsarUtils.NonMetaArtifactInfo>, String> artifactPathAndNameList = getValidArtifactNames(csarInfo, collectedWarningMessages);
580             if (artifactPathAndNameList.isRight()) {
581                 return Either.right(
582                     getComponentsUtils().getResponseFormatByArtifactId(ActionStatus.ARTIFACT_NAME_INVALID, artifactPathAndNameList.right().value()));
583             }
584             EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>> vfCsarArtifactsToHandle = null;
585             if (ArtifactsBusinessLogic.ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) {
586                 vfCsarArtifactsToHandle = new EnumMap<>(ArtifactsBusinessLogic.ArtifactOperationEnum.class);
587                 vfCsarArtifactsToHandle.put(artifactOperation.getArtifactOperationEnum(), artifactPathAndNameList.left().value());
588             } else {
589                 Either<EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes = findVfCsarArtifactsToHandle(
590                     component, artifactPathAndNameList.left().value(), csarInfo.getModifier());
591                 if (findVfCsarArtifactsToHandleRes.isRight()) {
592                     resStatus = Either.right(findVfCsarArtifactsToHandleRes.right().value());
593                 }
594                 if (resStatus == null) {
595                     vfCsarArtifactsToHandle = findVfCsarArtifactsToHandleRes.left().value();
596                 }
597             }
598             if (resStatus == null && vfCsarArtifactsToHandle != null) {
599                 resStatus = processCsarArtifacts(csarInfo, component, createdArtifacts, shouldLock, inTransaction, resStatus,
600                     vfCsarArtifactsToHandle);
601             }
602             if (resStatus == null) {
603                 resStatus = Either.left(component);
604             }
605         } catch (Exception e) {
606             resStatus = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
607             log.debug("Exception occured in createNonMetaArtifacts, message:{}", e.getMessage(), e);
608         } finally {
609             CsarUtils.handleWarningMessages(collectedWarningMessages);
610         }
611         return resStatus;
612     }
613
614     protected Either<Resource, ResponseFormat> createOrUpdateNonMetaArtifacts(CsarInfo csarInfo, Resource resource,
615                                                                               List<ArtifactDefinition> createdArtifacts, boolean shouldLock,
616                                                                               boolean inTransaction, ArtifactOperationInfo artifactOperation) {
617         return createOrUpdateNonMetaArtifactsComp(csarInfo, resource, createdArtifacts, shouldLock, inTransaction, artifactOperation);
618     }
619
620     protected <T extends Component> Either<T, ResponseFormat> processCsarArtifacts(CsarInfo csarInfo, Component comp,
621                                                                                    List<ArtifactDefinition> createdArtifacts, boolean shouldLock,
622                                                                                    boolean inTransaction, Either<T, ResponseFormat> resStatus,
623                                                                                    EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>> vfCsarArtifactsToHandle) {
624         for (Map.Entry<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>> currArtifactOperationPair : vfCsarArtifactsToHandle
625             .entrySet()) {
626             Optional<ResponseFormat> optionalCreateInDBError = currArtifactOperationPair.getValue().stream().map(
627                 e -> createOrUpdateSingleNonMetaArtifact(comp, csarInfo, e.getPath(), e.getArtifactName(), e.getArtifactType(),
628                     e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(), CsarUtils.ARTIFACT_CREATED_FROM_CSAR, e.getArtifactUniqueId(),
629                     new ArtifactOperationInfo(false, false, currArtifactOperationPair.getKey()), createdArtifacts, e.isFromCsar(), shouldLock,
630                     inTransaction)).filter(Either::isRight).map(e -> e.right().value()).findAny();
631             if (optionalCreateInDBError.isPresent()) {
632                 resStatus = Either.right(optionalCreateInDBError.get());
633                 break;
634             }
635         }
636         return resStatus;
637     }
638
639     protected Either<Boolean, ResponseFormat> createOrUpdateSingleNonMetaArtifact(Component component, CsarInfo csarInfo, String artifactPath,
640                                                                                   String artifactFileName, String artifactType,
641                                                                                   ArtifactGroupTypeEnum artifactGroupType, String artifactLabel,
642                                                                                   String artifactDisplayName, String artifactDescription,
643                                                                                   String artifactId, ArtifactOperationInfo operation,
644                                                                                   List<ArtifactDefinition> createdArtifacts, boolean isFromCsar,
645                                                                                   boolean shouldLock, boolean inTransaction) {
646         byte[] artifactFileBytes = null;
647         if (csarInfo.getCsar().containsKey(artifactPath)) {
648             artifactFileBytes = csarInfo.getCsar().get(artifactPath);
649         }
650         Either<Boolean, ResponseFormat> result = Either.left(true);
651         if (operation.getArtifactOperationEnum() == ArtifactsBusinessLogic.ArtifactOperationEnum.UPDATE
652             || operation.getArtifactOperationEnum() == ArtifactsBusinessLogic.ArtifactOperationEnum.DELETE) {
653             if (serviceImportParseLogic.isArtifactDeletionRequired(artifactId, artifactFileBytes, isFromCsar)) {
654                 Either<ArtifactDefinition, ResponseFormat> handleDelete = artifactsBusinessLogic
655                     .handleDelete(component.getUniqueId(), artifactId, csarInfo.getModifier(), component, shouldLock, inTransaction);
656                 if (handleDelete.isRight()) {
657                     result = Either.right(handleDelete.right().value());
658                 }
659                 return result;
660             }
661             if (org.apache.commons.lang.StringUtils.isEmpty(artifactId) && artifactFileBytes != null) {
662                 operation = new ArtifactOperationInfo(false, false, ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE);
663             }
664         }
665         if (artifactFileBytes != null) {
666             Map<String, Object> vendorLicenseModelJson = ArtifactUtils
667                 .buildJsonForUpdateArtifact(artifactId, artifactFileName, artifactType, artifactGroupType, artifactLabel, artifactDisplayName,
668                     artifactDescription, artifactFileBytes, null, isFromCsar);
669             Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts = csarArtifactsAndGroupsBusinessLogic
670                 .createOrUpdateCsarArtifactFromJson(component, csarInfo.getModifier(), vendorLicenseModelJson, operation);
671             serviceImportParseLogic.addNonMetaCreatedArtifactsToSupportRollback(operation, createdArtifacts, eitherNonMetaArtifacts);
672             if (eitherNonMetaArtifacts.isRight()) {
673                 BeEcompErrorManager.getInstance().logInternalFlowError("UploadLicenseArtifact",
674                     "Failed to upload license artifact: " + artifactFileName + "With csar uuid: " + csarInfo.getCsarUUID(),
675                     BeEcompErrorManager.ErrorSeverity.WARNING);
676                 return Either.right(eitherNonMetaArtifacts.right().value());
677             }
678         }
679         return result;
680     }
681
682     private Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifacts(Resource nodeTypeResource,
683                                                                                      Map<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
684                                                                                      List<ArtifactDefinition> createdArtifacts, User user,
685                                                                                      boolean inTransaction, boolean ignoreLifecycleState) {
686         List<ArtifactDefinition> handleNodeTypeArtifactsRequestRes;
687         Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = null;
688         Either<Resource, ResponseFormat> changeStateResponse;
689         try {
690             changeStateResponse = checkoutResource(nodeTypeResource, user, inTransaction);
691             if (changeStateResponse.isRight()) {
692                 return Either.right(changeStateResponse.right().value());
693             }
694             nodeTypeResource = changeStateResponse.left().value();
695             List<ArtifactDefinition> handledNodeTypeArtifacts = new ArrayList<>();
696             log.debug("************* Going to handle artifacts of node type resource {}. ", nodeTypeResource.getName());
697             for (Map.Entry<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> curOperationEntry : nodeTypeArtifactsToHandle
698                 .entrySet()) {
699                 ArtifactsBusinessLogic.ArtifactOperationEnum curOperation = curOperationEntry.getKey();
700                 List<ArtifactDefinition> curArtifactsToHandle = curOperationEntry.getValue();
701                 if (curArtifactsToHandle != null && !curArtifactsToHandle.isEmpty()) {
702                     log.debug("************* Going to {} artifact to vfc {}", curOperation.name(), nodeTypeResource.getName());
703                     handleNodeTypeArtifactsRequestRes = artifactsBusinessLogic
704                         .handleArtifactsRequestForInnerVfcComponent(curArtifactsToHandle, nodeTypeResource, user, createdArtifacts,
705                             new ArtifactOperationInfo(false, ignoreLifecycleState, curOperation), false, inTransaction);
706                     if (ArtifactsBusinessLogic.ArtifactOperationEnum.isCreateOrLink(curOperation)) {
707                         createdArtifacts.addAll(handleNodeTypeArtifactsRequestRes);
708                     }
709                     handledNodeTypeArtifacts.addAll(handleNodeTypeArtifactsRequestRes);
710                 }
711             }
712             if (handleNodeTypeArtifactsRes == null) {
713                 handleNodeTypeArtifactsRes = Either.left(handledNodeTypeArtifacts);
714             }
715         } catch (Exception e) {
716             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
717             handleNodeTypeArtifactsRes = Either.right(responseFormat);
718             log.debug("Exception occured when handleVfcArtifacts, error is:{}", e.getMessage(), e);
719         }
720         return handleNodeTypeArtifactsRes;
721     }
722
723     private Either<Resource, ResponseFormat> checkoutResource(Resource resource, User user, boolean inTransaction) {
724         Either<Resource, ResponseFormat> checkoutResourceRes;
725         try {
726             if (!resource.getComponentMetadataDefinition().getMetadataDataDefinition().getState()
727                 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
728                 Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic
729                     .changeComponentState(resource.getComponentType(), resource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
730                         new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
731                             LifecycleChangeInfoWithAction.LifecycleChanceActionEnum.CREATE_FROM_CSAR), inTransaction, true);
732                 if (checkoutRes.isRight()) {
733                     checkoutResourceRes = Either.right(checkoutRes.right().value());
734                 } else {
735                     checkoutResourceRes = Either.left((Resource) checkoutRes.left().value());
736                 }
737             } else {
738                 checkoutResourceRes = Either.left(resource);
739             }
740         } catch (Exception e) {
741             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
742             checkoutResourceRes = Either.right(responseFormat);
743             log.debug("Exception occured when checkoutResource {} , error is:{}", resource.getName(), e.getMessage(), e);
744         }
745         return checkoutResourceRes;
746     }
747
748     protected Either<Service, ResponseFormat> createOrUpdateArtifacts(ArtifactOperationEnum operation, List<ArtifactDefinition> createdArtifacts,
749                                                                       String yamlFileName, CsarInfo csarInfo, Service preparedService,
750                                                                       NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts,
751                                                                       boolean inTransaction, boolean shouldLock) {
752         Either<Service, ResponseFormat> createdCsarArtifactsEither = handleVfCsarArtifacts(preparedService, csarInfo, createdArtifacts,
753             new ArtifactOperationInfo(false, false, operation), shouldLock, inTransaction);
754         log.trace("************* Finished to add artifacts from yaml {}", yamlFileName);
755         if (createdCsarArtifactsEither.isRight()) {
756             return createdCsarArtifactsEither;
757         }
758         return Either.left(createdCsarArtifactsEither.left().value());
759     }
760
761     protected Either<Service, ResponseFormat> handleVfCsarArtifacts(Service service, CsarInfo csarInfo, List<ArtifactDefinition> createdArtifacts,
762                                                                     ArtifactOperationInfo artifactOperation, boolean shouldLock,
763                                                                     boolean inTransaction) {
764         if (csarInfo.getCsar() != null) {
765             String vendorLicenseModelId = null;
766             String vfLicenseModelId = null;
767             if (artifactOperation.getArtifactOperationEnum() == ArtifactsBusinessLogic.ArtifactOperationEnum.UPDATE) {
768                 Map<String, ArtifactDefinition> deploymentArtifactsMap = service.getDeploymentArtifacts();
769                 if (deploymentArtifactsMap != null && !deploymentArtifactsMap.isEmpty()) {
770                     for (Map.Entry<String, ArtifactDefinition> artifactEntry : deploymentArtifactsMap.entrySet()) {
771                         if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VENDOR_LICENSE_MODEL)) {
772                             vendorLicenseModelId = artifactEntry.getValue().getUniqueId();
773                         }
774                         if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VF_LICENSE_MODEL)) {
775                             vfLicenseModelId = artifactEntry.getValue().getUniqueId();
776                         }
777                     }
778                 }
779             }
780             createOrUpdateSingleNonMetaArtifact(service, csarInfo, CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL,
781                 Constants.VENDOR_LICENSE_MODEL, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
782                 Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME, Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId,
783                 artifactOperation, null, true, shouldLock, inTransaction);
784             createOrUpdateSingleNonMetaArtifact(service, csarInfo, CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL,
785                 ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, Constants.VF_LICENSE_LABEL,
786                 Constants.VF_LICENSE_DISPLAY_NAME, Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId, artifactOperation, null, true, shouldLock,
787                 inTransaction);
788             Either<Service, ResponseFormat> eitherCreateResult = createOrUpdateNonMetaArtifacts(csarInfo, service, createdArtifacts, shouldLock,
789                 inTransaction, artifactOperation);
790             if (eitherCreateResult.isRight()) {
791                 return Either.right(eitherCreateResult.right().value());
792             }
793             Either<Service, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(service.getUniqueId());
794             if (eitherGerResource.isRight()) {
795                 ResponseFormat responseFormat = componentsUtils
796                     .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), service,
797                         ComponentTypeEnum.SERVICE);
798                 return Either.right(responseFormat);
799             }
800             service = eitherGerResource.left().value();
801             Either<ImmutablePair<String, String>, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils
802                 .getArtifactsMeta(csarInfo.getCsar(), csarInfo.getCsarUUID(), componentsUtils);
803             if (artifacsMetaCsarStatus.isLeft()) {
804                 String artifactsFileName = artifacsMetaCsarStatus.left().value().getKey();
805                 String artifactsContents = artifacsMetaCsarStatus.left().value().getValue();
806                 Either<Service, ResponseFormat> createArtifactsFromCsar;
807                 if (ArtifactsBusinessLogic.ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) {
808                     createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic
809                         .createResourceArtifactsFromCsar(csarInfo, service, artifactsContents, artifactsFileName, createdArtifacts);
810                 } else {
811                     Either<Component, ResponseFormat> result = csarArtifactsAndGroupsBusinessLogic
812                         .updateResourceArtifactsFromCsar(csarInfo, service, artifactsContents, artifactsFileName, createdArtifacts, shouldLock,
813                             inTransaction);
814                     if ((result.left().value() instanceof Service) && result.isLeft()) {
815                         Service service1 = (Service) result.left().value();
816                         createArtifactsFromCsar = Either.left(service1);
817                     } else {
818                         createArtifactsFromCsar = Either.right(result.right().value());
819                     }
820                 }
821                 if (createArtifactsFromCsar.isRight()) {
822                     log.debug("Couldn't create artifacts from artifacts.meta");
823                     return Either.right(createArtifactsFromCsar.right().value());
824                 }
825                 return Either.left(createArtifactsFromCsar.left().value());
826             } else {
827                 return csarArtifactsAndGroupsBusinessLogic.deleteVFModules(service, csarInfo, shouldLock, inTransaction);
828             }
829         }
830         return Either.left(service);
831     }
832
833     protected Either<Service, ResponseFormat> createOrUpdateNonMetaArtifacts(CsarInfo csarInfo, Service resource,
834                                                                              List<ArtifactDefinition> createdArtifacts, boolean shouldLock,
835                                                                              boolean inTransaction, ArtifactOperationInfo artifactOperation) {
836         return createOrUpdateNonMetaArtifactsComp(csarInfo, resource, createdArtifacts, shouldLock, inTransaction, artifactOperation);
837     }
838
839     protected Either<EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandle(
840         Component component, List<CsarUtils.NonMetaArtifactInfo> artifactPathAndNameList, User user) {
841         List<ArtifactDefinition> existingArtifacts = new ArrayList<>();
842         if (component.getDeploymentArtifacts() != null && !component.getDeploymentArtifacts().isEmpty()) {
843             existingArtifacts.addAll(component.getDeploymentArtifacts().values());
844         }
845         if (component.getArtifacts() != null && !component.getArtifacts().isEmpty()) {
846             existingArtifacts.addAll(component.getArtifacts().values());
847         }
848         existingArtifacts = existingArtifacts.stream().filter(this::isNonMetaArtifact).collect(toList());
849         List<String> artifactsToIgnore = new ArrayList<>();
850         if (component.getGroups() != null) {
851             component.getGroups().forEach(g -> {
852                 if (g.getArtifacts() != null && !g.getArtifacts().isEmpty()) {
853                     artifactsToIgnore.addAll(g.getArtifacts());
854                 }
855             });
856         }
857         existingArtifacts = existingArtifacts.stream().filter(a -> !artifactsToIgnore.contains(a.getUniqueId())).collect(toList());
858         return organizeVfCsarArtifactsByArtifactOperation(artifactPathAndNameList, existingArtifacts, component, user);
859     }
860
861     private boolean isNonMetaArtifact(ArtifactDefinition artifact) {
862         boolean result = true;
863         if (artifact.getMandatory() || artifact.getArtifactName() == null || !isValidArtifactType(artifact)) {
864             result = false;
865         }
866         return result;
867     }
868
869     private boolean isValidArtifactType(ArtifactDefinition artifact) {
870         final String artifactType = artifact.getArtifactType();
871         return artifactType != null
872             && !ArtifactTypeEnum.VENDOR_LICENSE.getType().equals(ArtifactTypeEnum.findType(artifactType))
873             && !ArtifactTypeEnum.VF_LICENSE.getType().equals(ArtifactTypeEnum.findType(artifactType));
874     }
875
876     protected Either<EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>>, ResponseFormat> organizeVfCsarArtifactsByArtifactOperation(
877         List<CsarUtils.NonMetaArtifactInfo> artifactPathAndNameList, List<ArtifactDefinition> existingArtifactsToHandle, Component component,
878         User user) {
879         EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>> nodeTypeArtifactsToHandle = new EnumMap<>(
880             ArtifactsBusinessLogic.ArtifactOperationEnum.class);
881         Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
882         Either<EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>>, ResponseFormat> nodeTypeArtifactsToHandleRes = Either
883             .left(nodeTypeArtifactsToHandle);
884         try {
885             List<CsarUtils.NonMetaArtifactInfo> artifactsToUpload = new ArrayList<>(artifactPathAndNameList);
886             List<CsarUtils.NonMetaArtifactInfo> artifactsToUpdate = new ArrayList<>();
887             List<CsarUtils.NonMetaArtifactInfo> artifactsToDelete = new ArrayList<>();
888             for (CsarUtils.NonMetaArtifactInfo currNewArtifact : artifactPathAndNameList) {
889                 ArtifactDefinition foundArtifact;
890                 if (!existingArtifactsToHandle.isEmpty()) {
891                     foundArtifact = existingArtifactsToHandle.stream().filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName()))
892                         .findFirst().orElse(null);
893                     if (foundArtifact != null) {
894                         if (ArtifactTypeEnum.findType(foundArtifact.getArtifactType()).equals(currNewArtifact.getArtifactType())) {
895                             if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) {
896                                 currNewArtifact.setArtifactUniqueId(foundArtifact.getUniqueId());
897                                 artifactsToUpdate.add(currNewArtifact);
898                             }
899                             existingArtifactsToHandle.remove(foundArtifact);
900                             artifactsToUpload.remove(currNewArtifact);
901                         } else {
902                             log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName());
903                             ResponseFormat responseFormat = ResponseFormatManager.getInstance()
904                                 .getResponseFormat(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, currNewArtifact.getArtifactName(),
905                                     currNewArtifact.getArtifactType(), foundArtifact.getArtifactType());
906                             AuditingActionEnum auditingAction = artifactsBusinessLogic.detectAuditingType(
907                                 new ArtifactOperationInfo(false, false, ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE),
908                                 foundArtifact.getArtifactChecksum());
909                             artifactsBusinessLogic.handleAuditing(auditingAction, component, component.getUniqueId(), user, null, null,
910                                 foundArtifact.getUniqueId(), responseFormat, component.getComponentType(), null);
911                             responseWrapper.setInnerElement(responseFormat);
912                             break;
913                         }
914                     }
915                 }
916             }
917             if (responseWrapper.isEmpty()) {
918                 for (ArtifactDefinition currArtifact : existingArtifactsToHandle) {
919                     if (currArtifact.getIsFromCsar()) {
920                         artifactsToDelete.add(new CsarUtils.NonMetaArtifactInfo(currArtifact.getArtifactName(), null,
921                             ArtifactTypeEnum.findType(currArtifact.getArtifactType()), currArtifact.getArtifactGroupType(), null,
922                             currArtifact.getUniqueId(), currArtifact.getIsFromCsar()));
923                     } else {
924                         artifactsToUpdate.add(new CsarUtils.NonMetaArtifactInfo(currArtifact.getArtifactName(), null,
925                             ArtifactTypeEnum.findType(currArtifact.getArtifactType()), currArtifact.getArtifactGroupType(), null,
926                             currArtifact.getUniqueId(), currArtifact.getIsFromCsar()));
927                     }
928                 }
929             }
930             if (responseWrapper.isEmpty()) {
931                 if (!artifactsToUpload.isEmpty()) {
932                     nodeTypeArtifactsToHandle.put(ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE, artifactsToUpload);
933                 }
934                 if (!artifactsToUpdate.isEmpty()) {
935                     nodeTypeArtifactsToHandle.put(ArtifactsBusinessLogic.ArtifactOperationEnum.UPDATE, artifactsToUpdate);
936                 }
937                 if (!artifactsToDelete.isEmpty()) {
938                     nodeTypeArtifactsToHandle.put(ArtifactsBusinessLogic.ArtifactOperationEnum.DELETE, artifactsToDelete);
939                 }
940             }
941             if (!responseWrapper.isEmpty()) {
942                 nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement());
943             }
944         } catch (Exception e) {
945             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
946             responseWrapper.setInnerElement(responseFormat);
947             log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
948             nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement());
949         }
950         return nodeTypeArtifactsToHandleRes;
951     }
952
953     protected Either<List<CsarUtils.NonMetaArtifactInfo>, String> getValidArtifactNames(CsarInfo csarInfo,
954                                                                                         Map<String, Set<List<String>>> collectedWarningMessages) {
955         List<CsarUtils.NonMetaArtifactInfo> artifactPathAndNameList = csarInfo.getCsar().entrySet().stream()
956             .filter(e -> Pattern.compile(VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey()).matches())
957             .map(e -> CsarUtils.validateNonMetaArtifact(e.getKey(), e.getValue(), collectedWarningMessages)).filter(Either::isLeft)
958             .map(e -> e.left().value()).collect(toList());
959         Pattern englishNumbersAndUnderScoresOnly = Pattern.compile(CsarUtils.VALID_ENGLISH_ARTIFACT_NAME);
960         for (CsarUtils.NonMetaArtifactInfo nonMetaArtifactInfo : artifactPathAndNameList) {
961             if (!englishNumbersAndUnderScoresOnly.matcher(nonMetaArtifactInfo.getDisplayName()).matches()) {
962                 return Either.right(nonMetaArtifactInfo.getArtifactName());
963             }
964         }
965         return Either.left(artifactPathAndNameList);
966     }
967
968     protected Either<Service, ResponseFormat> createGroupsOnResource(Service service, Map<String, GroupDefinition> groups) {
969         if (groups != null && !groups.isEmpty()) {
970             List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(groups, service);
971             serviceImportParseLogic.handleGroupsProperties(service, groups);
972             serviceImportParseLogic.fillGroupsFinalFields(groupsAsList);
973             Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.createGroups(service, groupsAsList, true);
974             if (createGroups.isRight()) {
975                 return Either.right(createGroups.right().value());
976             }
977         } else {
978             return Either.left(service);
979         }
980         return getServiceResponseFormatEither(service);
981     }
982
983     private Either<Service, ResponseFormat> createPoliciesOnResource(final Service service,
984                                                                      final Map<String, PolicyDefinition> policies) {
985         if (MapUtils.isEmpty(policies)) {
986             return Either.left(service);
987         }
988         final Map<String, List<AttributeDefinition>> instanceAttributeMap =
989             service.getComponentInstancesAttributes()
990                 .entrySet().stream()
991                 .collect(
992                     toMap(Entry::getKey,
993                         entry -> entry.getValue().stream().map(AttributeDefinition.class::cast).collect(toList()))
994                 );
995         policies.values().stream()
996             .map(PolicyDataDefinition::getProperties)
997             .flatMap(Collection::stream)
998             .filter(PropertyDataDefinition::isToscaFunction)
999             .forEach(policyDefinition ->
1000                 toscaFunctionService
1001                     .updateFunctionWithDataFromSelfComponent(policyDefinition.getToscaFunction(), service, service.getComponentInstancesProperties(), instanceAttributeMap)
1002             );
1003         policyBusinessLogic.createPolicies(service, policies);
1004         return getServiceResponseFormatEither(service);
1005     }
1006
1007     private Either<Service, ResponseFormat> getServiceResponseFormatEither(Service service) {
1008         Either<Service, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(service.getUniqueId());
1009         if (updatedResource.isRight()) {
1010             ResponseFormat responseFormat = componentsUtils
1011                 .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), service,
1012                     ComponentTypeEnum.SERVICE);
1013             return Either.right(responseFormat);
1014         }
1015         return Either.left(updatedResource.left().value());
1016     }
1017
1018     protected List<GroupDefinition> updateGroupsMembersUsingResource(Map<String, GroupDefinition> groups, Service component) {
1019         List<GroupDefinition> result = new ArrayList<>();
1020         List<ComponentInstance> componentInstances = component.getComponentInstances();
1021         if (groups != null) {
1022             for (Map.Entry<String, GroupDefinition> entry : groups.entrySet()) {
1023                 String groupName = entry.getKey();
1024                 GroupDefinition groupDefinition = entry.getValue();
1025                 GroupDefinition updatedGroupDefinition = new GroupDefinition(groupDefinition);
1026                 updatedGroupDefinition.setMembers(null);
1027                 Map<String, String> members = groupDefinition.getMembers();
1028                 if (members != null) {
1029                     serviceImportParseLogic.updateGroupMembers(groups, updatedGroupDefinition, component, componentInstances, groupName, members);
1030                 }
1031                 result.add(updatedGroupDefinition);
1032             }
1033         }
1034         return result;
1035     }
1036
1037     protected Resource createRIAndRelationsFromYaml(String yamlName, Resource resource,
1038                                                     Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap,
1039                                                     String topologyTemplateYaml, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
1040                                                     Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
1041                                                     Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
1042                                                     String nodeName) {
1043         try {
1044             log.debug("************* Going to create all nodes {}", yamlName);
1045             handleNodeTypes(yamlName, resource, topologyTemplateYaml, false, nodeTypesArtifactsToCreate, nodeTypesNewCreatedArtifacts, nodeTypesInfo,
1046                 csarInfo, nodeName);
1047             log.debug("************* Going to create all resource instances {}", yamlName);
1048             resource = createResourceInstances(yamlName, resource, uploadComponentInstanceInfoMap, csarInfo.getCreatedNodes());
1049             log.debug("************* Finished to create all resource instances {}", yamlName);
1050             resource = createResourceInstancesRelations(csarInfo.getModifier(), yamlName, resource, uploadComponentInstanceInfoMap);
1051             log.debug("************* Going to create positions {}", yamlName);
1052             compositionBusinessLogic.setPositionsForComponentInstances(resource, csarInfo.getModifier().getUserId());
1053             log.debug("************* Finished to set positions {}", yamlName);
1054             return resource;
1055         } catch (Exception e) {
1056             throw new ComponentException(ActionStatus.GENERAL_ERROR);
1057         }
1058     }
1059
1060     protected Resource createResourceInstancesRelations(User user, String yamlName, Resource resource,
1061                                                         Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
1062         log.debug("#createResourceInstancesRelations - Going to create relations ");
1063         List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
1064         if (((MapUtils.isEmpty(uploadResInstancesMap) || CollectionUtils.isEmpty(componentInstancesList)) &&
1065             resource.getResourceType() != ResourceTypeEnum.PNF)) { // PNF can have no resource instances
1066             log.debug("#createResourceInstancesRelations - No instances found in the resource {} is empty, yaml template file name {}, ",
1067                 resource.getUniqueId(), yamlName);
1068             BeEcompErrorManager.getInstance()
1069                 .logInternalDataError("createResourceInstancesRelations", "No instances found in a resource or nn yaml template. ",
1070                     BeEcompErrorManager.ErrorSeverity.ERROR);
1071             throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName));
1072         }
1073         Map<String, List<ComponentInstanceProperty>> instProperties = new HashMap<>();
1074         Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities = new HashMap<>();
1075         Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements = new HashMap<>();
1076         Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts = new HashMap<>();
1077         Map<String, Map<String, ArtifactDefinition>> instArtifacts = new HashMap<>();
1078         Map<String, List<AttributeDefinition>> instAttributes = new HashMap<>();
1079         Map<String, Resource> originCompMap = new HashMap<>();
1080         List<RequirementCapabilityRelDef> relations = new ArrayList<>();
1081         Map<String, List<ComponentInstanceInput>> instInputs = new HashMap<>();
1082         Map<String, UploadNodeFilterInfo> instNodeFilter = new HashMap<>();
1083
1084         log.debug("enter ServiceImportBusinessLogic createResourceInstancesRelations#createResourceInstancesRelations - Before get all datatypes. ");
1085         final ApplicationDataTypeCache applicationDataTypeCache = serviceBusinessLogic.applicationDataTypeCache;
1086         if (applicationDataTypeCache != null) {
1087             Resource finalResource = resource;
1088             uploadResInstancesMap.values().forEach(
1089                 i -> processComponentInstance(yamlName, finalResource, componentInstancesList,
1090                     componentsUtils.getAllDataTypes(applicationDataTypeCache, finalResource.getModel()), instProperties, instCapabilities,
1091                     instRequirements, instDeploymentArtifacts, instArtifacts, instAttributes, originCompMap, instInputs, instNodeFilter, i));
1092         }
1093         serviceImportParseLogic.associateComponentInstancePropertiesToComponent(yamlName, resource, instProperties);
1094         serviceImportParseLogic.associateComponentInstanceInputsToComponent(yamlName, resource, instInputs);
1095         serviceImportParseLogic.associateDeploymentArtifactsToInstances(user, yamlName, resource, instDeploymentArtifacts);
1096         serviceImportParseLogic.associateArtifactsToInstances(yamlName, resource, instArtifacts);
1097         serviceImportParseLogic.associateOrAddCalculatedCapReq(yamlName, resource, instCapabilities, instRequirements);
1098         serviceImportParseLogic.associateInstAttributeToComponentToInstances(yamlName, resource, instAttributes);
1099         resource = serviceImportParseLogic.getResourceAfterCreateRelations(resource);
1100         serviceImportParseLogic.addRelationsToRI(yamlName, resource, uploadResInstancesMap, componentInstancesList, relations);
1101         serviceImportParseLogic.associateResourceInstances(yamlName, resource, relations);
1102         handleSubstitutionMappings(resource, uploadResInstancesMap);
1103         log.debug("************* in create relations, getResource start");
1104         Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
1105         log.debug("************* in create relations, getResource end");
1106         if (eitherGetResource.isRight()) {
1107             throw new ComponentException(
1108                 componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource));
1109         }
1110         return eitherGetResource.left().value();
1111     }
1112
1113     protected void processProperty(Resource resource, ComponentInstance currentCompInstance, Map<String, DataTypeDefinition> allDataTypes,
1114                                    Map<String, InputDefinition> currPropertiesMap, List<ComponentInstanceInput> instPropList,
1115                                    List<UploadPropInfo> propertyList) {
1116         UploadPropInfo propertyInfo = propertyList.get(0);
1117         String propName = propertyInfo.getName();
1118         if (!currPropertiesMap.containsKey(propName)) {
1119             throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName));
1120         }
1121         processProperty(allDataTypes, currPropertiesMap, instPropList, propertyInfo, propName, resource.getInputs());
1122     }
1123
1124     private void processProperty(Map<String, DataTypeDefinition> allDataTypes, Map<String, InputDefinition> currPropertiesMap,
1125                                  List<ComponentInstanceInput> instPropList, UploadPropInfo propertyInfo, String propName,
1126                                  List<InputDefinition> inputs2) {
1127         InputDefinition curPropertyDef = currPropertiesMap.get(propName);
1128         ComponentInstanceInput property = null;
1129         String value = null;
1130         List<GetInputValueDataDefinition> getInputs = null;
1131         boolean isValidate = true;
1132         if (propertyInfo.getValue() != null) {
1133             getInputs = propertyInfo.getGet_input();
1134             isValidate = getInputs == null || getInputs.isEmpty();
1135             if (isValidate) {
1136                 value = getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType());
1137             } else {
1138                 value = getPropertyJsonStringValue(propertyInfo.getValue(), TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
1139             }
1140         }
1141         property = new ComponentInstanceInput(curPropertyDef, value, null);
1142         String validPropertyVAlue = serviceBusinessLogic.validatePropValueBeforeCreate(property, value, isValidate, allDataTypes);
1143         property.setValue(validPropertyVAlue);
1144         if (isNotEmpty(getInputs)) {
1145             List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
1146             for (GetInputValueDataDefinition getInput : getInputs) {
1147                 List<InputDefinition> inputs = inputs2;
1148                 if (CollectionUtils.isEmpty(inputs)) {
1149                     throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1150                 }
1151                 Optional<InputDefinition> optional = inputs.stream().filter(p -> p.getName().equals(getInput.getInputName())).findAny();
1152                 if (!optional.isPresent()) {
1153                     throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1154                 }
1155                 InputDefinition input = optional.get();
1156                 getInput.setInputId(input.getUniqueId());
1157                 getInputValues.add(getInput);
1158                 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
1159                 processGetInput(getInputValues, inputs, getInputIndex);
1160             }
1161             property.setGetInputValues(getInputValues);
1162         }
1163         instPropList.add(property);
1164         currPropertiesMap.remove(property.getName());
1165     }
1166
1167     protected void handleSubstitutionMappings(Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
1168         if (resource.getResourceType() == ResourceTypeEnum.VF) {
1169             Either<Resource, StorageOperationStatus> getResourceRes = toscaOperationFacade.getToscaFullElement(resource.getUniqueId());
1170             if (getResourceRes.isRight()) {
1171                 ResponseFormat responseFormat = componentsUtils
1172                     .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), resource);
1173                 throw new ComponentException(responseFormat);
1174             }
1175             getResourceRes = updateCalculatedCapReqWithSubstitutionMappings(getResourceRes.left().value(), uploadResInstancesMap);
1176             if (getResourceRes.isRight()) {
1177                 ResponseFormat responseFormat = componentsUtils
1178                     .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), resource);
1179                 throw new ComponentException(responseFormat);
1180             }
1181         }
1182     }
1183
1184     protected Resource createResourceInstances(String yamlName, Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
1185                                                Map<String, Resource> nodeNamespaceMap) {
1186         Either<Resource, ResponseFormat> eitherResource = null;
1187         log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName);
1188         if (MapUtils.isEmpty(uploadResInstancesMap) && resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances
1189             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
1190             throw new ComponentException(responseFormat);
1191         }
1192         Map<String, Resource> existingNodeTypeMap = new HashMap<>();
1193         if (MapUtils.isNotEmpty(nodeNamespaceMap)) {
1194             nodeNamespaceMap.forEach((k, v) -> existingNodeTypeMap.put(v.getToscaResourceName(), v));
1195         }
1196         Map<ComponentInstance, Resource> resourcesInstancesMap = new HashMap<>();
1197         uploadResInstancesMap.values()
1198             .forEach(i -> createAndAddResourceInstance(i, yamlName, resource, nodeNamespaceMap, existingNodeTypeMap, resourcesInstancesMap));
1199         if (MapUtils.isNotEmpty(resourcesInstancesMap)) {
1200             try {
1201                 toscaOperationFacade.associateComponentInstancesToComponent(resource, resourcesInstancesMap, false, false);
1202             } catch (StorageException exp) {
1203                 if (exp.getStorageOperationStatus() != null && exp.getStorageOperationStatus() != StorageOperationStatus.OK) {
1204                     log.debug("Failed to add component instances to container component {}", resource.getName());
1205                     ResponseFormat responseFormat = componentsUtils
1206                         .getResponseFormat(componentsUtils.convertFromStorageResponse(exp.getStorageOperationStatus()));
1207                     eitherResource = Either.right(responseFormat);
1208                     throw new ByResponseFormatComponentException(eitherResource.right().value());
1209                 }
1210             }
1211         }
1212         log.debug("*************Going to get resource {}", resource.getUniqueId());
1213         Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade
1214             .getToscaElement(resource.getUniqueId(), serviceImportParseLogic.getComponentWithInstancesFilter());
1215         log.debug("*************finished to get resource {}", resource.getUniqueId());
1216         if (eitherGetResource.isRight()) {
1217             ResponseFormat responseFormat = componentsUtils
1218                 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource);
1219             throw new ComponentException(responseFormat);
1220         }
1221         if (CollectionUtils.isEmpty(eitherGetResource.left().value().getComponentInstances()) &&
1222             resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances
1223             log.debug("Error when create resource instance from csar. ComponentInstances list empty");
1224             BeEcompErrorManager.getInstance().logBeDaoSystemError("Error when create resource instance from csar. ComponentInstances list empty");
1225             throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
1226         }
1227         return eitherGetResource.left().value();
1228     }
1229
1230     protected void handleNodeTypes(String yamlName, Resource resource, String topologyTemplateYaml, boolean needLock,
1231                                    Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
1232                                    List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
1233                                    String nodeName) {
1234         try {
1235             for (Map.Entry<String, NodeTypeInfo> nodeTypeEntry : nodeTypesInfo.entrySet()) {
1236                 if (nodeTypeEntry.getValue().isNested()) {
1237                     handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
1238                         nodeTypeEntry.getKey());
1239                     log.trace("************* finished to create node {}", nodeTypeEntry.getKey());
1240                 }
1241             }
1242             Map<String, Object> mappedToscaTemplate = null;
1243             if (org.apache.commons.lang.StringUtils.isNotEmpty(nodeName) && MapUtils.isNotEmpty(nodeTypesInfo) && nodeTypesInfo
1244                 .containsKey(nodeName)) {
1245                 mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate();
1246             }
1247             if (MapUtils.isEmpty(mappedToscaTemplate)) {
1248                 mappedToscaTemplate = (Map<String, Object>) new Yaml().load(topologyTemplateYaml);
1249             }
1250             createResourcesFromYamlNodeTypesList(yamlName, resource, mappedToscaTemplate, needLock, nodeTypesArtifactsToHandle,
1251                 nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo);
1252         } catch (ComponentException e) {
1253             ResponseFormat responseFormat =
1254                 e.getResponseFormat() != null ? e.getResponseFormat() : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
1255             componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
1256             throw e;
1257         } catch (StorageException e) {
1258             ResponseFormat responseFormat = componentsUtils
1259                 .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
1260             componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
1261             throw e;
1262         } catch (Exception e) {
1263             log.debug("Exception occured when handleNodeTypes, error is:{}", e.getMessage(), e);
1264             throw new ComponentException(ActionStatus.GENERAL_ERROR);
1265         }
1266     }
1267
1268     protected Resource handleNestedVfc(Service service,
1269                                        Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
1270                                        List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
1271                                        String nodeName) {
1272         try {
1273             String yamlName = nodesInfo.get(nodeName).getTemplateFileName();
1274             Map<String, Object> nestedVfcJsonMap = nodesInfo.get(nodeName).getMappedToscaTemplate();
1275             createResourcesFromYamlNodeTypesList(yamlName, service, nestedVfcJsonMap, false, nodesArtifactsToHandle, createdArtifacts, nodesInfo,
1276                 csarInfo);
1277             log.debug("************* Finished to create node types from yaml {}", yamlName);
1278             if (nestedVfcJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) {
1279                 log.debug("************* Going to handle complex VFC from yaml {}", yamlName);
1280                 return handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName);
1281             }
1282             return new Resource();
1283         } catch (Exception e) {
1284             log.debug("Exception occured when handleNestedVFc, error is:{}", e.getMessage(), e);
1285             throw new ComponentException(ActionStatus.GENERAL_ERROR);
1286         }
1287     }
1288
1289     protected Resource handleNestedVfc(Resource resource,
1290                                        Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
1291                                        List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
1292                                        String nodeName) {
1293         String yamlName = nodesInfo.get(nodeName).getTemplateFileName();
1294         Map<String, Object> nestedVfcJsonMap = nodesInfo.get(nodeName).getMappedToscaTemplate();
1295         log.debug("************* Going to create node types from yaml {}", yamlName);
1296         createResourcesFromYamlNodeTypesList(yamlName, resource, nestedVfcJsonMap, false, nodesArtifactsToHandle, createdArtifacts, nodesInfo,
1297             csarInfo);
1298         if (nestedVfcJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) {
1299             log.debug("************* Going to handle complex VFC from yaml {}", yamlName);
1300             resource = handleComplexVfc(resource, nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName);
1301         }
1302         return resource;
1303     }
1304
1305     protected Resource handleComplexVfc(Resource resource,
1306                                         Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
1307                                         List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
1308                                         String nodeName, String yamlName) {
1309         Resource oldComplexVfc = null;
1310         Resource newComplexVfc = serviceImportParseLogic.buildValidComplexVfc(resource, csarInfo, nodeName, nodesInfo);
1311         Either<Resource, StorageOperationStatus> oldComplexVfcRes = toscaOperationFacade
1312             .getFullLatestComponentByToscaResourceName(newComplexVfc.getToscaResourceName());
1313         if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() == StorageOperationStatus.NOT_FOUND) {
1314             oldComplexVfcRes = toscaOperationFacade.getFullLatestComponentByToscaResourceName(
1315                 serviceImportParseLogic.buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), csarInfo.getVfResourceName(), nodeName).getRight());
1316         }
1317         if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() != StorageOperationStatus.NOT_FOUND) {
1318             throw new ComponentException(ActionStatus.GENERAL_ERROR);
1319         } else if (oldComplexVfcRes.isLeft()) {
1320             log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
1321             Either<Boolean, ResponseFormat> eitherValidation = serviceImportParseLogic
1322                 .validateNestedDerivedFromDuringUpdate(oldComplexVfcRes.left().value(), newComplexVfc,
1323                     ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion()));
1324             if (eitherValidation.isLeft()) {
1325                 oldComplexVfc = oldComplexVfcRes.left().value();
1326             }
1327         }
1328         newComplexVfc = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName, oldComplexVfc,
1329             newComplexVfc);
1330         csarInfo.getCreatedNodesToscaResourceNames().put(nodeName, newComplexVfc.getToscaResourceName());
1331         LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
1332             LifecycleChangeInfoWithAction.LifecycleChanceActionEnum.CREATE_FROM_CSAR);
1333         log.debug("Going to certify cvfc {}. ", newComplexVfc.getName());
1334         final Resource result = serviceImportParseLogic
1335             .propagateStateToCertified(csarInfo.getModifier(), newComplexVfc, lifecycleChangeInfo, true, false, true);
1336         csarInfo.getCreatedNodes().put(nodeName, result);
1337         csarInfo.removeNodeFromQueue();
1338         return result;
1339     }
1340
1341     private Map<String, Resource> createResourcesFromYamlNodeTypesList(String yamlName, Resource resource, Map<String, Object> mappedToscaTemplate,
1342                                                                        boolean needLock,
1343                                                                        Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
1344                                                                        List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
1345                                                                        Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo) {
1346         Either<String, ImportUtils.ResultStatusEnum> toscaVersion = findFirstToscaStringElement(mappedToscaTemplate,
1347             TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION);
1348         if (toscaVersion.isRight()) {
1349             throw new ComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE);
1350         }
1351         Map<String, Object> mapToConvert = new HashMap<>();
1352         mapToConvert.put(TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION.getElementName(), toscaVersion.left().value());
1353         Map<String, Object> nodeTypes = serviceImportParseLogic.getNodeTypesFromTemplate(mappedToscaTemplate);
1354         createNodeTypes(yamlName, resource, needLock, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, mapToConvert,
1355             nodeTypes);
1356         return csarInfo.getCreatedNodes();
1357     }
1358
1359     protected void createNodeTypes(String yamlName, Resource resource, boolean needLock,
1360                                    Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
1361                                    List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
1362                                    Map<String, Object> mapToConvert, Map<String, Object> nodeTypes) {
1363         Iterator<Map.Entry<String, Object>> nodesNameValueIter = nodeTypes.entrySet().iterator();
1364         Resource vfcCreated = null;
1365         while (nodesNameValueIter.hasNext()) {
1366             Map.Entry<String, Object> nodeType = nodesNameValueIter.next();
1367             Map<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle =
1368                 nodeTypesArtifactsToHandle == null || nodeTypesArtifactsToHandle.isEmpty() ? null : nodeTypesArtifactsToHandle.get(nodeType.getKey());
1369             if (nodeTypesInfo.containsKey(nodeType.getKey())) {
1370                 log.trace("************* Going to handle nested vfc {}", nodeType.getKey());
1371                 vfcCreated = handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
1372                     nodeType.getKey());
1373                 log.trace("************* Finished to handle nested vfc {}", nodeType.getKey());
1374             } else if (csarInfo.getCreatedNodesToscaResourceNames() != null && !csarInfo.getCreatedNodesToscaResourceNames()
1375                 .containsKey(nodeType.getKey())) {
1376                 log.trace("************* Going to create node {}", nodeType.getKey());
1377                 ImmutablePair<Resource, ActionStatus> resourceCreated = createNodeTypeResourceFromYaml(yamlName, nodeType, csarInfo.getModifier(),
1378                     mapToConvert, resource, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, true, csarInfo, true);
1379                 log.debug("************* Finished to create node {}", nodeType.getKey());
1380                 vfcCreated = resourceCreated.getLeft();
1381                 csarInfo.getCreatedNodesToscaResourceNames().put(nodeType.getKey(), vfcCreated.getToscaResourceName());
1382             }
1383             if (vfcCreated != null) {
1384                 csarInfo.getCreatedNodes().put(nodeType.getKey(), vfcCreated);
1385             }
1386             mapToConvert.remove(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName());
1387         }
1388     }
1389
1390     protected ImmutablePair<Resource, ActionStatus> createNodeTypeResourceFromYaml(String yamlName, Map.Entry<String, Object> nodeNameValue,
1391                                                                                    User user, Map<String, Object> mapToConvert, Resource resourceVf,
1392                                                                                    boolean needLock,
1393                                                                                    Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
1394                                                                                    List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
1395                                                                                    boolean forceCertificationAllowed, CsarInfo csarInfo,
1396                                                                                    boolean isNested) {
1397         UploadResourceInfo resourceMetaData = serviceImportParseLogic.fillResourceMetadata(yamlName, resourceVf, nodeNameValue.getKey(), user);
1398         String singleVfcYaml = serviceImportParseLogic.buildNodeTypeYaml(nodeNameValue, mapToConvert, resourceMetaData.getResourceType(), csarInfo);
1399         user = serviceBusinessLogic.validateUser(user, "CheckIn Resource", resourceVf, AuditingActionEnum.CHECKIN_RESOURCE, true);
1400         return serviceImportParseLogic.createResourceFromNodeType(singleVfcYaml, resourceMetaData, user, true, needLock, nodeTypeArtifactsToHandle,
1401             nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeNameValue.getKey(), isNested);
1402     }
1403
1404     protected Service createRIAndRelationsFromYaml(String yamlName, Service service,
1405                                                    Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap,
1406                                                    String topologyTemplateYaml, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
1407                                                    Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
1408                                                    Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
1409                                                    String nodeName) {
1410         log.debug("************* Going to create all nodes {}", yamlName);
1411         handleServiceNodeTypes(yamlName, service, topologyTemplateYaml, false, nodeTypesArtifactsToCreate, nodeTypesNewCreatedArtifacts,
1412             nodeTypesInfo, csarInfo, nodeName);
1413         if (MapUtils.isNotEmpty(uploadComponentInstanceInfoMap)) {
1414             log.debug("************* Going to create all resource instances {}", yamlName);
1415             service = createServiceInstances(yamlName, service, uploadComponentInstanceInfoMap, csarInfo.getCreatedNodes());
1416             log.debug("************* Going to create all relations {}", yamlName);
1417             service = createServiceInstancesRelations(csarInfo.getModifier(), yamlName, service, uploadComponentInstanceInfoMap);
1418             log.debug("************* Going to create positions {}", yamlName);
1419             compositionBusinessLogic.setPositionsForComponentInstances(service, csarInfo.getModifier().getUserId());
1420             log.debug("************* Finished to set positions {}", yamlName);
1421         }
1422         return service;
1423     }
1424
1425     protected Service createServiceInstancesRelations(User user, String yamlName, Service service,
1426                                                       Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
1427         log.debug("#createResourceInstancesRelations - Going to create relations ");
1428         List<ComponentInstance> componentInstancesList = service.getComponentInstances();
1429         if (MapUtils.isEmpty(uploadResInstancesMap) || CollectionUtils.isEmpty(componentInstancesList)) { // PNF can have no resource instances
1430             log.debug("#createResourceInstancesRelations - No instances found in the resource {} is empty, yaml template file name {}, ",
1431                 service.getUniqueId(), yamlName);
1432             BeEcompErrorManager.getInstance()
1433                 .logInternalDataError("createResourceInstancesRelations", "No instances found in a component or nn yaml template. ",
1434                     BeEcompErrorManager.ErrorSeverity.ERROR);
1435             throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName));
1436         }
1437         Map<String, List<ComponentInstanceProperty>> instProperties = new HashMap<>();
1438         Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities = new HashMap<>();
1439         Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements = new HashMap<>();
1440         Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts = new HashMap<>();
1441         Map<String, Map<String, ArtifactDefinition>> instArtifacts = new HashMap<>();
1442         Map<String, List<AttributeDefinition>> instAttributes = new HashMap<>();
1443         Map<String, Resource> originCompMap = new HashMap<>();
1444         List<RequirementCapabilityRelDef> relations = new ArrayList<>();
1445         Map<String, List<ComponentInstanceInput>> instInputs = new HashMap<>();
1446         Map<String, UploadNodeFilterInfo> instNodeFilter = new HashMap<>();
1447         log.debug("enter ServiceImportBusinessLogic  createServiceInstancesRelations#createResourceInstancesRelations - Before get all datatypes. ");
1448         final ApplicationDataTypeCache applicationDataTypeCache = serviceBusinessLogic.applicationDataTypeCache;
1449         if (applicationDataTypeCache != null) {
1450             final Map<String, DataTypeDefinition> allDataTypesMap =
1451                 componentsUtils.getAllDataTypes(applicationDataTypeCache, service.getModel());
1452             final Service service1 = service;
1453             uploadResInstancesMap.values().forEach(
1454                 i -> processComponentInstance(yamlName, service1, componentInstancesList,
1455                     allDataTypesMap, instProperties,
1456                     instCapabilities, instRequirements, instDeploymentArtifacts, instArtifacts, instAttributes, originCompMap, instInputs,
1457                     instNodeFilter, i));
1458         }
1459         updatePropertyToscaFunctionData(service, instProperties, instAttributes);
1460         serviceImportParseLogic.associateComponentInstancePropertiesToComponent(yamlName, service, instProperties);
1461         serviceImportParseLogic.associateComponentInstanceInputsToComponent(yamlName, service, instInputs);
1462         serviceImportParseLogic.associateCINodeFilterToComponent(yamlName, service, instNodeFilter);
1463         serviceImportParseLogic.associateDeploymentArtifactsToInstances(user, yamlName, service, instDeploymentArtifacts);
1464         serviceImportParseLogic.associateArtifactsToInstances(yamlName, service, instArtifacts);
1465         serviceImportParseLogic.associateOrAddCalculatedCapReq(yamlName, service, instCapabilities, instRequirements);
1466         log.debug("enter createServiceInstancesRelations test,instRequirements:{},instCapabilities:{}", instRequirements, instCapabilities);
1467         serviceImportParseLogic.associateInstAttributeToComponentToInstances(yamlName, service, instAttributes);
1468         ToscaElement serviceTemplate = ModelConverter.convertToToscaElement(service);
1469         Map<String, ListCapabilityDataDefinition> capabilities = serviceTemplate.getCapabilities();
1470         Map<String, ListRequirementDataDefinition> requirements = serviceTemplate.getRequirements();
1471         serviceImportParseLogic.associateCapabilitiesToService(yamlName, service, capabilities);
1472         serviceImportParseLogic.associateRequirementsToService(yamlName, service, requirements);
1473         service = getResourceAfterCreateRelations(service);
1474         addRelationsToRI(yamlName, service, uploadResInstancesMap, componentInstancesList, relations);
1475         serviceImportParseLogic.associateResourceInstances(yamlName, service, relations);
1476         log.debug("************* in create relations, getResource start");
1477         Either<Service, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(service.getUniqueId());
1478         log.debug("************* in create relations, getResource end");
1479         if (eitherGetResource.isRight()) {
1480             throw new ComponentException(componentsUtils
1481                 .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), service,
1482                     service.getComponentType()));
1483         }
1484         return eitherGetResource.left().value();
1485     }
1486
1487     private void updatePropertyToscaFunctionData(final Component service,
1488                                                  final Map<String, List<ComponentInstanceProperty>> instancePropertyMap,
1489                                                  final Map<String, List<AttributeDefinition>> instanceAttributeMap) {
1490         final Component updatedService =
1491             toscaOperationFacade.getToscaElement(service.getUniqueId()).left()
1492                 .on(storageOperationStatus -> {
1493                         final ActionStatus status = componentsUtils.convertFromStorageResponse(storageOperationStatus);
1494                         final ResponseFormat responseFormat =
1495                             componentsUtils.getResponseFormatByComponent(status, service, service.getComponentType());
1496                         throw new ComponentException(responseFormat);
1497                     }
1498                 );
1499         instancePropertyMap.values().forEach(instancePropertyList ->
1500             instancePropertyList.stream()
1501                 .filter(PropertyDataDefinition::isToscaFunction)
1502                 .forEach(instanceProperty -> {
1503                     toscaFunctionService.updateFunctionWithDataFromSelfComponent(instanceProperty.getToscaFunction(),
1504                         updatedService, instancePropertyMap, instanceAttributeMap);
1505                     instanceProperty.setValue(instanceProperty.getToscaFunction().getValue());
1506                 })
1507         );
1508     }
1509
1510     protected void processComponentInstance(String yamlName, Component component, List<ComponentInstance> componentInstancesList,
1511                                             Map<String, DataTypeDefinition> allDataTypes,
1512                                             Map<String, List<ComponentInstanceProperty>> instProperties,
1513                                             Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties,
1514                                             Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements,
1515                                             Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts,
1516                                             Map<String, Map<String, ArtifactDefinition>> instArtifacts,
1517                                             Map<String, List<AttributeDefinition>> instAttributes, Map<String, Resource> originCompMap,
1518                                             Map<String, List<ComponentInstanceInput>> instInputs,
1519                                             Map<String, UploadNodeFilterInfo> instNodeFilter,
1520                                             UploadComponentInstanceInfo uploadComponentInstanceInfo) {
1521         log.debug("enter ServiceImportBusinessLogic processComponentInstance");
1522         Optional<ComponentInstance> currentCompInstanceOpt = componentInstancesList.stream()
1523             .filter(i -> i.getName().equals(uploadComponentInstanceInfo.getName())).findFirst();
1524         if (currentCompInstanceOpt.isEmpty()) {
1525             log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(), component.getUniqueId());
1526             BeEcompErrorManager.getInstance()
1527                 .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE, component.getUniqueId(),
1528                     BeEcompErrorManager.ErrorSeverity.ERROR);
1529             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
1530             throw new ComponentException(responseFormat);
1531         }
1532         ComponentInstance currentCompInstance = currentCompInstanceOpt.get();
1533         String resourceInstanceId = currentCompInstance.getUniqueId();
1534         Resource originResource = getOriginResource(yamlName, originCompMap, currentCompInstance);
1535         if (MapUtils.isNotEmpty(originResource.getRequirements())) {
1536             instRequirements.put(currentCompInstance, originResource.getRequirements());
1537         }
1538         if (MapUtils.isNotEmpty(originResource.getCapabilities())) {
1539             processComponentInstanceCapabilities(allDataTypes, instCapabilties, uploadComponentInstanceInfo, currentCompInstance, originResource);
1540         }
1541         if (originResource.getDeploymentArtifacts() != null && !originResource.getDeploymentArtifacts().isEmpty()) {
1542             instDeploymentArtifacts.put(resourceInstanceId, originResource.getDeploymentArtifacts());
1543         }
1544         if (originResource.getArtifacts() != null && !originResource.getArtifacts().isEmpty()) {
1545             instArtifacts.put(resourceInstanceId, originResource.getArtifacts());
1546         }
1547         if (originResource.getAttributes() != null && !originResource.getAttributes().isEmpty()) {
1548             instAttributes.put(resourceInstanceId, originResource.getAttributes());
1549             addAttributeValueToResourceInstance(instAttributes, uploadComponentInstanceInfo.getAttributes());
1550         }
1551         if (uploadComponentInstanceInfo.getUploadNodeFilterInfo() != null) {
1552             instNodeFilter.put(resourceInstanceId, uploadComponentInstanceInfo.getUploadNodeFilterInfo());
1553         }
1554         if (originResource.getResourceType() != ResourceTypeEnum.VF) {
1555             ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, component, originResource,
1556                 currentCompInstance, instProperties, allDataTypes);
1557             if (addPropertiesValueToRiRes.getStatus() != 200) {
1558                 throw new ComponentException(addPropertiesValueToRiRes);
1559             }
1560         } else {
1561             addInputsValuesToRi(uploadComponentInstanceInfo, component, originResource, currentCompInstance, instInputs, allDataTypes);
1562         }
1563     }
1564
1565     protected void addInputsValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Component component, Resource originResource,
1566                                        ComponentInstance currentCompInstance, Map<String, List<ComponentInstanceInput>> instInputs,
1567                                        Map<String, DataTypeDefinition> allDataTypes) {
1568         Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
1569         try {
1570             if (MapUtils.isNotEmpty(propMap)) {
1571                 Map<String, InputDefinition> currPropertiesMap = new HashMap<>();
1572                 List<ComponentInstanceInput> instPropList = new ArrayList<>();
1573                 if (CollectionUtils.isEmpty(originResource.getInputs())) {
1574                     log.debug("failed to find properties ");
1575                     throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND));
1576                 }
1577                 originResource.getInputs().forEach(p -> serviceImportParseLogic.addInput(currPropertiesMap, p));
1578                 for (List<UploadPropInfo> propertyList : propMap.values()) {
1579                     processProperty(component, currentCompInstance, allDataTypes, currPropertiesMap, instPropList, propertyList);
1580                 }
1581                 currPropertiesMap.values().forEach(p -> instPropList.add(new ComponentInstanceInput(p)));
1582                 instInputs.put(currentCompInstance.getUniqueId(), instPropList);
1583             }
1584         } catch (Exception e) {
1585             log.debug("failed to add Inputs Values To Ri");
1586             throw new ComponentException(ActionStatus.GENERAL_ERROR);
1587         }
1588     }
1589
1590     protected void processProperty(Component component, ComponentInstance currentCompInstance, Map<String, DataTypeDefinition> allDataTypes,
1591                                    Map<String, InputDefinition> currPropertiesMap, List<ComponentInstanceInput> instPropList,
1592                                    List<UploadPropInfo> propertyList) {
1593         UploadPropInfo propertyInfo = propertyList.get(0);
1594         String propName = propertyInfo.getName();
1595         if (!currPropertiesMap.containsKey(propName)) {
1596             log.debug("failed to find property {} ", propName);
1597             throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName));
1598         }
1599         processProperty(allDataTypes, currPropertiesMap, instPropList, propertyInfo, propName, component.getInputs());
1600     }
1601
1602     protected void processGetInput(List<GetInputValueDataDefinition> getInputValues, List<InputDefinition> inputs,
1603                                    GetInputValueDataDefinition getInputIndex) {
1604         Optional<InputDefinition> optional;
1605         if (getInputIndex != null) {
1606             optional = inputs.stream().filter(p -> p.getName().equals(getInputIndex.getInputName())).findAny();
1607             if (!optional.isPresent()) {
1608                 log.debug("Failed to find input {} ", getInputIndex.getInputName());
1609                 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1610             }
1611             InputDefinition inputIndex = optional.get();
1612             getInputIndex.setInputId(inputIndex.getUniqueId());
1613             getInputValues.add(getInputIndex);
1614         }
1615     }
1616
1617     private void addAttributeValueToResourceInstance(Map<String, List<AttributeDefinition>> instAttributes,
1618                                                      Map<String, UploadAttributeInfo> attributeMap) {
1619         if (attributeMap == null) {
1620             return;
1621         }
1622         attributeMap.forEach((attributeName, attributeValue) -> instAttributes.values()
1623             .forEach(value -> value.stream().filter(attr -> attr.getName().equals(attributeName)).forEach(attr -> {
1624                 if (attributeValue.getValue() instanceof Collection<?> || attributeValue.getValue() instanceof Map<?, ?>) {
1625                     Gson gson = new Gson();
1626                     String json = gson.toJson(attributeValue.getValue());
1627                     attr.setValue(json);
1628                 } else {
1629                     attr.setValue(String.valueOf(attributeValue.getValue()));
1630                 }
1631             })));
1632     }
1633
1634     protected ResponseFormat addPropertyValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Component component,
1635                                                    Resource originResource, ComponentInstance currentCompInstance,
1636                                                    Map<String, List<ComponentInstanceProperty>> instProperties,
1637                                                    Map<String, DataTypeDefinition> allDataTypes) {
1638         Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
1639         Map<String, PropertyDefinition> currPropertiesMap = new HashMap<>();
1640         List<PropertyDefinition> originalPropertyList = originResource.getProperties();
1641         if (MapUtils.isNotEmpty(propMap) && CollectionUtils.isEmpty(originalPropertyList)) {
1642             log.debug("failed to find properties ");
1643             return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND);
1644         }
1645         if (CollectionUtils.isEmpty(originalPropertyList)) {
1646             return componentsUtils.getResponseFormat(ActionStatus.OK);
1647         }
1648         originalPropertyList.stream()
1649             .filter(property -> !currPropertiesMap.containsKey(property.getName()))
1650             .forEach(property -> currPropertiesMap.put(property.getName(), property));
1651         List<ComponentInstanceProperty> instPropList = new ArrayList<>();
1652         if (MapUtils.isNotEmpty(propMap)) {
1653             for (final List<UploadPropInfo> propertyList : propMap.values()) {
1654                 UploadPropInfo propertyInfo = propertyList.get(0);
1655                 String propName = propertyInfo.getName();
1656                 if (!currPropertiesMap.containsKey(propName)) {
1657                     log.debug("failed to find property {} ", propName);
1658                     return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName);
1659                 }
1660                 PropertyDefinition curPropertyDef = currPropertiesMap.get(propName);
1661                 String value = null;
1662                 final List<GetInputValueDataDefinition> getInputs = new ArrayList<>();
1663                 boolean isValidate = true;
1664                 if (propertyInfo.getValue() != null) {
1665                     getInputs.addAll(propertyInfo.getGet_input());
1666                     isValidate = getInputs.isEmpty();
1667                     if (isValidate) {
1668                         value = getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType());
1669                     } else {
1670                         value = getPropertyJsonStringValue(propertyInfo.getValue(), TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
1671                     }
1672                 }
1673                 final var property = new ComponentInstanceProperty(curPropertyDef, value, null);
1674                 String validatePropValue = serviceBusinessLogic.validatePropValueBeforeCreate(property, value, isValidate, allDataTypes);
1675                 property.setValue(validatePropValue);
1676                 property.setToscaFunction(propertyInfo.getToscaFunction());
1677                 if (!getInputs.isEmpty()) {
1678                     final List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
1679                     for (final GetInputValueDataDefinition getInput : getInputs) {
1680                         final List<InputDefinition> inputs = component.getInputs();
1681                         if (inputs == null || inputs.isEmpty()) {
1682                             log.debug("Failed to add property {} to instance. Inputs list is empty ", property);
1683                             serviceBusinessLogic.rollbackWithException(ActionStatus.INPUTS_NOT_FOUND,
1684                                 property.getGetInputValues().stream().map(GetInputValueDataDefinition::getInputName).collect(toList()).toString());
1685                         }
1686                         InputDefinition input = serviceImportParseLogic.findInputByName(inputs, getInput);
1687                         getInput.setInputId(input.getUniqueId());
1688                         getInputValues.add(getInput);
1689                         GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
1690                         if (getInputIndex != null) {
1691                             input = serviceImportParseLogic.findInputByName(inputs, getInputIndex);
1692                             getInputIndex.setInputId(input.getUniqueId());
1693                             getInputValues.add(getInputIndex);
1694                         }
1695                     }
1696                     property.setGetInputValues(getInputValues);
1697                 }
1698                 instPropList.add(property);
1699                 currPropertiesMap.remove(property.getName());
1700             }
1701         }
1702         if (!currPropertiesMap.isEmpty()) {
1703             for (PropertyDefinition value : currPropertiesMap.values()) {
1704                 instPropList.add(new ComponentInstanceProperty(value));
1705             }
1706         }
1707         instProperties.put(currentCompInstance.getUniqueId(), instPropList);
1708         return componentsUtils.getResponseFormat(ActionStatus.OK);
1709     }
1710
1711     protected void processComponentInstanceCapabilities(Map<String, DataTypeDefinition> allDataTypes,
1712                                                         Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties,
1713                                                         UploadComponentInstanceInfo uploadComponentInstanceInfo,
1714                                                         ComponentInstance currentCompInstance, Resource originResource) {
1715         log.debug("enter processComponentInstanceCapabilities");
1716         Map<String, List<CapabilityDefinition>> originCapabilities;
1717         if (MapUtils.isNotEmpty(uploadComponentInstanceInfo.getCapabilities())) {
1718             originCapabilities = new HashMap<>();
1719             Map<String, Map<String, UploadPropInfo>> newPropertiesMap = new HashMap<>();
1720             originResource.getCapabilities().forEach((k, v) -> serviceImportParseLogic.addCapabilities(originCapabilities, k, v));
1721             uploadComponentInstanceInfo.getCapabilities().values()
1722                 .forEach(l -> serviceImportParseLogic.addCapabilitiesProperties(newPropertiesMap, l));
1723             updateCapabilityPropertiesValues(allDataTypes, originCapabilities, newPropertiesMap);
1724         } else {
1725             originCapabilities = originResource.getCapabilities();
1726         }
1727         instCapabilties.put(currentCompInstance, originCapabilities);
1728     }
1729
1730     protected void updateCapabilityPropertiesValues(Map<String, DataTypeDefinition> allDataTypes,
1731                                                     Map<String, List<CapabilityDefinition>> originCapabilities,
1732                                                     Map<String, Map<String, UploadPropInfo>> newPropertiesMap) {
1733         originCapabilities.values().stream().flatMap(Collection::stream).filter(c -> newPropertiesMap.containsKey(c.getName()))
1734             .forEach(c -> updatePropertyValues(c.getProperties(), newPropertiesMap.get(c.getName()), allDataTypes));
1735     }
1736
1737     protected void updatePropertyValues(List<ComponentInstanceProperty> properties, Map<String, UploadPropInfo> newProperties,
1738                                         Map<String, DataTypeDefinition> allDataTypes) {
1739         properties.forEach(p -> updatePropertyValue(p, newProperties.get(p.getName()), allDataTypes));
1740     }
1741
1742     protected String updatePropertyValue(ComponentInstanceProperty property, UploadPropInfo propertyInfo,
1743                                          Map<String, DataTypeDefinition> allDataTypes) {
1744         String value = null;
1745         List<GetInputValueDataDefinition> getInputs = null;
1746         boolean isValidate = true;
1747         if (null != propertyInfo && propertyInfo.getValue() != null) {
1748             getInputs = propertyInfo.getGet_input();
1749             isValidate = getInputs == null || getInputs.isEmpty();
1750             if (isValidate) {
1751                 value = getPropertyJsonStringValue(propertyInfo.getValue(), property.getType());
1752             } else {
1753                 value = getPropertyJsonStringValue(propertyInfo.getValue(), TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
1754             }
1755         }
1756         property.setValue(value);
1757         return serviceBusinessLogic.validatePropValueBeforeCreate(property, value, isValidate, allDataTypes);
1758     }
1759
1760     protected Resource getOriginResource(String yamlName, Map<String, Resource> originCompMap, ComponentInstance currentCompInstance) {
1761         Resource originResource;
1762         log.debug("after enter ServiceImportBusinessLogic processComponentInstance, enter getOriginResource");
1763         if (!originCompMap.containsKey(currentCompInstance.getComponentUid())) {
1764             Either<Resource, StorageOperationStatus> getOriginResourceRes = toscaOperationFacade
1765                 .getToscaFullElement(currentCompInstance.getComponentUid());
1766             if (getOriginResourceRes.isRight()) {
1767                 ResponseFormat responseFormat = componentsUtils
1768                     .getResponseFormat(componentsUtils.convertFromStorageResponse(getOriginResourceRes.right().value()), yamlName);
1769                 throw new ComponentException(responseFormat);
1770             }
1771             originResource = getOriginResourceRes.left().value();
1772             originCompMap.put(originResource.getUniqueId(), originResource);
1773         } else {
1774             originResource = originCompMap.get(currentCompInstance.getComponentUid());
1775         }
1776         return originResource;
1777     }
1778
1779     protected Either<Resource, StorageOperationStatus> updateCalculatedCapReqWithSubstitutionMappings(Resource resource,
1780                                                                                                       Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
1781         Either<Resource, StorageOperationStatus> updateRes = null;
1782         Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities = new HashMap<>();
1783         Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements = new HashMap<>();
1784         StorageOperationStatus status = toscaOperationFacade.deleteAllCalculatedCapabilitiesRequirements(resource.getUniqueId());
1785         if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
1786             log.debug("Failed to delete all calculated capabilities and requirements of resource {} upon update. Status is {}",
1787                 resource.getUniqueId(), status);
1788             updateRes = Either.right(status);
1789         }
1790         if (updateRes == null) {
1791             fillUpdatedInstCapabilitiesRequirements(resource.getComponentInstances(), uploadResInstancesMap, updatedInstCapabilities,
1792                 updatedInstRequirements);
1793             status = toscaOperationFacade.associateOrAddCalculatedCapReq(updatedInstCapabilities, updatedInstRequirements, resource);
1794             if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
1795                 updateRes = Either.right(status);
1796             }
1797         }
1798         if (updateRes == null) {
1799             updateRes = Either.left(resource);
1800         }
1801         return updateRes;
1802     }
1803
1804     protected void fillUpdatedInstCapabilitiesRequirements(List<ComponentInstance> componentInstances,
1805                                                            Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
1806                                                            Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities,
1807                                                            Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements) {
1808         componentInstances.stream().forEach(i -> {
1809             fillUpdatedInstCapabilities(updatedInstCapabilities, i, uploadResInstancesMap.get(i.getName()).getCapabilitiesNamesToUpdate());
1810             fillUpdatedInstRequirements(updatedInstRequirements, i, uploadResInstancesMap.get(i.getName()).getRequirementsNamesToUpdate());
1811         });
1812     }
1813
1814     protected void fillUpdatedInstCapabilities(Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilties,
1815                                                ComponentInstance instance, Map<String, String> capabilitiesNamesToUpdate) {
1816         Map<String, List<CapabilityDefinition>> updatedCapabilities = new HashMap<>();
1817         Set<String> updatedCapNames = new HashSet<>();
1818         if (MapUtils.isNotEmpty(capabilitiesNamesToUpdate)) {
1819             for (Map.Entry<String, List<CapabilityDefinition>> requirements : instance.getCapabilities().entrySet()) {
1820                 updatedCapabilities.put(requirements.getKey(), requirements.getValue().stream().filter(
1821                         c -> capabilitiesNamesToUpdate.containsKey(c.getName()) && !updatedCapNames.contains(capabilitiesNamesToUpdate.get(c.getName())))
1822                     .map(c -> {
1823                         c.setParentName(c.getName());
1824                         c.setName(capabilitiesNamesToUpdate.get(c.getName()));
1825                         updatedCapNames.add(c.getName());
1826                         return c;
1827                     }).collect(toList()));
1828             }
1829         }
1830         if (MapUtils.isNotEmpty(updatedCapabilities)) {
1831             updatedInstCapabilties.put(instance, updatedCapabilities);
1832         }
1833     }
1834
1835     protected void fillUpdatedInstRequirements(Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements,
1836                                                ComponentInstance instance, Map<String, String> requirementsNamesToUpdate) {
1837         Map<String, List<RequirementDefinition>> updatedRequirements = new HashMap<>();
1838         Set<String> updatedReqNames = new HashSet<>();
1839         if (MapUtils.isNotEmpty(requirementsNamesToUpdate)) {
1840             for (Map.Entry<String, List<RequirementDefinition>> requirements : instance.getRequirements().entrySet()) {
1841                 updatedRequirements.put(requirements.getKey(), requirements.getValue().stream().filter(
1842                         r -> requirementsNamesToUpdate.containsKey(r.getName()) && !updatedReqNames.contains(requirementsNamesToUpdate.get(r.getName())))
1843                     .map(r -> {
1844                         r.setParentName(r.getName());
1845                         r.setName(requirementsNamesToUpdate.get(r.getName()));
1846                         updatedReqNames.add(r.getName());
1847                         return r;
1848                     }).collect(toList()));
1849             }
1850         }
1851         if (MapUtils.isNotEmpty(updatedRequirements)) {
1852             updatedInstRequirements.put(instance, updatedRequirements);
1853         }
1854     }
1855
1856     protected void addRelationsToRI(String yamlName, Service service, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
1857                                     List<ComponentInstance> componentInstancesList, List<RequirementCapabilityRelDef> relations) {
1858         for (Map.Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) {
1859             UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
1860             ComponentInstance currentCompInstance = null;
1861             for (ComponentInstance compInstance : componentInstancesList) {
1862                 if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
1863                     currentCompInstance = compInstance;
1864                     break;
1865                 }
1866             }
1867             if (currentCompInstance == null) {
1868                 log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(), service.getUniqueId());
1869                 BeEcompErrorManager.getInstance()
1870                     .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE, service.getUniqueId(),
1871                         BeEcompErrorManager.ErrorSeverity.ERROR);
1872                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
1873                 throw new ComponentException(responseFormat);
1874             }
1875             ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, service, entry.getValue(), relations);
1876             if (addRelationToRiRes.getStatus() != 200) {
1877                 throw new ComponentException(addRelationToRiRes);
1878             }
1879         }
1880     }
1881
1882     protected ResponseFormat addRelationToRI(String yamlName, Service service, UploadComponentInstanceInfo nodesInfoValue,
1883                                              List<RequirementCapabilityRelDef> relations) {
1884         List<ComponentInstance> componentInstancesList = service.getComponentInstances();
1885         ComponentInstance currentCompInstance = null;
1886         for (ComponentInstance compInstance : componentInstancesList) {
1887             if (compInstance.getName().equals(nodesInfoValue.getName())) {
1888                 currentCompInstance = compInstance;
1889                 break;
1890             }
1891         }
1892         if (currentCompInstance == null) {
1893             log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, nodesInfoValue.getName(), service.getUniqueId());
1894             BeEcompErrorManager.getInstance()
1895                 .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + nodesInfoValue.getName() + IN_RESOURCE, service.getUniqueId(),
1896                     BeEcompErrorManager.ErrorSeverity.ERROR);
1897             return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
1898         }
1899         String resourceInstanceId = currentCompInstance.getUniqueId();
1900         Map<String, List<UploadReqInfo>> regMap = nodesInfoValue.getRequirements();
1901         if (regMap != null) {
1902             Iterator<Map.Entry<String, List<UploadReqInfo>>> nodesRegValue = regMap.entrySet().iterator();
1903             while (nodesRegValue.hasNext()) {
1904                 Map.Entry<String, List<UploadReqInfo>> nodesRegInfoEntry = nodesRegValue.next();
1905                 List<UploadReqInfo> uploadRegInfoList = nodesRegInfoEntry.getValue();
1906                 for (UploadReqInfo uploadRegInfo : uploadRegInfoList) {
1907                     log.debug("Going to create  relation {}", uploadRegInfo.getName());
1908                     String regName = uploadRegInfo.getName();
1909                     RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef();
1910                     regCapRelDef.setFromNode(resourceInstanceId);
1911                     log.debug("try to find available requirement {} ", regName);
1912                     Either<RequirementDefinition, ResponseFormat> eitherReqStatus = serviceImportParseLogic
1913                         .findAvailableRequirement(regName, yamlName, nodesInfoValue, currentCompInstance, uploadRegInfo.getCapabilityName());
1914                     if (eitherReqStatus.isRight()) {
1915                         log.debug("failed to find available requirement {} status is {}", regName, eitherReqStatus.right().value());
1916                         return eitherReqStatus.right().value();
1917                     }
1918                     RequirementDefinition validReq = eitherReqStatus.left().value();
1919                     List<CapabilityRequirementRelationship> reqAndRelationshipPairList = regCapRelDef.getRelationships();
1920                     if (reqAndRelationshipPairList == null) {
1921                         reqAndRelationshipPairList = new ArrayList<>();
1922                     }
1923                     RelationshipInfo reqAndRelationshipPair = new RelationshipInfo();
1924                     reqAndRelationshipPair.setRequirement(regName);
1925                     reqAndRelationshipPair.setRequirementOwnerId(validReq.getOwnerId());
1926                     reqAndRelationshipPair.setRequirementUid(validReq.getUniqueId());
1927                     RelationshipImpl relationship = new RelationshipImpl();
1928                     relationship.setType(validReq.getCapability());
1929                     reqAndRelationshipPair.setRelationships(relationship);
1930                     ComponentInstance currentCapCompInstance = null;
1931                     for (ComponentInstance compInstance : componentInstancesList) {
1932                         if (compInstance.getName().equals(uploadRegInfo.getNode())) {
1933                             currentCapCompInstance = compInstance;
1934                             break;
1935                         }
1936                     }
1937                     if (currentCapCompInstance == null) {
1938                         log.debug("The component instance  with name {} not found on resource {} ", uploadRegInfo.getNode(), service.getUniqueId());
1939                         BeEcompErrorManager.getInstance()
1940                             .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + uploadRegInfo.getNode() + IN_RESOURCE, service.getUniqueId(),
1941                                 BeEcompErrorManager.ErrorSeverity.ERROR);
1942                         return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
1943                     }
1944                     regCapRelDef.setToNode(currentCapCompInstance.getUniqueId());
1945                     log.debug("try to find aviable Capability  req name is {} ", validReq.getName());
1946                     CapabilityDefinition aviableCapForRel = serviceImportParseLogic
1947                         .findAvailableCapabilityByTypeOrName(validReq, currentCapCompInstance, uploadRegInfo);
1948                     if (aviableCapForRel == null) {
1949                         BeEcompErrorManager.getInstance().logInternalDataError(
1950                             "aviable capability was not found. req name is " + validReq.getName() + " component instance is " + currentCapCompInstance
1951                                 .getUniqueId(), service.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR);
1952                         return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
1953                     }
1954                     reqAndRelationshipPair.setCapability(aviableCapForRel.getName());
1955                     reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId());
1956                     reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId());
1957                     CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship();
1958                     capReqRel.setRelation(reqAndRelationshipPair);
1959                     if (StringUtils.isNotEmpty(uploadRegInfo.getRelationshipTemplate())) {
1960                         capReqRel.setOperations(getOperations(nodesInfoValue.getOperations(), uploadRegInfo.getRelationshipTemplate()));
1961                     }
1962                     reqAndRelationshipPairList.add(capReqRel);
1963                     regCapRelDef.setRelationships(reqAndRelationshipPairList);
1964                     relations.add(regCapRelDef);
1965                 }
1966             }
1967         }
1968         return componentsUtils.getResponseFormat(ActionStatus.OK, yamlName);
1969     }
1970
1971     private List<OperationUi> getOperations(final Map<String, List<OperationUi>> operations, final String relationshipTemplate) {
1972         final List<OperationUi> operationUiList = new ArrayList<>();
1973         operations.forEach((operationKey, operationValues) -> {
1974             if (operationKey.equals(relationshipTemplate)) {
1975                 operationUiList.addAll(operationValues);
1976             }
1977         });
1978         return operationUiList;
1979     }
1980
1981     protected Service getResourceAfterCreateRelations(Service service) {
1982         ComponentParametersView parametersView = serviceImportParseLogic.getComponentFilterAfterCreateRelations();
1983         Either<Service, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(service.getUniqueId(), parametersView);
1984         if (eitherGetResource.isRight()) {
1985             serviceImportParseLogic.throwComponentExceptionByResource(eitherGetResource.right().value(), service);
1986         }
1987         return eitherGetResource.left().value();
1988     }
1989
1990     protected Service createServiceInstances(String yamlName, Service service, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
1991                                              Map<String, Resource> nodeNamespaceMap) {
1992         Either<Resource, ResponseFormat> eitherResource = null;
1993         log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName);
1994         if (MapUtils.isEmpty(uploadResInstancesMap)) { // PNF can have no resource instances
1995             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
1996             throw new ComponentException(responseFormat);
1997         }
1998         Map<String, Resource> existingNodeTypeMap = new HashMap<>();
1999         if (MapUtils.isNotEmpty(nodeNamespaceMap)) {
2000             nodeNamespaceMap.forEach((k, v) -> existingNodeTypeMap.put(v.getToscaResourceName(), v));
2001         }
2002         Map<ComponentInstance, Resource> resourcesInstancesMap = new HashMap<>();
2003         uploadResInstancesMap.values()
2004             .forEach(i -> createAndAddResourceInstance(i, yamlName, service, nodeNamespaceMap, existingNodeTypeMap, resourcesInstancesMap));
2005         if (MapUtils.isNotEmpty(resourcesInstancesMap)) {
2006             try {
2007                 toscaOperationFacade.associateComponentInstancesToComponent(service, resourcesInstancesMap, false, false);
2008             } catch (StorageException exp) {
2009                 if (exp.getStorageOperationStatus() != null && exp.getStorageOperationStatus() != StorageOperationStatus.OK) {
2010                     log.debug("Failed to add component instances to container component {}", service.getName());
2011                     ResponseFormat responseFormat = componentsUtils
2012                         .getResponseFormat(componentsUtils.convertFromStorageResponse(exp.getStorageOperationStatus()));
2013                     eitherResource = Either.right(responseFormat);
2014                     throw new ComponentException(eitherResource.right().value());
2015                 }
2016             }
2017         }
2018         Either<Service, StorageOperationStatus> eitherGetResource = toscaOperationFacade
2019             .getToscaElement(service.getUniqueId(), serviceImportParseLogic.getComponentWithInstancesFilter());
2020         log.debug("*************finished to get resource {}", service.getUniqueId());
2021         if (eitherGetResource.isRight()) {
2022             ResponseFormat responseFormat = componentsUtils
2023                 .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), service,
2024                     ComponentTypeEnum.SERVICE);
2025             throw new ComponentException(responseFormat);
2026         }
2027         if (CollectionUtils.isEmpty(eitherGetResource.left().value().getComponentInstances())) { // PNF can have no resource instances
2028             log.debug("Error when create resource instance from csar. ComponentInstances list empty");
2029             BeEcompErrorManager.getInstance().logBeDaoSystemError("Error when create resource instance from csar. ComponentInstances list empty");
2030             throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
2031         }
2032         return eitherGetResource.left().value();
2033     }
2034
2035     protected void createAndAddResourceInstance(UploadComponentInstanceInfo uploadComponentInstanceInfo, String yamlName, Component component,
2036                                                 Map<String, Resource> nodeNamespaceMap, Map<String, Resource> existingnodeTypeMap,
2037                                                 Map<ComponentInstance, Resource> resourcesInstancesMap) {
2038         log.debug("*************Going to create  resource instances {}", uploadComponentInstanceInfo.getName());
2039         try {
2040             if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
2041                 uploadComponentInstanceInfo.setType(nodeNamespaceMap.get(uploadComponentInstanceInfo.getType()).getToscaResourceName());
2042             }
2043             Resource refResource = validateResourceInstanceBeforeCreate(yamlName, uploadComponentInstanceInfo, existingnodeTypeMap);
2044             ComponentInstance componentInstance = new ComponentInstance();
2045             componentInstance.setComponentUid(refResource.getUniqueId());
2046             Collection<String> directives = uploadComponentInstanceInfo.getDirectives();
2047             if (directives != null && !directives.isEmpty()) {
2048                 componentInstance.setDirectives(new ArrayList<>(directives));
2049             }
2050             UploadNodeFilterInfo uploadNodeFilterInfo = uploadComponentInstanceInfo.getUploadNodeFilterInfo();
2051             if (uploadNodeFilterInfo != null) {
2052                 componentInstance
2053                     .setNodeFilter(new CINodeFilterUtils().getNodeFilterDataDefinition(uploadNodeFilterInfo, componentInstance.getUniqueId()));
2054             }
2055             ComponentTypeEnum containerComponentType = component.getComponentType();
2056             NodeTypeEnum containerNodeType = containerComponentType.getNodeType();
2057             if (containerNodeType.equals(NodeTypeEnum.Resource) && MapUtils.isNotEmpty(uploadComponentInstanceInfo.getCapabilities()) && MapUtils
2058                 .isNotEmpty(refResource.getCapabilities())) {
2059                 serviceImportParseLogic.setCapabilityNamesTypes(refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities());
2060                 Map<String, List<CapabilityDefinition>> validComponentInstanceCapabilities = serviceImportParseLogic
2061                     .getValidComponentInstanceCapabilities(refResource.getUniqueId(), refResource.getCapabilities(),
2062                         uploadComponentInstanceInfo.getCapabilities());
2063                 componentInstance.setCapabilities(validComponentInstanceCapabilities);
2064             }
2065             if (!existingnodeTypeMap.containsKey(uploadComponentInstanceInfo.getType())) {
2066                 ResponseFormat responseFormat = componentsUtils
2067                     .getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(),
2068                         uploadComponentInstanceInfo.getType());
2069                 throw new ComponentException(responseFormat);
2070             }
2071             Resource origResource = existingnodeTypeMap.get(uploadComponentInstanceInfo.getType());
2072             componentInstance.setName(uploadComponentInstanceInfo.getName());
2073             componentInstance.setIcon(origResource.getIcon());
2074             resourcesInstancesMap.put(componentInstance, origResource);
2075         } catch (Exception e) {
2076             throw new ComponentException(ActionStatus.GENERAL_ERROR, e.getMessage());
2077         }
2078     }
2079
2080     protected Resource validateResourceInstanceBeforeCreate(String yamlName, UploadComponentInstanceInfo uploadComponentInstanceInfo,
2081                                                             Map<String, Resource> nodeNamespaceMap) {
2082         Resource refResource;
2083         try {
2084             if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
2085                 refResource = nodeNamespaceMap.get(uploadComponentInstanceInfo.getType());
2086             } else {
2087                 Either<Resource, StorageOperationStatus> findResourceEither = toscaOperationFacade
2088                     .getLatestResourceByToscaResourceName(uploadComponentInstanceInfo.getType());
2089                 if (findResourceEither.isRight()) {
2090                     ResponseFormat responseFormat = componentsUtils
2091                         .getResponseFormat(componentsUtils.convertFromStorageResponse(findResourceEither.right().value()));
2092                     throw new ComponentException(responseFormat);
2093                 }
2094                 refResource = findResourceEither.left().value();
2095                 nodeNamespaceMap.put(refResource.getToscaResourceName(), refResource);
2096             }
2097             String componentState = refResource.getComponentMetadataDefinition().getMetadataDataDefinition().getState();
2098             if (componentState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
2099                 ResponseFormat responseFormat = componentsUtils
2100                     .getResponseFormat(ActionStatus.ILLEGAL_COMPONENT_STATE, refResource.getComponentType().getValue(), refResource.getName(),
2101                         componentState);
2102                 throw new ComponentException(responseFormat);
2103             }
2104             if (!ModelConverter.isAtomicComponent(refResource) && refResource.getResourceType() != ResourceTypeEnum.VF) {
2105                 log.debug("validateResourceInstanceBeforeCreate -  ref resource type is  ", refResource.getResourceType());
2106                 ResponseFormat responseFormat = componentsUtils
2107                     .getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(),
2108                         uploadComponentInstanceInfo.getType());
2109                 throw new ComponentException(responseFormat);
2110             }
2111             return refResource;
2112         } catch (Exception e) {
2113             throw new ComponentException(ActionStatus.GENERAL_ERROR, e.getMessage());
2114         }
2115     }
2116
2117     protected void handleServiceNodeTypes(String yamlName, Service service, String topologyTemplateYaml, boolean needLock,
2118                                           Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
2119                                           List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
2120                                           CsarInfo csarInfo, String nodeName) {
2121         try {
2122             for (Map.Entry<String, NodeTypeInfo> nodeTypeEntry : nodeTypesInfo.entrySet()) {
2123                 boolean isResourceNotExisted = validateResourceNotExisted(nodeTypeEntry.getKey());
2124                 if (nodeTypeEntry.getValue().isNested() && isResourceNotExisted) {
2125                     handleNestedVF(service, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
2126                         nodeTypeEntry.getKey());
2127                     log.trace("************* finished to create node {}", nodeTypeEntry.getKey());
2128                 }
2129             }
2130             Map<String, Object> mappedToscaTemplate = null;
2131             if (org.apache.commons.lang.StringUtils.isNotEmpty(nodeName) && MapUtils.isNotEmpty(nodeTypesInfo) && nodeTypesInfo
2132                 .containsKey(nodeName)) {
2133                 mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate();
2134             }
2135             if (MapUtils.isEmpty(mappedToscaTemplate)) {
2136                 mappedToscaTemplate = (Map<String, Object>) new Yaml().load(topologyTemplateYaml);
2137             }
2138             createResourcesFromYamlNodeTypesList(yamlName, service, mappedToscaTemplate, needLock, nodeTypesArtifactsToHandle,
2139                 nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo);
2140         } catch (ComponentException | StorageException e) {
2141             throw e;
2142         } catch (Exception e) {
2143             log.debug("Exception occured when handleServiceNodeTypes, error is:{}", e.getMessage(), e);
2144             throw new ComponentException(ActionStatus.GENERAL_ERROR);
2145         }
2146     }
2147
2148     protected boolean validateResourceNotExisted(String type) {
2149         try {
2150             Either<Resource, StorageOperationStatus> latestResource = toscaOperationFacade.getLatestResourceByToscaResourceName(type);
2151             return latestResource.isRight();
2152         } catch (Exception e) {
2153             log.debug("Exception occured when validateResourceNotExisted, error is:{}", e.getMessage(), e);
2154             throw new ComponentException(ActionStatus.GENERAL_ERROR);
2155         }
2156     }
2157
2158     protected Resource handleNestedVF(Service service,
2159                                       Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
2160                                       List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
2161                                       String nodeName) {
2162         try {
2163             String yamlName = nodesInfo.get(nodeName).getTemplateFileName();
2164             Map<String, Object> nestedVfcJsonMap = nodesInfo.get(nodeName).getMappedToscaTemplate();
2165             createResourcesFromYamlNodeTypesList(yamlName, service, nestedVfcJsonMap, false, nodesArtifactsToHandle, createdArtifacts, nodesInfo,
2166                 csarInfo);
2167             log.debug("************* Finished to create node types from yaml {}", yamlName);
2168             if (nestedVfcJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) {
2169                 log.debug("************* Going to handle complex VFC from yaml {}", yamlName);
2170                 return handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName);
2171             }
2172             return new Resource();
2173         } catch (Exception e) {
2174             log.debug("Exception occured when handleNestedVF, error is:{}", e.getMessage(), e);
2175             throw new ComponentException(ActionStatus.GENERAL_ERROR);
2176         }
2177     }
2178
2179     protected Resource handleComplexVfc(
2180         Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
2181         List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo, String nodeName, String yamlName) {
2182         try {
2183             Resource oldComplexVfc = null;
2184             Resource newComplexVfc = serviceImportParseLogic.buildValidComplexVfc(csarInfo, nodeName, nodesInfo);
2185             Either<Resource, StorageOperationStatus> oldComplexVfcRes = toscaOperationFacade
2186                 .getFullLatestComponentByToscaResourceName(newComplexVfc.getToscaResourceName());
2187             if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() == StorageOperationStatus.NOT_FOUND) {
2188                 oldComplexVfcRes = toscaOperationFacade.getFullLatestComponentByToscaResourceName(
2189                     serviceImportParseLogic.buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), csarInfo.getVfResourceName(), nodeName)
2190                         .getRight());
2191             }
2192             if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() != StorageOperationStatus.NOT_FOUND) {
2193                 log.debug("Failed to fetch previous complex VFC by tosca resource name {}. Status is {}. ", newComplexVfc.getToscaResourceName(),
2194                     oldComplexVfcRes.right().value());
2195                 throw new ComponentException(ActionStatus.GENERAL_ERROR);
2196             } else if (oldComplexVfcRes.isLeft()) {
2197                 log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
2198                 Either<Boolean, ResponseFormat> eitherValidation = serviceImportParseLogic
2199                     .validateNestedDerivedFromDuringUpdate(oldComplexVfcRes.left().value(), newComplexVfc,
2200                         ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion()));
2201                 if (eitherValidation.isLeft()) {
2202                     oldComplexVfc = oldComplexVfcRes.left().value();
2203                 }
2204             }
2205             newComplexVfc = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName, oldComplexVfc,
2206                 newComplexVfc);
2207             csarInfo.getCreatedNodesToscaResourceNames().put(nodeName, newComplexVfc.getToscaResourceName());
2208             LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
2209                 LifecycleChangeInfoWithAction.LifecycleChanceActionEnum.CREATE_FROM_CSAR);
2210             log.debug("Going to certify cvfc {}. ", newComplexVfc.getName());
2211             final Resource result = serviceImportParseLogic
2212                 .propagateStateToCertified(csarInfo.getModifier(), newComplexVfc, lifecycleChangeInfo, true, false, true);
2213             csarInfo.getCreatedNodes().put(nodeName, result);
2214             csarInfo.removeNodeFromQueue();
2215             return result;
2216         } catch (Exception e) {
2217             log.debug("Exception occured when handleComplexVfc, error is:{}", e.getMessage(), e);
2218             throw new ComponentException(ActionStatus.GENERAL_ERROR);
2219         }
2220     }
2221
2222     protected Resource handleComplexVfc(
2223         Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
2224         List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo, String nodeName, String yamlName,
2225         Resource oldComplexVfc, Resource newComplexVfc) {
2226         Resource handleComplexVfcRes;
2227         try {
2228             Map<String, Object> mappedToscaTemplate = nodesInfo.get(nodeName).getMappedToscaTemplate();
2229             String yamlContent = new String(csarInfo.getCsar().get(yamlName));
2230             Map<String, NodeTypeInfo> newNodeTypesInfo = nodesInfo.entrySet().stream()
2231                 .collect(toMap(Map.Entry::getKey, e -> e.getValue().getUnmarkedCopy()));
2232             CsarInfo.markNestedVfc(mappedToscaTemplate, newNodeTypesInfo);
2233             if (oldComplexVfc == null) {
2234                 handleComplexVfcRes = createResourceFromYaml(newComplexVfc, yamlContent, yamlName, newNodeTypesInfo, csarInfo, nodesArtifactsToHandle,
2235                     false, true, nodeName);
2236             } else {
2237                 handleComplexVfcRes = updateResourceFromYaml(oldComplexVfc, newComplexVfc, AuditingActionEnum.UPDATE_RESOURCE_METADATA,
2238                     createdArtifacts, yamlContent, yamlName, csarInfo, newNodeTypesInfo, nodesArtifactsToHandle, nodeName, true);
2239             }
2240             return handleComplexVfcRes;
2241         } catch (Exception e) {
2242             log.debug("Exception occured when handleComplexVfc, error is:{}", e.getMessage(), e);
2243             throw new ComponentException(ActionStatus.GENERAL_ERROR);
2244         }
2245     }
2246
2247     protected Resource updateResourceFromYaml(Resource oldRresource, Resource newRresource, AuditingActionEnum actionEnum,
2248                                               List<ArtifactDefinition> createdArtifacts, String yamlFileName, String yamlFileContent,
2249                                               CsarInfo csarInfo, Map<String, NodeTypeInfo> nodeTypesInfo,
2250                                               Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
2251                                               String nodeName, boolean isNested) {
2252         boolean inTransaction = true;
2253         boolean shouldLock = false;
2254         Resource preparedResource = null;
2255         ParsedToscaYamlInfo uploadComponentInstanceInfoMap = null;
2256         try {
2257             uploadComponentInstanceInfoMap = csarBusinessLogic
2258                 .getParsedToscaYamlInfo(yamlFileContent, yamlFileName, nodeTypesInfo, csarInfo, nodeName, oldRresource);
2259             Map<String, UploadComponentInstanceInfo> instances = uploadComponentInstanceInfoMap.getInstances();
2260             if (MapUtils.isEmpty(instances) && newRresource.getResourceType() != ResourceTypeEnum.PNF) {
2261                 throw new ComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlFileName);
2262             }
2263             preparedResource = updateExistingResourceByImport(newRresource, oldRresource, csarInfo.getModifier(), inTransaction, shouldLock,
2264                 isNested).left;
2265             log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContent);
2266             serviceImportParseLogic.handleResourceGenericType(preparedResource);
2267             handleNodeTypes(yamlFileName, preparedResource, yamlFileContent, shouldLock, nodeTypesArtifactsToHandle, createdArtifacts, nodeTypesInfo,
2268                 csarInfo, nodeName);
2269             preparedResource = serviceImportParseLogic.createInputsOnResource(preparedResource, uploadComponentInstanceInfoMap.getInputs());
2270             preparedResource = createResourceInstances(yamlFileName, preparedResource, instances, csarInfo.getCreatedNodes());
2271             preparedResource = createResourceInstancesRelations(csarInfo.getModifier(), yamlFileName, preparedResource, instances);
2272         } catch (ComponentException e) {
2273             ResponseFormat responseFormat =
2274                 e.getResponseFormat() == null ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
2275             log.debug("#updateResourceFromYaml - failed to update resource from yaml {} .The error is {}", yamlFileName, responseFormat);
2276             componentsUtils
2277                 .auditResource(responseFormat, csarInfo.getModifier(), preparedResource == null ? oldRresource : preparedResource, actionEnum);
2278             throw e;
2279         } catch (StorageException e) {
2280             ResponseFormat responseFormat = componentsUtils
2281                 .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
2282             log.debug("#updateResourceFromYaml - failed to update resource from yaml {} .The error is {}", yamlFileName, responseFormat);
2283             componentsUtils
2284                 .auditResource(responseFormat, csarInfo.getModifier(), preparedResource == null ? oldRresource : preparedResource, actionEnum);
2285             throw e;
2286         }
2287         Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic.validateUpdateVfGroupNames(
2288             uploadComponentInstanceInfoMap.getGroups(), preparedResource.getSystemName());
2289         if (validateUpdateVfGroupNamesRes.isRight()) {
2290             throw new ComponentException(validateUpdateVfGroupNamesRes.right().value());
2291         }
2292         Map<String, GroupDefinition> groups;
2293         if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
2294             groups = validateUpdateVfGroupNamesRes.left().value();
2295         } else {
2296             groups = uploadComponentInstanceInfoMap.getGroups();
2297         }
2298         serviceImportParseLogic.handleGroupsProperties(preparedResource, groups);
2299         preparedResource = serviceImportParseLogic.updateGroupsOnResource(preparedResource, groups);
2300         NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName, nodeTypesArtifactsToHandle);
2301         Either<Resource, ResponseFormat> updateArtifactsEither = createOrUpdateArtifacts(ArtifactsBusinessLogic.ArtifactOperationEnum.UPDATE,
2302             createdArtifacts, yamlFileName, csarInfo, preparedResource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
2303         if (updateArtifactsEither.isRight()) {
2304             log.debug("failed to update artifacts {}", updateArtifactsEither.right().value());
2305             throw new ComponentException(updateArtifactsEither.right().value());
2306         }
2307         preparedResource = serviceImportParseLogic.getResourceWithGroups(updateArtifactsEither.left().value().getUniqueId());
2308         ActionStatus mergingPropsAndInputsStatus = resourceDataMergeBusinessLogic.mergeResourceEntities(oldRresource, preparedResource);
2309         if (mergingPropsAndInputsStatus != ActionStatus.OK) {
2310             ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(mergingPropsAndInputsStatus, preparedResource);
2311             throw new ComponentException(responseFormat);
2312         }
2313         compositionBusinessLogic.setPositionsForComponentInstances(preparedResource, csarInfo.getModifier().getUserId());
2314         return preparedResource;
2315     }
2316
2317     protected Resource createResourceFromYaml(Resource resource, String topologyTemplateYaml, String yamlName,
2318                                               Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
2319                                               Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
2320                                               boolean shouldLock, boolean inTransaction, String nodeName) {
2321         List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
2322         Resource createdResource;
2323         try {
2324             ParsedToscaYamlInfo parsedToscaYamlInfo = csarBusinessLogic
2325                 .getParsedToscaYamlInfo(topologyTemplateYaml, yamlName, nodeTypesInfo, csarInfo, nodeName, resource);
2326             if (MapUtils.isEmpty(parsedToscaYamlInfo.getInstances()) && resource.getResourceType() != ResourceTypeEnum.PNF) {
2327                 throw new ComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2328             }
2329             log.debug("#createResourceFromYaml - Going to create resource {} and RIs ", resource.getName());
2330             createdResource = createResourceAndRIsFromYaml(yamlName, resource, parsedToscaYamlInfo, AuditingActionEnum.IMPORT_RESOURCE, false,
2331                 createdArtifacts, topologyTemplateYaml, nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, shouldLock, inTransaction, nodeName);
2332             log.debug("#createResourceFromYaml - The resource {} has been created ", resource.getName());
2333         } catch (ComponentException e) {
2334             ResponseFormat responseFormat =
2335                 e.getResponseFormat() == null ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
2336             componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
2337             throw e;
2338         } catch (StorageException e) {
2339             ResponseFormat responseFormat = componentsUtils
2340                 .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
2341             componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
2342             throw e;
2343         }
2344         return createdResource;
2345     }
2346
2347     protected Resource createResourceAndRIsFromYaml(String yamlName, Resource resource, ParsedToscaYamlInfo parsedToscaYamlInfo,
2348                                                     AuditingActionEnum actionEnum, boolean isNormative, List<ArtifactDefinition> createdArtifacts,
2349                                                     String topologyTemplateYaml, Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
2350                                                     Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
2351                                                     boolean shouldLock, boolean inTransaction, String nodeName) {
2352         List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>();
2353         if (shouldLock) {
2354             Either<Boolean, ResponseFormat> lockResult = serviceBusinessLogic
2355                 .lockComponentByName(resource.getSystemName(), resource, CREATE_RESOURCE);
2356             if (lockResult.isRight()) {
2357                 serviceImportParseLogic.rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
2358                 throw new ComponentException(lockResult.right().value());
2359             }
2360             log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
2361         }
2362         try {
2363             log.trace("************* createResourceFromYaml before full create resource {}", yamlName);
2364             Resource genericResource = serviceBusinessLogic.fetchAndSetDerivedFromGenericType(resource);
2365             resource = createResourceTransaction(resource, csarInfo.getModifier(), isNormative);
2366             log.trace("************* Going to add inputs from yaml {}", yamlName);
2367             Map<String, Object> yamlMap = ImportUtils.loadYamlAsStrictMap(csarInfo.getMainTemplateContent());
2368             Map<String, Object> metadata = (Map<String, Object>) yamlMap.get("metadata");
2369             String type = (String) metadata.get("type");
2370             if (resource.shouldGenerateInputs() && !"Service".equalsIgnoreCase(type)) {
2371                 serviceBusinessLogic.generateAndAddInputsFromGenericTypeProperties(resource, genericResource);
2372             }
2373             Map<String, InputDefinition> inputs = parsedToscaYamlInfo.getInputs();
2374             resource = serviceImportParseLogic.createInputsOnResource(resource, inputs);
2375             Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap = parsedToscaYamlInfo.getInstances();
2376             resource = createRIAndRelationsFromYaml(yamlName, resource, uploadComponentInstanceInfoMap, topologyTemplateYaml,
2377                 nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, nodeName);
2378             log.trace("************* Finished to create nodes, RI and Relation  from yaml {}", yamlName);
2379             // validate update vf module group names
2380             Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic.validateUpdateVfGroupNames(
2381                 parsedToscaYamlInfo.getGroups(), resource.getSystemName());
2382             if (validateUpdateVfGroupNamesRes.isRight()) {
2383                 serviceImportParseLogic.rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
2384                 throw new ComponentException(validateUpdateVfGroupNamesRes.right().value());
2385             }
2386             Map<String, GroupDefinition> groups;
2387             log.trace("************* Going to add groups from yaml {}", yamlName);
2388             if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
2389                 groups = validateUpdateVfGroupNamesRes.left().value();
2390             } else {
2391                 groups = parsedToscaYamlInfo.getGroups();
2392             }
2393             Either<Resource, ResponseFormat> createGroupsOnResource = createGroupsOnResource(resource, groups);
2394             if (createGroupsOnResource.isRight()) {
2395                 serviceImportParseLogic.rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
2396                 throw new ComponentException(createGroupsOnResource.right().value());
2397             }
2398             resource = createGroupsOnResource.left().value();
2399             log.trace("************* Going to add artifacts from yaml {}", yamlName);
2400             NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName, nodeTypesArtifactsToCreate);
2401             Either<Resource, ResponseFormat> createArtifactsEither = createOrUpdateArtifacts(ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE,
2402                 createdArtifacts, yamlName, csarInfo, resource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
2403             if (createArtifactsEither.isRight()) {
2404                 serviceImportParseLogic.rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
2405                 throw new ComponentException(createArtifactsEither.right().value());
2406             }
2407             resource = serviceImportParseLogic.getResourceWithGroups(createArtifactsEither.left().value().getUniqueId());
2408             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
2409             componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, actionEnum);
2410             ASDCKpiApi.countCreatedResourcesKPI();
2411             return resource;
2412         } catch (ComponentException | StorageException e) {
2413             serviceImportParseLogic.rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
2414             throw e;
2415         } finally {
2416             if (!inTransaction) {
2417                 janusGraphDao.commit();
2418             }
2419             if (shouldLock) {
2420                 graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(), NodeTypeEnum.Resource);
2421             }
2422         }
2423     }
2424
2425     protected Either<Resource, ResponseFormat> createGroupsOnResource(Resource resource, Map<String, GroupDefinition> groups) {
2426         if (groups != null && !groups.isEmpty()) {
2427             List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(groups, resource);
2428             serviceImportParseLogic.handleGroupsProperties(resource, groups);
2429             serviceImportParseLogic.fillGroupsFinalFields(groupsAsList);
2430             Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.createGroups(resource, groupsAsList, true);
2431             if (createGroups.isRight()) {
2432                 return Either.right(createGroups.right().value());
2433             }
2434         } else {
2435             return Either.left(resource);
2436         }
2437         Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
2438         if (updatedResource.isRight()) {
2439             ResponseFormat responseFormat = componentsUtils
2440                 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource);
2441             return Either.right(responseFormat);
2442         }
2443         return Either.left(updatedResource.left().value());
2444     }
2445
2446     protected List<GroupDefinition> updateGroupsMembersUsingResource(Map<String, GroupDefinition> groups, Resource component) {
2447         List<GroupDefinition> result = new ArrayList<>();
2448         List<ComponentInstance> componentInstances = component.getComponentInstances();
2449         if (groups != null) {
2450             for (Map.Entry<String, GroupDefinition> entry : groups.entrySet()) {
2451                 String groupName = entry.getKey();
2452                 GroupDefinition groupDefinition = entry.getValue();
2453                 GroupDefinition updatedGroupDefinition = new GroupDefinition(groupDefinition);
2454                 updatedGroupDefinition.setMembers(null);
2455                 Map<String, String> members = groupDefinition.getMembers();
2456                 if (members != null) {
2457                     updateGroupMembers(groups, updatedGroupDefinition, component, componentInstances, groupName, members);
2458                 }
2459                 result.add(updatedGroupDefinition);
2460             }
2461         }
2462         return result;
2463     }
2464
2465     protected void updateGroupMembers(Map<String, GroupDefinition> groups, GroupDefinition updatedGroupDefinition, Resource component,
2466                                       List<ComponentInstance> componentInstances, String groupName, Map<String, String> members) {
2467         Set<String> compInstancesNames = members.keySet();
2468         if (CollectionUtils.isEmpty(componentInstances)) {
2469             String membersAstString = compInstancesNames.stream().collect(joining(","));
2470             log.debug("The members: {}, in group: {}, cannot be found in component {}. There are no component instances.", membersAstString,
2471                 groupName, component.getNormalizedName());
2472             throw new ComponentException(componentsUtils
2473                 .getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, component.getNormalizedName(),
2474                     serviceImportParseLogic.getComponentTypeForResponse(component)));
2475         }
2476         Map<String, String> memberNames = componentInstances.stream().collect(toMap(ComponentInstance::getName, ComponentInstance::getUniqueId));
2477         memberNames.putAll(groups.keySet().stream().collect(toMap(g -> g, g -> "")));
2478         Map<String, String> relevantInstances = memberNames.entrySet().stream().filter(n -> compInstancesNames.contains(n.getKey()))
2479             .collect(toMap(Map.Entry::getKey, Map.Entry::getValue));
2480         if (relevantInstances == null || relevantInstances.size() != compInstancesNames.size()) {
2481             List<String> foundMembers = new ArrayList<>();
2482             if (relevantInstances != null) {
2483                 foundMembers = relevantInstances.keySet().stream().collect(toList());
2484             }
2485             compInstancesNames.removeAll(foundMembers);
2486             String membersAstString = compInstancesNames.stream().collect(joining(","));
2487             throw new ComponentException(componentsUtils
2488                 .getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, component.getNormalizedName(),
2489                     serviceImportParseLogic.getComponentTypeForResponse(component)));
2490         }
2491         updatedGroupDefinition.setMembers(relevantInstances);
2492     }
2493
2494     protected Resource createResourceTransaction(Resource resource, User user, boolean isNormative) {
2495         Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade
2496             .validateComponentNameExists(resource.getName(), resource.getResourceType(), resource.getComponentType());
2497         if (eitherValidation.isRight()) {
2498             ResponseFormat errorResponse = componentsUtils
2499                 .getResponseFormat(componentsUtils.convertFromStorageResponse(eitherValidation.right().value()));
2500             throw new ComponentException(errorResponse);
2501         }
2502         if (Boolean.TRUE.equals(eitherValidation.left().value())) {
2503             log.debug("resource with name: {}, already exists", resource.getName());
2504             ResponseFormat errorResponse = componentsUtils
2505                 .getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
2506             throw new ComponentException(errorResponse);
2507         }
2508         log.debug("send resource {} to dao for create", resource.getName());
2509         serviceImportParseLogic.createArtifactsPlaceHolderData(resource, user);
2510         if (!isNormative) {
2511             log.debug("enrich resource with creator, version and state");
2512             resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
2513             resource.setVersion(INITIAL_VERSION);
2514             resource.setHighestVersion(true);
2515             if (resource.getResourceType() != null && resource.getResourceType() != ResourceTypeEnum.VF) {
2516                 resource.setAbstract(false);
2517             }
2518         }
2519         return toscaOperationFacade.createToscaComponent(resource).left()
2520             .on(r -> serviceImportParseLogic.throwComponentExceptionByResource(r, resource));
2521     }
2522
2523     protected ImmutablePair<Resource, ActionStatus> updateExistingResourceByImport(Resource newResource, Resource oldResource, User user,
2524                                                                                    boolean inTransaction, boolean needLock, boolean isNested) {
2525         String lockedResourceId = oldResource.getUniqueId();
2526         log.debug("found resource: name={}, id={}, version={}, state={}", oldResource.getName(), lockedResourceId, oldResource.getVersion(),
2527             oldResource.getLifecycleState());
2528         ImmutablePair<Resource, ActionStatus> resourcePair = null;
2529         try {
2530             serviceBusinessLogic.lockComponent(lockedResourceId, oldResource, needLock, "Update Resource by Import");
2531             oldResource = serviceImportParseLogic.prepareResourceForUpdate(oldResource, newResource, user, inTransaction, false);
2532             serviceImportParseLogic.mergeOldResourceMetadataWithNew(oldResource, newResource);
2533             serviceImportParseLogic.validateResourceFieldsBeforeUpdate(oldResource, newResource, inTransaction, isNested);
2534             serviceImportParseLogic.validateCapabilityTypesCreate(user, serviceImportParseLogic.getCapabilityTypeOperation(), newResource,
2535                 AuditingActionEnum.IMPORT_RESOURCE, inTransaction);
2536             createNewResourceToOldResource(newResource, oldResource, user);
2537             Either<Resource, StorageOperationStatus> overrideResource = toscaOperationFacade.overrideComponent(newResource, oldResource);
2538             if (overrideResource.isRight()) {
2539                 ResponseFormat responseFormat = new ResponseFormat();
2540                 serviceBusinessLogic.throwComponentException(responseFormat);
2541             }
2542             log.debug("Resource updated successfully!!!");
2543             resourcePair = new ImmutablePair<>(overrideResource.left().value(), ActionStatus.OK);
2544             return resourcePair;
2545         } finally {
2546             if (resourcePair == null) {
2547                 BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
2548                 janusGraphDao.rollback();
2549             } else if (!inTransaction) {
2550                 janusGraphDao.commit();
2551             }
2552             if (needLock) {
2553                 log.debug("unlock resource {}", lockedResourceId);
2554                 graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
2555             }
2556         }
2557     }
2558
2559     protected void createNewResourceToOldResource(Resource newResource, Resource oldResource, User user) {
2560         newResource.setContactId(newResource.getContactId().toLowerCase());
2561         newResource.setCreatorUserId(user.getUserId());
2562         newResource.setCreatorFullName(user.getFullName());
2563         newResource.setLastUpdaterUserId(user.getUserId());
2564         newResource.setLastUpdaterFullName(user.getFullName());
2565         newResource.setUniqueId(oldResource.getUniqueId());
2566         newResource.setVersion(oldResource.getVersion());
2567         newResource.setInvariantUUID(oldResource.getInvariantUUID());
2568         newResource.setLifecycleState(oldResource.getLifecycleState());
2569         newResource.setUUID(oldResource.getUUID());
2570         newResource.setNormalizedName(oldResource.getNormalizedName());
2571         newResource.setSystemName(oldResource.getSystemName());
2572         if (oldResource.getCsarUUID() != null) {
2573             newResource.setCsarUUID(oldResource.getCsarUUID());
2574         }
2575         if (oldResource.getCsarVersionId() != null) {
2576             newResource.setCsarVersionId(oldResource.getCsarVersionId());
2577         }
2578         if (oldResource.getImportedToscaChecksum() != null) {
2579             newResource.setImportedToscaChecksum(oldResource.getImportedToscaChecksum());
2580         }
2581         if (newResource.getDerivedFromGenericType() == null || newResource.getDerivedFromGenericType().isEmpty()) {
2582             newResource.setDerivedFromGenericType(oldResource.getDerivedFromGenericType());
2583         }
2584         if (newResource.getDerivedFromGenericVersion() == null || newResource.getDerivedFromGenericVersion().isEmpty()) {
2585             newResource.setDerivedFromGenericVersion(oldResource.getDerivedFromGenericVersion());
2586         }
2587         if (newResource.getToscaArtifacts() == null || newResource.getToscaArtifacts().isEmpty()) {
2588             serviceBusinessLogic.setToscaArtifactsPlaceHolders(newResource, user);
2589         }
2590         if (newResource.getInterfaces() == null || newResource.getInterfaces().isEmpty()) {
2591             newResource.setInterfaces(oldResource.getInterfaces());
2592         }
2593         if (CollectionUtils.isEmpty(newResource.getProperties())) {
2594             newResource.setProperties(oldResource.getProperties());
2595         }
2596         if (newResource.getModel() == null) {
2597             newResource.setModel(oldResource.getModel());
2598         }
2599     }
2600
2601     protected Map<String, Resource> createResourcesFromYamlNodeTypesList(String yamlName, Service service, Map<String, Object> mappedToscaTemplate,
2602                                                                          boolean needLock,
2603                                                                          Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
2604                                                                          List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
2605                                                                          Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo) {
2606         try {
2607             Either<String, ImportUtils.ResultStatusEnum> toscaVersion = findFirstToscaStringElement(mappedToscaTemplate,
2608                 TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION);
2609             if (toscaVersion.isRight()) {
2610                 throw new ComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE);
2611             }
2612             Map<String, Object> mapToConvert = new HashMap<>();
2613             mapToConvert.put(TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION.getElementName(), toscaVersion.left().value());
2614             Map<String, Object> nodeTypes = serviceImportParseLogic.getNodeTypesFromTemplate(mappedToscaTemplate);
2615             createNodeTypes(yamlName, service, needLock, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
2616                     mapToConvert, nodeTypes);
2617             return csarInfo.getCreatedNodes();
2618         } catch (Exception e) {
2619             log.debug("Exception occured when createResourcesFromYamlNodeTypesList,error is:{}", e.getMessage(), e);
2620             throw new ComponentException(ActionStatus.GENERAL_ERROR);
2621         }
2622     }
2623
2624     protected void createNodeTypes(String yamlName, Service service, boolean needLock,
2625                                    Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
2626                                    List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
2627                                    Map<String, Object> mapToConvert, Map<String, Object> nodeTypes) {
2628         Iterator<Map.Entry<String, Object>> nodesNameValueIter = nodeTypes.entrySet().iterator();
2629         Resource vfcCreated = null;
2630         while (nodesNameValueIter.hasNext()) {
2631             Map.Entry<String, Object> nodeType = nodesNameValueIter.next();
2632             String nodeTypeKey = nodeType.getKey();
2633             Map<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle =
2634                 nodeTypesArtifactsToHandle == null || nodeTypesArtifactsToHandle.isEmpty() ? null : nodeTypesArtifactsToHandle.get(nodeTypeKey);
2635             if (nodeTypesInfo.containsKey(nodeTypeKey)) {
2636                 vfcCreated = handleNestedVfc(service, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
2637                     nodeTypeKey);
2638                 log.trace("************* Finished to handle nested vfc {}", nodeTypeKey);
2639             } else if (csarInfo.getCreatedNodesToscaResourceNames() != null && !csarInfo.getCreatedNodesToscaResourceNames()
2640                 .containsKey(nodeTypeKey)) {
2641                 ImmutablePair<Resource, ActionStatus> resourceCreated = serviceImportParseLogic
2642                     .createNodeTypeResourceFromYaml(yamlName, nodeType, csarInfo.getModifier(), mapToConvert, service, needLock,
2643                         nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, true, csarInfo, true);
2644                 log.debug("************* Finished to create node {}", nodeTypeKey);
2645                 vfcCreated = resourceCreated.getLeft();
2646                 csarInfo.getCreatedNodesToscaResourceNames().put(nodeTypeKey, vfcCreated.getName());
2647             }
2648             if (vfcCreated != null) {
2649                 csarInfo.getCreatedNodes().put(nodeTypeKey, vfcCreated);
2650             }
2651             mapToConvert.remove(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName());
2652         }
2653     }
2654 }