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