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