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