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