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