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