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