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