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