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