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