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