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