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