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