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