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