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