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