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