Service import issues
[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, uploadComponentInstanceInfo.getUploadNodeFilterInfo());
2017         }
2018         if (MapUtils.isNotEmpty(uploadComponentInstanceInfo.getInterfaces())) {
2019
2020             ResponseFormat addInterfacesToRiRes = addInterfaceValuesToRi(
2021                 uploadComponentInstanceInfo,
2022                 component,
2023                 originResource,
2024                 currentCompInstance,
2025                 instInterfaces
2026             );
2027             if (addInterfacesToRiRes.getStatus() != 200) {
2028                 throw new ComponentException(addInterfacesToRiRes);
2029             }
2030         }
2031         if (originResource.getResourceType() != ResourceTypeEnum.VF) {
2032             ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, component, originResource,
2033                 currentCompInstance, instProperties, allDataTypes);
2034             if (addPropertiesValueToRiRes.getStatus() != 200) {
2035                 throw new ComponentException(addPropertiesValueToRiRes);
2036             }
2037         } else {
2038             addInputsValuesToRi(uploadComponentInstanceInfo, component, originResource, currentCompInstance, instInputs, allDataTypes);
2039         }
2040     }
2041
2042     protected void addInputsValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Component component, Resource originResource,
2043                                        ComponentInstance currentCompInstance, Map<String, List<ComponentInstanceInput>> instInputs,
2044                                        Map<String, DataTypeDefinition> allDataTypes) {
2045         Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
2046         try {
2047             if (MapUtils.isNotEmpty(propMap)) {
2048                 Map<String, InputDefinition> currPropertiesMap = new HashMap<>();
2049                 List<ComponentInstanceInput> instPropList = new ArrayList<>();
2050                 if (CollectionUtils.isEmpty(originResource.getInputs())) {
2051                     log.debug("failed to find properties ");
2052                     throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND));
2053                 }
2054                 originResource.getInputs().forEach(p -> serviceImportParseLogic.addInput(currPropertiesMap, p));
2055                 for (List<UploadPropInfo> propertyList : propMap.values()) {
2056                     processProperty(component, allDataTypes, currPropertiesMap, instPropList, propertyList);
2057                 }
2058                 currPropertiesMap.values().forEach(p -> instPropList.add(new ComponentInstanceInput(p)));
2059                 instInputs.put(currentCompInstance.getUniqueId(), instPropList);
2060             }
2061         } catch (Exception e) {
2062             log.debug("failed to add Inputs Values To Ri");
2063             throw new ComponentException(ActionStatus.GENERAL_ERROR);
2064         }
2065     }
2066
2067     protected void processProperty(Component component, Map<String, DataTypeDefinition> allDataTypes,
2068                                    Map<String, InputDefinition> currPropertiesMap, List<ComponentInstanceInput> instPropList,
2069                                    List<UploadPropInfo> propertyList) {
2070         UploadPropInfo propertyInfo = propertyList.get(0);
2071         String propName = propertyInfo.getName();
2072         if (!currPropertiesMap.containsKey(propName)) {
2073             log.debug("failed to find property {} ", propName);
2074             throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName));
2075         }
2076         processProperty(allDataTypes, currPropertiesMap, instPropList, propertyInfo, propName, component.getInputs());
2077     }
2078
2079     protected void processGetInput(List<GetInputValueDataDefinition> getInputValues, List<InputDefinition> inputs,
2080                                    GetInputValueDataDefinition getInputIndex) {
2081         Optional<InputDefinition> optional;
2082         if (getInputIndex != null) {
2083             optional = inputs.stream().filter(p -> p.getName().equals(getInputIndex.getInputName())).findAny();
2084             if (!optional.isPresent()) {
2085                 log.debug("Failed to find input {} ", getInputIndex.getInputName());
2086                 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2087             }
2088             InputDefinition inputIndex = optional.get();
2089             getInputIndex.setInputId(inputIndex.getUniqueId());
2090             getInputValues.add(getInputIndex);
2091         }
2092     }
2093
2094     private void addAttributeValueToResourceInstance(Map<String, List<AttributeDefinition>> instAttributes,
2095                                                      Map<String, UploadAttributeInfo> attributeMap) {
2096         if (attributeMap == null) {
2097             return;
2098         }
2099         attributeMap.forEach((attributeName, attributeValue) -> instAttributes.values()
2100             .forEach(value -> value.stream().filter(attr -> attr.getName().equals(attributeName)).forEach(attr -> {
2101                 if (attributeValue.getValue() instanceof Collection<?> || attributeValue.getValue() instanceof Map<?, ?>) {
2102                     Gson gson = new Gson();
2103                     String json = gson.toJson(attributeValue.getValue());
2104                     attr.setValue(json);
2105                 } else {
2106                     attr.setValue(String.valueOf(attributeValue.getValue()));
2107                 }
2108             })));
2109     }
2110
2111     protected ResponseFormat addPropertyValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Component component,
2112                                                    Resource originResource, ComponentInstance currentCompInstance,
2113                                                    Map<String, List<ComponentInstanceProperty>> instProperties,
2114                                                    Map<String, DataTypeDefinition> allDataTypes) {
2115         Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
2116         Map<String, PropertyDefinition> currPropertiesMap = new HashMap<>();
2117         List<PropertyDefinition> originalPropertyList = originResource.getProperties();
2118         if (MapUtils.isNotEmpty(propMap) && CollectionUtils.isEmpty(originalPropertyList)) {
2119             log.debug("failed to find properties ");
2120             return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND);
2121         }
2122         if (CollectionUtils.isEmpty(originalPropertyList)) {
2123             return componentsUtils.getResponseFormat(ActionStatus.OK);
2124         }
2125         originalPropertyList.stream()
2126             .filter(property -> !currPropertiesMap.containsKey(property.getName()))
2127             .forEach(property -> currPropertiesMap.put(property.getName(), property));
2128         List<ComponentInstanceProperty> instPropList = new ArrayList<>();
2129         if (MapUtils.isNotEmpty(propMap)) {
2130             for (final List<UploadPropInfo> propertyList : propMap.values()) {
2131                 UploadPropInfo propertyInfo = propertyList.get(0);
2132                 String propName = propertyInfo.getName();
2133                 if (!currPropertiesMap.containsKey(propName)) {
2134                     log.debug("failed to find property {} ", propName);
2135                     return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName);
2136                 }
2137                 PropertyDefinition curPropertyDef = currPropertiesMap.get(propName);
2138                 String value = null;
2139                 final List<GetInputValueDataDefinition> getInputs = new ArrayList<>();
2140                 boolean isValidate = true;
2141                 if (propertyInfo.getValue() != null) {
2142                     getInputs.addAll(propertyInfo.getGet_input());
2143                     isValidate = getInputs.isEmpty();
2144                     if (isValidate) {
2145                         value = getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType());
2146                     } else {
2147                         value = getPropertyJsonStringValue(propertyInfo.getValue(), TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
2148                     }
2149                 }
2150                 final var property = new ComponentInstanceProperty(curPropertyDef, value, null);
2151                 String validatedPropValue = serviceBusinessLogic.validatePropValueBeforeCreate(property, value, true, allDataTypes);
2152
2153                 addSubPropertyYamlToscaFunctions(validatedPropValue, value, property.getType(), propertyInfo, allDataTypes);
2154
2155                 if (CollectionUtils.isNotEmpty(propertyInfo.getSubPropertyToscaFunctions())) {
2156                     validatedPropValue = value;
2157                 }
2158
2159                 property.setValue(validatedPropValue);
2160
2161                 if (tryHandlingAsYamlToscaFunction(validatedPropValue, value, propertyInfo)) {
2162                     try {
2163                         final Object yamlValue = new Yaml().loadAs(value, Object.class);
2164                         CustomYamlFunction toscaFunction = new CustomYamlFunction();
2165                         toscaFunction.setYamlValue(yamlValue);
2166                         property.setToscaFunction(toscaFunction);
2167                     } catch (Exception exception) {
2168                         log.info("Cannot create YAML value for {}", propName);
2169                     }
2170                 } else {
2171                     property.setToscaFunction(propertyInfo.getToscaFunction());
2172                 }
2173                 property.setSubPropertyToscaFunctions(propertyInfo.getSubPropertyToscaFunctions());
2174                 if (!getInputs.isEmpty() && CollectionUtils.isEmpty(property.getSubPropertyToscaFunctions())) {
2175                     final List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
2176                     for (final GetInputValueDataDefinition getInput : getInputs) {
2177                         final List<InputDefinition> inputs = component.getInputs();
2178                         if (inputs == null || inputs.isEmpty()) {
2179                             log.debug("Failed to add property {} to instance. Inputs list is empty ", property);
2180                             serviceBusinessLogic.rollbackWithException(ActionStatus.INPUTS_NOT_FOUND,
2181                                 property.getGetInputValues().stream().map(GetInputValueDataDefinition::getInputName).collect(toList()).toString());
2182                         }
2183                         InputDefinition input = serviceImportParseLogic.findInputByName(inputs, getInput);
2184                         getInput.setInputId(input.getUniqueId());
2185                         getInputValues.add(getInput);
2186                         GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
2187                         if (getInputIndex != null) {
2188                             input = serviceImportParseLogic.findInputByName(inputs, getInputIndex);
2189                             getInputIndex.setInputId(input.getUniqueId());
2190                             getInputValues.add(getInputIndex);
2191                         }
2192                     }
2193                     property.setGetInputValues(getInputValues);
2194                 }
2195                 instPropList.add(property);
2196                 currPropertiesMap.remove(property.getName());
2197             }
2198         }
2199         if (!currPropertiesMap.isEmpty()) {
2200             for (PropertyDefinition value : currPropertiesMap.values()) {
2201                 instPropList.add(new ComponentInstanceProperty(value));
2202             }
2203         }
2204         instProperties.put(currentCompInstance.getUniqueId(), instPropList);
2205         return componentsUtils.getResponseFormat(ActionStatus.OK);
2206     }
2207
2208     private boolean tryHandlingAsYamlToscaFunction(String validatedPropValue, String value, UploadPropInfo propertyInfo) {
2209         return StringUtils.isEmpty(validatedPropValue) && StringUtils.isNotEmpty(value) && propertyInfo.getToscaFunction() == null
2210             && CollectionUtils.isEmpty(propertyInfo.getSubPropertyToscaFunctions());
2211     }
2212
2213     private void addSubPropertyYamlToscaFunctions(final String validatedPropValue, final String value, final String propertyType,
2214                                                   final UploadPropInfo propertyInfo, final Map<String, DataTypeDefinition> allDataTypes) {
2215         if (StringUtils.isNotEmpty(validatedPropValue) || StringUtils.isEmpty(value) || ToscaPropertyType.isValidType(propertyType) != null) {
2216             return;
2217         }
2218         try {
2219             final JsonObject jsonObject = JsonParser.parseString(value).getAsJsonObject();
2220
2221             final DataTypeDefinition dataTypeDefinition = allDataTypes.get(propertyType);
2222             final List<String> propertyNames =
2223                 dataTypeDefinition.getProperties().stream().map(PropertyDataDefinition::getName).collect(Collectors.toList());
2224
2225             boolean hasSubPropertyValues = jsonObject.entrySet().stream().allMatch(entry -> propertyNames.contains(entry.getKey()));
2226
2227             if (hasSubPropertyValues) {
2228                 for (final PropertyDefinition prop : dataTypeDefinition.getProperties()) {
2229                     if (propertyInfo.getSubPropertyToscaFunctions().stream()
2230                         .anyMatch(subPropertyToscaFunction -> subPropertyToscaFunction.getSubPropertyPath().get(0).equals(prop.getName()))) {
2231                         continue;
2232                     }
2233                     Optional<SubPropertyToscaFunction> subPropertyToscaFunction = createSubPropertyYamlToscaFunction(jsonObject, prop, allDataTypes);
2234                     if (subPropertyToscaFunction.isPresent()) {
2235                         propertyInfo.getSubPropertyToscaFunctions().add(subPropertyToscaFunction.get());
2236                     }
2237                 }
2238             }
2239         } catch (Exception exception) {
2240             log.info("Cannot create YAML value for {}", value);
2241         }
2242     }
2243
2244     private Optional<SubPropertyToscaFunction> createSubPropertyYamlToscaFunction(final JsonObject jsonObject, final PropertyDefinition prop,
2245                                                                                   final Map<String, DataTypeDefinition> allDataTypes) {
2246         JsonElement propJsonElement = jsonObject.get(prop.getName());
2247         if (propJsonElement != null) {
2248             final String subPropValue = propJsonElement.toString();
2249             final ComponentInstanceProperty subProperty = new ComponentInstanceProperty(prop, subPropValue, null);
2250             final String validateSubPropValue =
2251                 serviceBusinessLogic.validatePropValueBeforeCreate(subProperty, subPropValue, true, allDataTypes);
2252
2253             if (StringUtils.isEmpty(validateSubPropValue) && StringUtils.isNotEmpty(subPropValue)) {
2254                 try {
2255                     Object yamlValue = new Yaml().loadAs(subPropValue, Object.class);
2256                     SubPropertyToscaFunction subPropertyToscaFunction = new SubPropertyToscaFunction();
2257                     CustomYamlFunction toscaFunction = new CustomYamlFunction();
2258                     toscaFunction.setYamlValue(yamlValue);
2259                     subPropertyToscaFunction.setToscaFunction(toscaFunction);
2260                     subPropertyToscaFunction.setSubPropertyPath(Collections.singletonList(prop.getName()));
2261                     return Optional.of(subPropertyToscaFunction);
2262                 } catch (Exception exception) {
2263                     log.info("Cannot create YAML value for {}", subPropValue);
2264                 }
2265             }
2266         }
2267         return Optional.empty();
2268     }
2269
2270     protected ResponseFormat addInterfaceValuesToRi(
2271         UploadComponentInstanceInfo uploadComponentInstanceInfo,
2272         Component component,
2273         Resource originResource, ComponentInstance currentCompInstance,
2274         Map<String, Map<String, InterfaceDefinition>> instInterfaces
2275     ) {
2276         Map<String, UploadInterfaceInfo> instanceInterfacesMap = uploadComponentInstanceInfo.getInterfaces();
2277         Map<String, InterfaceDefinition> currInterfacesMap = new HashMap<>();
2278         Map<String, InterfaceDefinition> interfacesFromNodeType = originResource.getInterfaces();
2279         if ((MapUtils.isNotEmpty(instanceInterfacesMap)) && (MapUtils.isEmpty(interfacesFromNodeType))) {
2280             log.debug("failed to find interfaces ");
2281             return componentsUtils.getResponseFormat(ActionStatus.INTERFACE_NOT_FOUND_IN_COMPONENT);
2282         }
2283         if (interfacesFromNodeType == null || interfacesFromNodeType.isEmpty()) {
2284             return componentsUtils.getResponseFormat(ActionStatus.OK);
2285         }
2286         for (Map.Entry<String, InterfaceDefinition> entryInstances : interfacesFromNodeType.entrySet()) {
2287             String interfaceName = entryInstances.getKey().substring(entryInstances.getKey().lastIndexOf(".") + 1);
2288             if (!currInterfacesMap.containsKey(interfaceName)) {
2289                 currInterfacesMap.put(interfaceName, entryInstances.getValue());
2290             }
2291         }
2292
2293         Map<String, InterfaceDefinition> instInterfacesMap = new HashMap<>();
2294         if (MapUtils.isNotEmpty(instanceInterfacesMap)) {
2295             for (UploadInterfaceInfo uploadInterfaceInfo : instanceInterfacesMap.values()) {
2296                 String interfaceName = uploadInterfaceInfo.getName();
2297                 if (!currInterfacesMap.containsKey(interfaceName)) {
2298                     log.debug("failed to find interface {} ", interfaceName);
2299                     return componentsUtils.getResponseFormat(ActionStatus.INTERFACE_NOT_FOUND_IN_COMPONENT, interfaceName);
2300                 }
2301                 InterfaceDefinition currentInterfaceDef = currInterfacesMap.get(interfaceName);
2302                 Map<String, OperationDataDefinition> operationsToAdd = new HashMap<>();
2303
2304                 Map<String, OperationDataDefinition> operations = uploadInterfaceInfo.getOperations();
2305                 for (Map.Entry<String, OperationDataDefinition> operation : operations.entrySet()) {
2306                     OperationDataDefinition templateOperation = currentInterfaceDef.getOperationsMap().get(operation.getKey());
2307                     OperationDataDefinition instanceOperation = operation.getValue();
2308                     //Inputs
2309                     ListDataDefinition<OperationInputDefinition> instanceInputs = instanceOperation.getInputs();
2310                     mergeOperationInputDefinitions(templateOperation.getInputs(), instanceInputs);
2311                     if (null != instanceInputs) {
2312                         component.getProperties()
2313                             .forEach(property -> instanceInputs.getListToscaDataDefinition().stream()
2314                                 .filter(instanceInput ->
2315                                     instanceInput.getToscaFunction() instanceof ToscaGetFunctionDataDefinition &&
2316                                         property.getName().equals(instanceInput.getToscaFunction() != null ?
2317                                             ((ToscaGetFunctionDataDefinition) instanceInput.getToscaFunction()).getPropertyName() :
2318                                             null))
2319                                 .forEach(oldInput -> oldInput.setType(property.getType()))
2320                             );
2321                     }
2322                     templateOperation.setInputs(instanceInputs);
2323                     //Implementation
2324                     templateOperation.setImplementation(instanceOperation.getImplementation());
2325                     //Description
2326                     templateOperation.setDescription(instanceOperation.getDescription());
2327                     operationsToAdd.put(operation.getKey(), templateOperation);
2328                 }
2329                 InterfaceDefinition interfaceDef = new InterfaceDefinition();
2330                 interfaceDef.setModel(component.getModel());
2331                 interfaceDef.setType(currentInterfaceDef.getType());
2332                 interfaceDef.setUniqueId(currentInterfaceDef.getType());
2333                 interfaceDef.setDescription(uploadInterfaceInfo.getDescription());
2334                 interfaceDef.setOperations(operationsToAdd);
2335                 instInterfacesMap.put(currentInterfaceDef.getType(), interfaceDef);
2336                 currInterfacesMap.remove(interfaceName);
2337             }
2338         }
2339         if (!currInterfacesMap.isEmpty()) {
2340             for (InterfaceDefinition value : currInterfacesMap.values()) {
2341                 instInterfacesMap.put(value.getUniqueId(), value);
2342             }
2343         }
2344         instInterfaces.put(currentCompInstance.getUniqueId(), instInterfacesMap);
2345         return componentsUtils.getResponseFormat(ActionStatus.OK);
2346     }
2347
2348     private void mergeOperationInputDefinitions(ListDataDefinition<OperationInputDefinition> inputsFromNodeType,
2349                                                 ListDataDefinition<OperationInputDefinition> instanceInputs) {
2350         if (inputsFromNodeType == null || CollectionUtils.isEmpty(inputsFromNodeType.getListToscaDataDefinition()) || instanceInputs == null
2351             || CollectionUtils.isEmpty(instanceInputs.getListToscaDataDefinition())) {
2352             return;
2353         }
2354         instanceInputs.getListToscaDataDefinition().forEach(
2355             instanceInput -> inputsFromNodeType.getListToscaDataDefinition().stream().filter(
2356                 templateInput -> templateInput.getName().equals(instanceInput.getName())
2357             ).forEach(
2358                 newInstanceInput -> {
2359                     instanceInput.setSourceProperty(newInstanceInput.getSourceProperty());
2360                     instanceInput.setSource(newInstanceInput.getSource());
2361                     instanceInput.setType(newInstanceInput.getType());
2362                 }
2363             )
2364         );
2365         instanceInputs.getListToscaDataDefinition().stream()
2366             .filter(instanceInput -> inputsFromNodeType.getListToscaDataDefinition().stream().noneMatch(
2367                 inputFromNodeType -> inputFromNodeType.getName().equals(instanceInput.getName())
2368             ))
2369             .forEach(oldInput -> oldInput.setType("string"));
2370     }
2371
2372     protected void processComponentInstanceCapabilities(Map<String, DataTypeDefinition> allDataTypes,
2373                                                         Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties,
2374                                                         UploadComponentInstanceInfo uploadComponentInstanceInfo,
2375                                                         ComponentInstance currentCompInstance, Resource originResource) {
2376         log.debug("enter processComponentInstanceCapabilities");
2377         Map<String, List<CapabilityDefinition>> originCapabilities;
2378         if (MapUtils.isNotEmpty(uploadComponentInstanceInfo.getCapabilities())) {
2379             originCapabilities = new HashMap<>();
2380             Map<String, Map<String, UploadPropInfo>> newPropertiesMap = new HashMap<>();
2381             originResource.getCapabilities().forEach((k, v) -> serviceImportParseLogic.addCapabilities(originCapabilities, k, v));
2382             uploadComponentInstanceInfo.getCapabilities().values()
2383                 .forEach(l -> serviceImportParseLogic.addCapabilitiesProperties(newPropertiesMap, l));
2384             updateCapabilityPropertiesValues(allDataTypes, originCapabilities, newPropertiesMap);
2385         } else {
2386             originCapabilities = originResource.getCapabilities();
2387         }
2388         instCapabilties.put(currentCompInstance, originCapabilities);
2389     }
2390
2391     protected void updateCapabilityPropertiesValues(Map<String, DataTypeDefinition> allDataTypes,
2392                                                     Map<String, List<CapabilityDefinition>> originCapabilities,
2393                                                     Map<String, Map<String, UploadPropInfo>> newPropertiesMap) {
2394         originCapabilities.values().stream().flatMap(Collection::stream).filter(c -> newPropertiesMap.containsKey(c.getName()))
2395             .forEach(c -> updatePropertyValues(c.getProperties(), newPropertiesMap.get(c.getName()), allDataTypes));
2396     }
2397
2398     protected void updatePropertyValues(List<ComponentInstanceProperty> properties, Map<String, UploadPropInfo> newProperties,
2399                                         Map<String, DataTypeDefinition> allDataTypes) {
2400         properties.forEach(p -> updatePropertyValue(p, newProperties.get(p.getName()), allDataTypes));
2401     }
2402
2403     protected String updatePropertyValue(ComponentInstanceProperty property, UploadPropInfo propertyInfo,
2404                                          Map<String, DataTypeDefinition> allDataTypes) {
2405         String value = null;
2406         List<GetInputValueDataDefinition> getInputs = null;
2407         boolean isValidate = true;
2408         if (null != propertyInfo && propertyInfo.getValue() != null) {
2409             getInputs = propertyInfo.getGet_input();
2410             isValidate = getInputs == null || getInputs.isEmpty();
2411             if (isValidate) {
2412                 value = getPropertyJsonStringValue(propertyInfo.getValue(), property.getType());
2413             } else {
2414                 value = getPropertyJsonStringValue(propertyInfo.getValue(), TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
2415             }
2416         }
2417         property.setValue(value);
2418         return serviceBusinessLogic.validatePropValueBeforeCreate(property, value, isValidate, allDataTypes);
2419     }
2420
2421     protected Resource getOriginResource(String yamlName, Map<String, Resource> originCompMap, ComponentInstance currentCompInstance) {
2422         Resource originResource;
2423         log.debug("after enter ServiceImportBusinessLogic processComponentInstance, enter getOriginResource");
2424         if (!originCompMap.containsKey(currentCompInstance.getComponentUid())) {
2425             Either<Resource, StorageOperationStatus> getOriginResourceRes = toscaOperationFacade
2426                 .getToscaFullElement(currentCompInstance.getComponentUid());
2427             if (getOriginResourceRes.isRight()) {
2428                 ResponseFormat responseFormat = componentsUtils
2429                     .getResponseFormat(componentsUtils.convertFromStorageResponse(getOriginResourceRes.right().value()), yamlName);
2430                 throw new ComponentException(responseFormat);
2431             }
2432             originResource = getOriginResourceRes.left().value();
2433             originCompMap.put(originResource.getUniqueId(), originResource);
2434         } else {
2435             originResource = originCompMap.get(currentCompInstance.getComponentUid());
2436         }
2437         return originResource;
2438     }
2439
2440     protected Either<Resource, StorageOperationStatus> updateCalculatedCapReqWithSubstitutionMappings(Resource resource,
2441                                                                                                       Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
2442         Either<Resource, StorageOperationStatus> updateRes = null;
2443         Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities = new HashMap<>();
2444         Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements = new HashMap<>();
2445         StorageOperationStatus status = toscaOperationFacade.deleteAllCalculatedCapabilitiesRequirements(resource.getUniqueId());
2446         if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
2447             log.debug("Failed to delete all calculated capabilities and requirements of resource {} upon update. Status is {}",
2448                 resource.getUniqueId(), status);
2449             updateRes = Either.right(status);
2450         }
2451         if (updateRes == null) {
2452             fillUpdatedInstCapabilitiesRequirements(resource.getComponentInstances(), uploadResInstancesMap, updatedInstCapabilities,
2453                 updatedInstRequirements);
2454             status = toscaOperationFacade.associateOrAddCalculatedCapReq(updatedInstCapabilities, updatedInstRequirements, resource);
2455             if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
2456                 updateRes = Either.right(status);
2457             }
2458         }
2459         if (updateRes == null) {
2460             updateRes = Either.left(resource);
2461         }
2462         return updateRes;
2463     }
2464
2465     protected void fillUpdatedInstCapabilitiesRequirements(List<ComponentInstance> componentInstances,
2466                                                            Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
2467                                                            Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities,
2468                                                            Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements) {
2469         componentInstances.stream().forEach(i -> {
2470             fillUpdatedInstCapabilities(updatedInstCapabilities, i, uploadResInstancesMap.get(i.getName()).getCapabilitiesNamesToUpdate());
2471             fillUpdatedInstRequirements(updatedInstRequirements, i, uploadResInstancesMap.get(i.getName()).getRequirementsNamesToUpdate());
2472         });
2473     }
2474
2475     protected void fillUpdatedInstCapabilities(Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilties,
2476                                                ComponentInstance instance, Map<String, String> capabilitiesNamesToUpdate) {
2477         Map<String, List<CapabilityDefinition>> updatedCapabilities = new HashMap<>();
2478         Set<String> updatedCapNames = new HashSet<>();
2479         if (MapUtils.isNotEmpty(capabilitiesNamesToUpdate)) {
2480             for (Map.Entry<String, List<CapabilityDefinition>> requirements : instance.getCapabilities().entrySet()) {
2481                 updatedCapabilities.put(requirements.getKey(), requirements.getValue().stream().filter(
2482                         c -> capabilitiesNamesToUpdate.containsKey(c.getName()) && !updatedCapNames.contains(capabilitiesNamesToUpdate.get(c.getName())))
2483                     .map(c -> {
2484                         c.setParentName(c.getName());
2485                         c.setName(capabilitiesNamesToUpdate.get(c.getName()));
2486                         updatedCapNames.add(c.getName());
2487                         return c;
2488                     }).collect(toList()));
2489             }
2490         }
2491         if (MapUtils.isNotEmpty(updatedCapabilities)) {
2492             updatedInstCapabilties.put(instance, updatedCapabilities);
2493         }
2494     }
2495
2496     protected void fillUpdatedInstRequirements(Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements,
2497                                                ComponentInstance instance, Map<String, String> requirementsNamesToUpdate) {
2498         Map<String, List<RequirementDefinition>> updatedRequirements = new HashMap<>();
2499         Set<String> updatedReqNames = new HashSet<>();
2500         if (MapUtils.isNotEmpty(requirementsNamesToUpdate)) {
2501             for (Map.Entry<String, List<RequirementDefinition>> requirements : instance.getRequirements().entrySet()) {
2502                 updatedRequirements.put(requirements.getKey(), requirements.getValue().stream().filter(
2503                         r -> requirementsNamesToUpdate.containsKey(r.getName()) && !updatedReqNames.contains(requirementsNamesToUpdate.get(r.getName())))
2504                     .map(r -> {
2505                         r.setParentName(r.getName());
2506                         r.setName(requirementsNamesToUpdate.get(r.getName()));
2507                         updatedReqNames.add(r.getName());
2508                         return r;
2509                     }).collect(toList()));
2510             }
2511         }
2512         if (MapUtils.isNotEmpty(updatedRequirements)) {
2513             updatedInstRequirements.put(instance, updatedRequirements);
2514         }
2515     }
2516
2517     protected void addRelationsToRI(String yamlName, Service service, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
2518                                     List<ComponentInstance> componentInstancesList, List<RequirementCapabilityRelDef> relations) {
2519         for (Map.Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) {
2520             UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
2521             ComponentInstance currentCompInstance = null;
2522             for (ComponentInstance compInstance : componentInstancesList) {
2523                 if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
2524                     currentCompInstance = compInstance;
2525                     break;
2526                 }
2527             }
2528             if (currentCompInstance == null) {
2529                 log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(), service.getUniqueId());
2530                 BeEcompErrorManager.getInstance()
2531                     .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE, service.getUniqueId(),
2532                         BeEcompErrorManager.ErrorSeverity.ERROR);
2533                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2534                 throw new ComponentException(responseFormat);
2535             }
2536             ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, service, entry.getValue(), relations);
2537             if (addRelationToRiRes.getStatus() != 200) {
2538                 throw new ComponentException(addRelationToRiRes);
2539             }
2540         }
2541     }
2542
2543     protected ResponseFormat addRelationToRI(String yamlName, Service service, UploadComponentInstanceInfo nodesInfoValue,
2544                                              List<RequirementCapabilityRelDef> relations) {
2545         List<ComponentInstance> componentInstancesList = service.getComponentInstances();
2546         ComponentInstance currentCompInstance = null;
2547         for (ComponentInstance compInstance : componentInstancesList) {
2548             if (compInstance.getName().equals(nodesInfoValue.getName())) {
2549                 currentCompInstance = compInstance;
2550                 break;
2551             }
2552         }
2553         if (currentCompInstance == null) {
2554             log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, nodesInfoValue.getName(), service.getUniqueId());
2555             BeEcompErrorManager.getInstance()
2556                 .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + nodesInfoValue.getName() + IN_RESOURCE, service.getUniqueId(),
2557                     BeEcompErrorManager.ErrorSeverity.ERROR);
2558             return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2559         }
2560         String resourceInstanceId = currentCompInstance.getUniqueId();
2561         Map<String, List<UploadReqInfo>> regMap = nodesInfoValue.getRequirements();
2562         if (regMap != null) {
2563             Iterator<Map.Entry<String, List<UploadReqInfo>>> nodesRegValue = regMap.entrySet().iterator();
2564             while (nodesRegValue.hasNext()) {
2565                 Map.Entry<String, List<UploadReqInfo>> nodesRegInfoEntry = nodesRegValue.next();
2566                 List<UploadReqInfo> uploadRegInfoList = nodesRegInfoEntry.getValue();
2567                 for (UploadReqInfo uploadRegInfo : uploadRegInfoList) {
2568                     log.debug("Going to create  relation {}", uploadRegInfo.getName());
2569                     String regName = uploadRegInfo.getName();
2570                     RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef();
2571                     regCapRelDef.setFromNode(resourceInstanceId);
2572                     log.debug("try to find available requirement {} ", regName);
2573                     Either<RequirementDefinition, ResponseFormat> eitherReqStatus = serviceImportParseLogic
2574                         .findAvailableRequirement(regName, yamlName, nodesInfoValue, currentCompInstance, uploadRegInfo.getCapabilityName());
2575                     if (eitherReqStatus.isRight()) {
2576                         log.debug("failed to find available requirement {} status is {}", regName, eitherReqStatus.right().value());
2577                         return eitherReqStatus.right().value();
2578                     }
2579                     RequirementDefinition validReq = eitherReqStatus.left().value();
2580                     List<CapabilityRequirementRelationship> reqAndRelationshipPairList = regCapRelDef.getRelationships();
2581                     if (reqAndRelationshipPairList == null) {
2582                         reqAndRelationshipPairList = new ArrayList<>();
2583                     }
2584                     RelationshipInfo reqAndRelationshipPair = new RelationshipInfo();
2585                     reqAndRelationshipPair.setRequirement(regName);
2586                     reqAndRelationshipPair.setRequirementOwnerId(validReq.getOwnerId());
2587                     reqAndRelationshipPair.setRequirementUid(validReq.getUniqueId());
2588                     RelationshipImpl relationship = new RelationshipImpl();
2589                     relationship.setType(validReq.getCapability());
2590                     reqAndRelationshipPair.setRelationships(relationship);
2591                     ComponentInstance currentCapCompInstance = null;
2592                     for (ComponentInstance compInstance : componentInstancesList) {
2593                         if (compInstance.getName().equals(uploadRegInfo.getNode())) {
2594                             currentCapCompInstance = compInstance;
2595                             break;
2596                         }
2597                     }
2598                     if (currentCapCompInstance == null) {
2599                         log.debug("The component instance  with name {} not found on resource {} ", uploadRegInfo.getNode(), service.getUniqueId());
2600                         BeEcompErrorManager.getInstance()
2601                             .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + uploadRegInfo.getNode() + IN_RESOURCE, service.getUniqueId(),
2602                                 BeEcompErrorManager.ErrorSeverity.ERROR);
2603                         return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2604                     }
2605                     regCapRelDef.setToNode(currentCapCompInstance.getUniqueId());
2606                     log.debug("try to find aviable Capability  req name is {} ", validReq.getName());
2607                     CapabilityDefinition aviableCapForRel = serviceImportParseLogic
2608                         .findAvailableCapabilityByTypeOrName(validReq, currentCapCompInstance, uploadRegInfo);
2609                     if (aviableCapForRel == null) {
2610                         BeEcompErrorManager.getInstance().logInternalDataError(
2611                             "aviable capability was not found. req name is " + validReq.getName() + " component instance is " + currentCapCompInstance
2612                                 .getUniqueId(), service.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR);
2613                         return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2614                     }
2615                     reqAndRelationshipPair.setCapability(aviableCapForRel.getName());
2616                     reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId());
2617                     reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId());
2618                     CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship();
2619                     capReqRel.setRelation(reqAndRelationshipPair);
2620                     if (StringUtils.isNotEmpty(uploadRegInfo.getRelationshipTemplate())) {
2621                         capReqRel.setOperations(getOperations(nodesInfoValue.getOperations(), uploadRegInfo.getRelationshipTemplate()));
2622                     }
2623                     reqAndRelationshipPairList.add(capReqRel);
2624                     regCapRelDef.setRelationships(reqAndRelationshipPairList);
2625                     relations.add(regCapRelDef);
2626                 }
2627             }
2628         }
2629         return componentsUtils.getResponseFormat(ActionStatus.OK, yamlName);
2630     }
2631
2632     private List<OperationUi> getOperations(final Map<String, List<OperationUi>> operations, final String relationshipTemplate) {
2633         final List<OperationUi> operationUiList = new ArrayList<>();
2634         operations.forEach((operationKey, operationValues) -> {
2635             if (operationKey.equals(relationshipTemplate)) {
2636                 operationUiList.addAll(operationValues);
2637             }
2638         });
2639         return operationUiList;
2640     }
2641
2642     protected Service getResourceAfterCreateRelations(Service service) {
2643         ComponentParametersView parametersView = serviceImportParseLogic.getComponentFilterAfterCreateRelations();
2644         Either<Service, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(service.getUniqueId(), parametersView);
2645         if (eitherGetResource.isRight()) {
2646             serviceImportParseLogic.throwComponentExceptionByResource(eitherGetResource.right().value(), service);
2647         }
2648         return eitherGetResource.left().value();
2649     }
2650
2651     protected Service createServiceInstances(String yamlName, Service service, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
2652                                              Map<String, Resource> nodeNamespaceMap) {
2653         Either<Resource, ResponseFormat> eitherResource = null;
2654         log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName);
2655         if (MapUtils.isEmpty(uploadResInstancesMap)) { // PNF can have no resource instances
2656             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
2657             throw new ComponentException(responseFormat);
2658         }
2659         Map<String, Resource> existingNodeTypeMap = new HashMap<>();
2660         if (MapUtils.isNotEmpty(nodeNamespaceMap)) {
2661             nodeNamespaceMap.forEach((k, v) -> existingNodeTypeMap.put(v.getToscaResourceName(), v));
2662         }
2663         Map<ComponentInstance, Resource> resourcesInstancesMap = new HashMap<>();
2664         uploadResInstancesMap.values()
2665             .forEach(i -> createAndAddResourceInstance(i, yamlName, service, nodeNamespaceMap, existingNodeTypeMap, resourcesInstancesMap));
2666         if (MapUtils.isNotEmpty(resourcesInstancesMap)) {
2667             try {
2668                 toscaOperationFacade.associateComponentInstancesToComponent(service, resourcesInstancesMap, false, false);
2669             } catch (StorageException exp) {
2670                 if (exp.getStorageOperationStatus() != null && exp.getStorageOperationStatus() != StorageOperationStatus.OK) {
2671                     log.debug("Failed to add component instances to container component {}", service.getName());
2672                     ResponseFormat responseFormat = componentsUtils
2673                         .getResponseFormat(componentsUtils.convertFromStorageResponse(exp.getStorageOperationStatus()));
2674                     eitherResource = Either.right(responseFormat);
2675                     throw new ComponentException(eitherResource.right().value());
2676                 }
2677             }
2678         }
2679         Either<Service, StorageOperationStatus> eitherGetResource = toscaOperationFacade
2680             .getToscaElement(service.getUniqueId(), serviceImportParseLogic.getComponentWithInstancesFilter());
2681         log.debug("*************finished to get resource {}", service.getUniqueId());
2682         if (eitherGetResource.isRight()) {
2683             ResponseFormat responseFormat = componentsUtils
2684                 .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), service,
2685                     ComponentTypeEnum.SERVICE);
2686             throw new ComponentException(responseFormat);
2687         }
2688         if (CollectionUtils.isEmpty(eitherGetResource.left().value().getComponentInstances())) { // PNF can have no resource instances
2689             log.debug("Error when create resource instance from csar. ComponentInstances list empty");
2690             BeEcompErrorManager.getInstance().logBeDaoSystemError("Error when create resource instance from csar. ComponentInstances list empty");
2691             throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
2692         }
2693         return eitherGetResource.left().value();
2694     }
2695
2696     protected void createAndAddResourceInstance(UploadComponentInstanceInfo uploadComponentInstanceInfo, String yamlName, Component component,
2697                                                 Map<String, Resource> nodeNamespaceMap, Map<String, Resource> existingnodeTypeMap,
2698                                                 Map<ComponentInstance, Resource> resourcesInstancesMap) {
2699         log.debug("*************Going to create  resource instances {}", uploadComponentInstanceInfo.getName());
2700         try {
2701             if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
2702                 uploadComponentInstanceInfo.setType(nodeNamespaceMap.get(uploadComponentInstanceInfo.getType()).getToscaResourceName());
2703             }
2704             Resource refResource =
2705                 validateResourceInstanceBeforeCreate(yamlName, component.getModel(), uploadComponentInstanceInfo, existingnodeTypeMap);
2706             ComponentInstance componentInstance = new ComponentInstance();
2707             componentInstance.setComponentUid(refResource.getUniqueId());
2708             Collection<String> directives = uploadComponentInstanceInfo.getDirectives();
2709             if (directives != null && !directives.isEmpty()) {
2710                 componentInstance.setDirectives(new ArrayList<>(directives));
2711             }
2712             UploadNodeFilterInfo uploadNodeFilterInfo = uploadComponentInstanceInfo.getUploadNodeFilterInfo();
2713             if (uploadNodeFilterInfo != null) {
2714                 componentInstance
2715                     .setNodeFilter(new CINodeFilterUtils().getNodeFilterDataDefinition(uploadNodeFilterInfo, componentInstance.getUniqueId()));
2716             }
2717             ComponentTypeEnum containerComponentType = component.getComponentType();
2718             NodeTypeEnum containerNodeType = containerComponentType.getNodeType();
2719             if (containerNodeType.equals(NodeTypeEnum.Resource) && MapUtils.isNotEmpty(uploadComponentInstanceInfo.getCapabilities()) && MapUtils
2720                 .isNotEmpty(refResource.getCapabilities())) {
2721                 serviceImportParseLogic.setCapabilityNamesTypes(refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities());
2722                 Map<String, List<CapabilityDefinition>> validComponentInstanceCapabilities = serviceImportParseLogic
2723                     .getValidComponentInstanceCapabilities(refResource.getUniqueId(), refResource.getCapabilities(),
2724                         uploadComponentInstanceInfo.getCapabilities());
2725                 componentInstance.setCapabilities(validComponentInstanceCapabilities);
2726             }
2727             if (!existingnodeTypeMap.containsKey(uploadComponentInstanceInfo.getType())) {
2728                 ResponseFormat responseFormat = componentsUtils
2729                     .getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(),
2730                         uploadComponentInstanceInfo.getType());
2731                 throw new ComponentException(responseFormat);
2732             }
2733             Resource origResource = existingnodeTypeMap.get(uploadComponentInstanceInfo.getType());
2734             componentInstance.setName(uploadComponentInstanceInfo.getName());
2735             componentInstance.setIcon(origResource.getIcon());
2736             componentInstance.setMinOccurrences(uploadComponentInstanceInfo.getMinOccurrences());
2737             componentInstance.setMaxOccurrences(uploadComponentInstanceInfo.getMaxOccurrences());
2738             componentInstance.setInstanceCount(uploadComponentInstanceInfo.getInstanceCount());
2739             resourcesInstancesMap.put(componentInstance, origResource);
2740         } catch (final ComponentException e) {
2741             throw e;
2742         } catch (final Exception e) {
2743             throw new ComponentException(ActionStatus.GENERAL_ERROR, e.getMessage());
2744         }
2745     }
2746
2747     protected Resource validateResourceInstanceBeforeCreate(String yamlName, String model, UploadComponentInstanceInfo uploadComponentInstanceInfo,
2748                                                             Map<String, Resource> nodeNamespaceMap) {
2749         Resource refResource;
2750         try {
2751             if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
2752                 refResource = nodeNamespaceMap.get(uploadComponentInstanceInfo.getType());
2753             } else {
2754                 final Either<Component, StorageOperationStatus> resourceEither =
2755                     toscaOperationFacade.getLatestByToscaResourceName(uploadComponentInstanceInfo.getType(), model);
2756                 if (resourceEither.isRight()) {
2757                     ResponseFormat responseFormat = componentsUtils
2758                         .getResponseFormat(componentsUtils.convertFromStorageResponse(resourceEither.right().value()));
2759                     throw new ComponentException(responseFormat);
2760                 }
2761                 refResource = (Resource) resourceEither.left().value();
2762                 nodeNamespaceMap.put(refResource.getToscaResourceName(), refResource);
2763             }
2764             String componentState = refResource.getComponentMetadataDefinition().getMetadataDataDefinition().getState();
2765             if (componentState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
2766                 ResponseFormat responseFormat = componentsUtils
2767                     .getResponseFormat(ActionStatus.ILLEGAL_COMPONENT_STATE, refResource.getComponentType().getValue(), refResource.getName(),
2768                         componentState);
2769                 throw new ComponentException(responseFormat);
2770             }
2771             if (!ModelConverter.isAtomicComponent(refResource) && refResource.getResourceType() != ResourceTypeEnum.VF) {
2772                 log.debug("validateResourceInstanceBeforeCreate -  ref resource type is  ", refResource.getResourceType());
2773                 ResponseFormat responseFormat = componentsUtils
2774                     .getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(),
2775                         uploadComponentInstanceInfo.getType());
2776                 throw new ComponentException(responseFormat);
2777             }
2778             return refResource;
2779         } catch (final ComponentException e) {
2780             throw e;
2781         } catch (final Exception e) {
2782             throw new ComponentException(ActionStatus.GENERAL_ERROR, e.getMessage());
2783         }
2784     }
2785
2786     protected void handleServiceNodeTypes(String yamlName, Service service, String topologyTemplateYaml, boolean needLock,
2787                                           Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
2788                                           List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
2789                                           CsarInfo csarInfo, String nodeName) {
2790         try {
2791             for (Map.Entry<String, NodeTypeInfo> nodeTypeEntry : nodeTypesInfo.entrySet()) {
2792                 boolean isResourceNotExisted = validateResourceNotExisted(nodeTypeEntry.getKey());
2793                 if (nodeTypeEntry.getValue().isNested() && isResourceNotExisted) {
2794                     handleNestedVF(service, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
2795                         nodeTypeEntry.getKey());
2796                     log.trace("************* finished to create node {}", nodeTypeEntry.getKey());
2797                 }
2798             }
2799             Map<String, Object> mappedToscaTemplate = null;
2800             if (org.apache.commons.lang.StringUtils.isNotEmpty(nodeName) && MapUtils.isNotEmpty(nodeTypesInfo) && nodeTypesInfo
2801                 .containsKey(nodeName)) {
2802                 mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate();
2803             }
2804             if (MapUtils.isEmpty(mappedToscaTemplate)) {
2805                 mappedToscaTemplate = (Map<String, Object>) new Yaml().load(topologyTemplateYaml);
2806             }
2807             createResourcesFromYamlNodeTypesList(yamlName, service, mappedToscaTemplate, needLock, nodeTypesArtifactsToHandle,
2808                 nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo);
2809         } catch (ComponentException | StorageException e) {
2810             throw e;
2811         } catch (Exception e) {
2812             log.debug("Exception occured when handleServiceNodeTypes, error is:{}", e.getMessage(), e);
2813             throw new ComponentException(ActionStatus.GENERAL_ERROR);
2814         }
2815     }
2816
2817     protected boolean validateResourceNotExisted(String type) {
2818         try {
2819             Either<Resource, StorageOperationStatus> latestResource = toscaOperationFacade.getLatestResourceByToscaResourceName(type);
2820             return latestResource.isRight();
2821         } catch (Exception e) {
2822             log.debug("Exception occured when validateResourceNotExisted, error is:{}", e.getMessage(), e);
2823             throw new ComponentException(ActionStatus.GENERAL_ERROR);
2824         }
2825     }
2826
2827     protected Resource handleNestedVF(Service service,
2828                                       Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
2829                                       List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
2830                                       String nodeName) {
2831         try {
2832             String yamlName = nodesInfo.get(nodeName).getTemplateFileName();
2833             Map<String, Object> nestedVfcJsonMap = nodesInfo.get(nodeName).getMappedToscaTemplate();
2834             createResourcesFromYamlNodeTypesList(yamlName, service, nestedVfcJsonMap, false, nodesArtifactsToHandle, createdArtifacts, nodesInfo,
2835                 csarInfo);
2836             log.debug("************* Finished to create node types from yaml {}", yamlName);
2837             if (nestedVfcJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) {
2838                 log.debug("************* Going to handle complex VFC from yaml {}", yamlName);
2839                 return handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName);
2840             }
2841             return new Resource();
2842         } catch (Exception e) {
2843             log.debug("Exception occured when handleNestedVF, error is:{}", e.getMessage(), e);
2844             throw new ComponentException(ActionStatus.GENERAL_ERROR);
2845         }
2846     }
2847
2848     protected Resource handleComplexVfc(
2849         Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
2850         List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo, String nodeName, String yamlName) {
2851         try {
2852             Resource oldComplexVfc = null;
2853             Resource newComplexVfc = serviceImportParseLogic.buildValidComplexVfc(csarInfo, nodeName, nodesInfo);
2854             Either<Resource, StorageOperationStatus> oldComplexVfcRes = toscaOperationFacade
2855                 .getFullLatestComponentByToscaResourceName(newComplexVfc.getToscaResourceName());
2856             if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() == StorageOperationStatus.NOT_FOUND) {
2857                 oldComplexVfcRes = toscaOperationFacade.getFullLatestComponentByToscaResourceName(
2858                     serviceImportParseLogic.buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), csarInfo.getVfResourceName(), nodeName)
2859                         .getRight());
2860             }
2861             if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() != StorageOperationStatus.NOT_FOUND) {
2862                 log.debug("Failed to fetch previous complex VFC by tosca resource name {}. Status is {}. ", newComplexVfc.getToscaResourceName(),
2863                     oldComplexVfcRes.right().value());
2864                 throw new ComponentException(ActionStatus.GENERAL_ERROR);
2865             } else if (oldComplexVfcRes.isLeft()) {
2866                 log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
2867                 Either<Boolean, ResponseFormat> eitherValidation = serviceImportParseLogic
2868                     .validateNestedDerivedFromDuringUpdate(oldComplexVfcRes.left().value(), newComplexVfc,
2869                         ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion()));
2870                 if (eitherValidation.isLeft()) {
2871                     oldComplexVfc = oldComplexVfcRes.left().value();
2872                 }
2873             }
2874             newComplexVfc = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName, oldComplexVfc,
2875                 newComplexVfc);
2876             csarInfo.getCreatedNodesToscaResourceNames().put(nodeName, newComplexVfc.getToscaResourceName());
2877             LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
2878                 LifecycleChangeInfoWithAction.LifecycleChanceActionEnum.CREATE_FROM_CSAR);
2879             log.debug("Going to certify cvfc {}. ", newComplexVfc.getName());
2880             final Resource result = serviceImportParseLogic
2881                 .propagateStateToCertified(csarInfo.getModifier(), newComplexVfc, lifecycleChangeInfo, true, false, true);
2882             csarInfo.getCreatedNodes().put(nodeName, result);
2883             csarInfo.removeNodeFromQueue();
2884             return result;
2885         } catch (Exception e) {
2886             log.debug("Exception occured when handleComplexVfc, error is:{}", e.getMessage(), e);
2887             throw new ComponentException(ActionStatus.GENERAL_ERROR);
2888         }
2889     }
2890
2891     protected Resource handleComplexVfc(
2892         Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
2893         List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo, String nodeName, String yamlName,
2894         Resource oldComplexVfc, Resource newComplexVfc) {
2895         Resource handleComplexVfcRes;
2896         try {
2897             Map<String, Object> mappedToscaTemplate = nodesInfo.get(nodeName).getMappedToscaTemplate();
2898             String yamlContent = new String(csarInfo.getCsar().get(yamlName));
2899             Map<String, NodeTypeInfo> newNodeTypesInfo = nodesInfo.entrySet().stream()
2900                 .collect(toMap(Map.Entry::getKey, e -> e.getValue().getUnmarkedCopy()));
2901             CsarInfo.markNestedVfc(mappedToscaTemplate, newNodeTypesInfo);
2902             if (oldComplexVfc == null) {
2903                 handleComplexVfcRes = createResourceFromYaml(newComplexVfc, yamlContent, yamlName, newNodeTypesInfo, csarInfo, nodesArtifactsToHandle,
2904                     false, true, nodeName);
2905             } else {
2906                 handleComplexVfcRes = updateResourceFromYaml(oldComplexVfc, newComplexVfc, AuditingActionEnum.UPDATE_RESOURCE_METADATA,
2907                     createdArtifacts, yamlContent, yamlName, csarInfo, newNodeTypesInfo, nodesArtifactsToHandle, nodeName, true);
2908             }
2909             return handleComplexVfcRes;
2910         } catch (Exception e) {
2911             log.debug("Exception occured when handleComplexVfc, error is:{}", e.getMessage(), e);
2912             throw new ComponentException(ActionStatus.GENERAL_ERROR);
2913         }
2914     }
2915
2916     protected Resource updateResourceFromYaml(Resource oldRresource, Resource newRresource, AuditingActionEnum actionEnum,
2917                                               List<ArtifactDefinition> createdArtifacts, String yamlFileName, String yamlFileContent,
2918                                               CsarInfo csarInfo, Map<String, NodeTypeInfo> nodeTypesInfo,
2919                                               Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
2920                                               String nodeName, boolean isNested) {
2921         boolean inTransaction = true;
2922         boolean shouldLock = false;
2923         Resource preparedResource = null;
2924         ParsedToscaYamlInfo uploadComponentInstanceInfoMap = null;
2925         try {
2926             uploadComponentInstanceInfoMap = csarBusinessLogic
2927                 .getParsedToscaYamlInfo(yamlFileContent, yamlFileName, nodeTypesInfo, csarInfo, nodeName, oldRresource);
2928             Map<String, UploadComponentInstanceInfo> instances = uploadComponentInstanceInfoMap.getInstances();
2929             if (MapUtils.isEmpty(instances) && newRresource.getResourceType() != ResourceTypeEnum.PNF) {
2930                 throw new ComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlFileName);
2931             }
2932             preparedResource = updateExistingResourceByImport(newRresource, oldRresource, csarInfo.getModifier(), inTransaction, shouldLock,
2933                 isNested).left;
2934             log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContent);
2935             serviceImportParseLogic.handleResourceGenericType(preparedResource);
2936             handleNodeTypes(yamlFileName, preparedResource, yamlFileContent, shouldLock, nodeTypesArtifactsToHandle, createdArtifacts, nodeTypesInfo,
2937                 csarInfo, nodeName);
2938             preparedResource = serviceImportParseLogic.createInputsOnResource(preparedResource, uploadComponentInstanceInfoMap.getInputs());
2939             preparedResource = createResourceInstances(yamlFileName, preparedResource, instances, csarInfo.getCreatedNodes());
2940             preparedResource = createResourceInstancesRelations(csarInfo.getModifier(), yamlFileName, preparedResource, instances);
2941         } catch (ComponentException e) {
2942             ResponseFormat responseFormat =
2943                 e.getResponseFormat() == null ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
2944             log.debug("#updateResourceFromYaml - failed to update resource from yaml {} .The error is {}", yamlFileName, responseFormat);
2945             componentsUtils
2946                 .auditResource(responseFormat, csarInfo.getModifier(), preparedResource == null ? oldRresource : preparedResource, actionEnum);
2947             throw e;
2948         } catch (StorageException e) {
2949             ResponseFormat responseFormat = componentsUtils
2950                 .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
2951             log.debug("#updateResourceFromYaml - failed to update resource from yaml {} .The error is {}", yamlFileName, responseFormat);
2952             componentsUtils
2953                 .auditResource(responseFormat, csarInfo.getModifier(), preparedResource == null ? oldRresource : preparedResource, actionEnum);
2954             throw e;
2955         }
2956         Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic.validateUpdateVfGroupNames(
2957             uploadComponentInstanceInfoMap.getGroups(), preparedResource.getSystemName());
2958         if (validateUpdateVfGroupNamesRes.isRight()) {
2959             throw new ComponentException(validateUpdateVfGroupNamesRes.right().value());
2960         }
2961         Map<String, GroupDefinition> groups;
2962         if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
2963             groups = validateUpdateVfGroupNamesRes.left().value();
2964         } else {
2965             groups = uploadComponentInstanceInfoMap.getGroups();
2966         }
2967         serviceImportParseLogic.handleGroupsProperties(preparedResource, groups);
2968         preparedResource = serviceImportParseLogic.updateGroupsOnResource(preparedResource, groups);
2969         NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName, nodeTypesArtifactsToHandle);
2970         Either<Resource, ResponseFormat> updateArtifactsEither = createOrUpdateArtifacts(ArtifactsBusinessLogic.ArtifactOperationEnum.UPDATE,
2971             createdArtifacts, yamlFileName, csarInfo, preparedResource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
2972         if (updateArtifactsEither.isRight()) {
2973             log.debug("failed to update artifacts {}", updateArtifactsEither.right().value());
2974             throw new ComponentException(updateArtifactsEither.right().value());
2975         }
2976         preparedResource = serviceImportParseLogic.getResourceWithGroups(updateArtifactsEither.left().value().getUniqueId());
2977         ActionStatus mergingPropsAndInputsStatus = resourceDataMergeBusinessLogic.mergeResourceEntities(oldRresource, preparedResource);
2978         if (mergingPropsAndInputsStatus != ActionStatus.OK) {
2979             ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(mergingPropsAndInputsStatus, preparedResource);
2980             throw new ComponentException(responseFormat);
2981         }
2982         compositionBusinessLogic.setPositionsForComponentInstances(preparedResource, csarInfo.getModifier().getUserId());
2983         return preparedResource;
2984     }
2985
2986     protected Resource createResourceFromYaml(Resource resource, String topologyTemplateYaml, String yamlName,
2987                                               Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
2988                                               Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
2989                                               boolean shouldLock, boolean inTransaction, String nodeName) {
2990         List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
2991         Resource createdResource;
2992         try {
2993             ParsedToscaYamlInfo parsedToscaYamlInfo = csarBusinessLogic
2994                 .getParsedToscaYamlInfo(topologyTemplateYaml, yamlName, nodeTypesInfo, csarInfo, nodeName, resource);
2995             if (MapUtils.isEmpty(parsedToscaYamlInfo.getInstances()) && resource.getResourceType() != ResourceTypeEnum.PNF) {
2996                 throw new ComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2997             }
2998             log.debug("#createResourceFromYaml - Going to create resource {} and RIs ", resource.getName());
2999             createdResource = createResourceAndRIsFromYaml(yamlName, resource, parsedToscaYamlInfo, AuditingActionEnum.IMPORT_RESOURCE, false,
3000                 createdArtifacts, topologyTemplateYaml, nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, shouldLock, inTransaction, nodeName);
3001             log.debug("#createResourceFromYaml - The resource {} has been created ", resource.getName());
3002         } catch (ComponentException e) {
3003             ResponseFormat responseFormat =
3004                 e.getResponseFormat() == null ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
3005             componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
3006             throw e;
3007         } catch (StorageException e) {
3008             ResponseFormat responseFormat = componentsUtils
3009                 .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
3010             componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
3011             throw e;
3012         }
3013         return createdResource;
3014     }
3015
3016     protected Resource createResourceAndRIsFromYaml(String yamlName, Resource resource, ParsedToscaYamlInfo parsedToscaYamlInfo,
3017                                                     AuditingActionEnum actionEnum, boolean isNormative, List<ArtifactDefinition> createdArtifacts,
3018                                                     String topologyTemplateYaml, Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
3019                                                     Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
3020                                                     boolean shouldLock, boolean inTransaction, String nodeName) {
3021         List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>();
3022         if (shouldLock) {
3023             Either<Boolean, ResponseFormat> lockResult = serviceBusinessLogic
3024                 .lockComponentByName(resource.getSystemName(), resource, CREATE_RESOURCE);
3025             if (lockResult.isRight()) {
3026                 serviceImportParseLogic.rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
3027                 throw new ComponentException(lockResult.right().value());
3028             }
3029             log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
3030         }
3031         try {
3032             log.trace("************* createResourceFromYaml before full create resource {}", yamlName);
3033             Resource genericResource = serviceBusinessLogic.fetchAndSetDerivedFromGenericType(resource);
3034             resource = createResourceTransaction(resource, csarInfo.getModifier(), isNormative);
3035             log.trace("************* Going to add inputs from yaml {}", yamlName);
3036             Map<String, Object> yamlMap = ImportUtils.loadYamlAsStrictMap(csarInfo.getMainTemplateContent());
3037             Map<String, Object> metadata = (Map<String, Object>) yamlMap.get("metadata");
3038             String type = (String) metadata.get("type");
3039             if (resource.shouldGenerateInputs() && !"Service".equalsIgnoreCase(type)) {
3040                 serviceBusinessLogic.generateAndAddInputsFromGenericTypeProperties(resource, genericResource);
3041             }
3042             Map<String, InputDefinition> inputs = parsedToscaYamlInfo.getInputs();
3043             resource = serviceImportParseLogic.createInputsOnResource(resource, inputs);
3044             Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap = parsedToscaYamlInfo.getInstances();
3045             resource = createRIAndRelationsFromYaml(yamlName, resource, uploadComponentInstanceInfoMap, topologyTemplateYaml,
3046                 nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, nodeName);
3047             log.trace("************* Finished to create nodes, RI and Relation  from yaml {}", yamlName);
3048             // validate update vf module group names
3049             Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic.validateUpdateVfGroupNames(
3050                 parsedToscaYamlInfo.getGroups(), resource.getSystemName());
3051             if (validateUpdateVfGroupNamesRes.isRight()) {
3052                 serviceImportParseLogic.rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
3053                 throw new ComponentException(validateUpdateVfGroupNamesRes.right().value());
3054             }
3055             Map<String, GroupDefinition> groups;
3056             log.trace("************* Going to add groups from yaml {}", yamlName);
3057             if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
3058                 groups = validateUpdateVfGroupNamesRes.left().value();
3059             } else {
3060                 groups = parsedToscaYamlInfo.getGroups();
3061             }
3062             Either<Resource, ResponseFormat> createGroupsOnResource = createGroupsOnResource(resource, groups);
3063             if (createGroupsOnResource.isRight()) {
3064                 serviceImportParseLogic.rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
3065                 throw new ComponentException(createGroupsOnResource.right().value());
3066             }
3067             resource = createGroupsOnResource.left().value();
3068             log.trace("************* Going to add artifacts from yaml {}", yamlName);
3069             NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName, nodeTypesArtifactsToCreate);
3070             Either<Resource, ResponseFormat> createArtifactsEither = createOrUpdateArtifacts(ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE,
3071                 createdArtifacts, yamlName, csarInfo, resource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
3072             if (createArtifactsEither.isRight()) {
3073                 serviceImportParseLogic.rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
3074                 throw new ComponentException(createArtifactsEither.right().value());
3075             }
3076             resource = serviceImportParseLogic.getResourceWithGroups(createArtifactsEither.left().value().getUniqueId());
3077             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
3078             componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, actionEnum);
3079             ASDCKpiApi.countCreatedResourcesKPI();
3080             return resource;
3081         } catch (ComponentException | StorageException e) {
3082             serviceImportParseLogic.rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
3083             throw e;
3084         } finally {
3085             if (!inTransaction) {
3086                 janusGraphDao.commit();
3087             }
3088             if (shouldLock) {
3089                 graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(), NodeTypeEnum.Resource);
3090             }
3091         }
3092     }
3093
3094     protected Either<Resource, ResponseFormat> createGroupsOnResource(Resource resource, Map<String, GroupDefinition> groups) {
3095         if (groups != null && !groups.isEmpty()) {
3096             List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(groups, resource);
3097             serviceImportParseLogic.handleGroupsProperties(resource, groups);
3098             serviceImportParseLogic.fillGroupsFinalFields(groupsAsList);
3099             Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.createGroups(resource, groupsAsList, true);
3100             if (createGroups.isRight()) {
3101                 return Either.right(createGroups.right().value());
3102             }
3103         } else {
3104             return Either.left(resource);
3105         }
3106         Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
3107         if (updatedResource.isRight()) {
3108             ResponseFormat responseFormat = componentsUtils
3109                 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource);
3110             return Either.right(responseFormat);
3111         }
3112         return Either.left(updatedResource.left().value());
3113     }
3114
3115     protected List<GroupDefinition> updateGroupsMembersUsingResource(Map<String, GroupDefinition> groups, Resource component) {
3116         List<GroupDefinition> result = new ArrayList<>();
3117         List<ComponentInstance> componentInstances = component.getComponentInstances();
3118         if (groups != null) {
3119             for (Map.Entry<String, GroupDefinition> entry : groups.entrySet()) {
3120                 String groupName = entry.getKey();
3121                 GroupDefinition groupDefinition = entry.getValue();
3122                 GroupDefinition updatedGroupDefinition = new GroupDefinition(groupDefinition);
3123                 updatedGroupDefinition.setMembers(null);
3124                 Map<String, String> members = groupDefinition.getMembers();
3125                 if (members != null) {
3126                     updateGroupMembers(groups, updatedGroupDefinition, component, componentInstances, groupName, members);
3127                 }
3128                 result.add(updatedGroupDefinition);
3129             }
3130         }
3131         return result;
3132     }
3133
3134     protected void updateGroupMembers(Map<String, GroupDefinition> groups, GroupDefinition updatedGroupDefinition, Resource component,
3135                                       List<ComponentInstance> componentInstances, String groupName, Map<String, String> members) {
3136         Set<String> compInstancesNames = members.keySet();
3137         if (CollectionUtils.isEmpty(componentInstances)) {
3138             String membersAstString = compInstancesNames.stream().collect(joining(","));
3139             log.debug("The members: {}, in group: {}, cannot be found in component {}. There are no component instances.", membersAstString,
3140                 groupName, component.getNormalizedName());
3141             throw new ComponentException(componentsUtils
3142                 .getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, component.getNormalizedName(),
3143                     serviceImportParseLogic.getComponentTypeForResponse(component)));
3144         }
3145         Map<String, String> memberNames = componentInstances.stream().collect(toMap(ComponentInstance::getName, ComponentInstance::getUniqueId));
3146         memberNames.putAll(groups.keySet().stream().collect(toMap(g -> g, g -> "")));
3147         Map<String, String> relevantInstances = memberNames.entrySet().stream().filter(n -> compInstancesNames.contains(n.getKey()))
3148             .collect(toMap(Map.Entry::getKey, Map.Entry::getValue));
3149         if (relevantInstances == null || relevantInstances.size() != compInstancesNames.size()) {
3150             List<String> foundMembers = new ArrayList<>();
3151             if (relevantInstances != null) {
3152                 foundMembers = relevantInstances.keySet().stream().collect(toList());
3153             }
3154             compInstancesNames.removeAll(foundMembers);
3155             String membersAstString = compInstancesNames.stream().collect(joining(","));
3156             throw new ComponentException(componentsUtils
3157                 .getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, component.getNormalizedName(),
3158                     serviceImportParseLogic.getComponentTypeForResponse(component)));
3159         }
3160         updatedGroupDefinition.setMembers(relevantInstances);
3161     }
3162
3163     protected Resource createResourceTransaction(Resource resource, User user, boolean isNormative) {
3164         Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade
3165             .validateComponentNameExists(resource.getName(), resource.getResourceType(), resource.getComponentType());
3166         if (eitherValidation.isRight()) {
3167             ResponseFormat errorResponse = componentsUtils
3168                 .getResponseFormat(componentsUtils.convertFromStorageResponse(eitherValidation.right().value()));
3169             throw new ComponentException(errorResponse);
3170         }
3171         if (Boolean.TRUE.equals(eitherValidation.left().value())) {
3172             log.debug("resource with name: {}, already exists", resource.getName());
3173             ResponseFormat errorResponse = componentsUtils
3174                 .getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
3175             throw new ComponentException(errorResponse);
3176         }
3177         log.debug("send resource {} to dao for create", resource.getName());
3178         serviceImportParseLogic.createArtifactsPlaceHolderData(resource, user);
3179         if (!isNormative) {
3180             log.debug("enrich resource with creator, version and state");
3181             resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
3182             resource.setVersion(INITIAL_VERSION);
3183             resource.setHighestVersion(true);
3184             if (resource.getResourceType() != null && resource.getResourceType() != ResourceTypeEnum.VF) {
3185                 resource.setAbstract(false);
3186             }
3187         }
3188         return toscaOperationFacade.createToscaComponent(resource).left()
3189             .on(r -> serviceImportParseLogic.throwComponentExceptionByResource(r, resource));
3190     }
3191
3192     protected ImmutablePair<Resource, ActionStatus> updateExistingResourceByImport(Resource newResource, Resource oldResource, User user,
3193                                                                                    boolean inTransaction, boolean needLock, boolean isNested) {
3194         String lockedResourceId = oldResource.getUniqueId();
3195         log.debug("found resource: name={}, id={}, version={}, state={}", oldResource.getName(), lockedResourceId, oldResource.getVersion(),
3196             oldResource.getLifecycleState());
3197         ImmutablePair<Resource, ActionStatus> resourcePair = null;
3198         try {
3199             serviceBusinessLogic.lockComponent(lockedResourceId, oldResource, needLock, "Update Resource by Import");
3200             oldResource = serviceImportParseLogic.prepareResourceForUpdate(oldResource, newResource, user, inTransaction, false);
3201             serviceImportParseLogic.mergeOldResourceMetadataWithNew(oldResource, newResource);
3202             serviceImportParseLogic.validateResourceFieldsBeforeUpdate(oldResource, newResource, inTransaction, isNested);
3203             serviceImportParseLogic.validateCapabilityTypesCreate(user, serviceImportParseLogic.getCapabilityTypeOperation(), newResource,
3204                 AuditingActionEnum.IMPORT_RESOURCE, inTransaction);
3205             createNewResourceToOldResource(newResource, oldResource, user);
3206             Either<Resource, StorageOperationStatus> overrideResource = toscaOperationFacade.overrideComponent(newResource, oldResource);
3207             if (overrideResource.isRight()) {
3208                 ResponseFormat responseFormat = new ResponseFormat();
3209                 serviceBusinessLogic.throwComponentException(responseFormat);
3210             }
3211             log.debug("Resource updated successfully!!!");
3212             resourcePair = new ImmutablePair<>(overrideResource.left().value(), ActionStatus.OK);
3213             return resourcePair;
3214         } finally {
3215             if (resourcePair == null) {
3216                 BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
3217                 janusGraphDao.rollback();
3218             } else if (!inTransaction) {
3219                 janusGraphDao.commit();
3220             }
3221             if (needLock) {
3222                 log.debug("unlock resource {}", lockedResourceId);
3223                 graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
3224             }
3225         }
3226     }
3227
3228     protected void createNewResourceToOldResource(Resource newResource, Resource oldResource, User user) {
3229         newResource.setContactId(newResource.getContactId().toLowerCase());
3230         newResource.setCreatorUserId(user.getUserId());
3231         newResource.setCreatorFullName(user.getFullName());
3232         newResource.setLastUpdaterUserId(user.getUserId());
3233         newResource.setLastUpdaterFullName(user.getFullName());
3234         newResource.setUniqueId(oldResource.getUniqueId());
3235         newResource.setVersion(oldResource.getVersion());
3236         newResource.setInvariantUUID(oldResource.getInvariantUUID());
3237         newResource.setLifecycleState(oldResource.getLifecycleState());
3238         newResource.setUUID(oldResource.getUUID());
3239         newResource.setNormalizedName(oldResource.getNormalizedName());
3240         newResource.setSystemName(oldResource.getSystemName());
3241         if (oldResource.getCsarUUID() != null) {
3242             newResource.setCsarUUID(oldResource.getCsarUUID());
3243         }
3244         if (oldResource.getCsarVersionId() != null) {
3245             newResource.setCsarVersionId(oldResource.getCsarVersionId());
3246         }
3247         if (oldResource.getImportedToscaChecksum() != null) {
3248             newResource.setImportedToscaChecksum(oldResource.getImportedToscaChecksum());
3249         }
3250         if (newResource.getDerivedFromGenericType() == null || newResource.getDerivedFromGenericType().isEmpty()) {
3251             newResource.setDerivedFromGenericType(oldResource.getDerivedFromGenericType());
3252         }
3253         if (newResource.getDerivedFromGenericVersion() == null || newResource.getDerivedFromGenericVersion().isEmpty()) {
3254             newResource.setDerivedFromGenericVersion(oldResource.getDerivedFromGenericVersion());
3255         }
3256         if (newResource.getToscaArtifacts() == null || newResource.getToscaArtifacts().isEmpty()) {
3257             serviceBusinessLogic.setToscaArtifactsPlaceHolders(newResource, user);
3258         }
3259         if (newResource.getInterfaces() == null || newResource.getInterfaces().isEmpty()) {
3260             newResource.setInterfaces(oldResource.getInterfaces());
3261         }
3262         if (CollectionUtils.isEmpty(newResource.getProperties())) {
3263             newResource.setProperties(oldResource.getProperties());
3264         }
3265         if (newResource.getModel() == null) {
3266             newResource.setModel(oldResource.getModel());
3267         }
3268     }
3269
3270     protected Map<String, Resource> createResourcesFromYamlNodeTypesList(String yamlName, Service service, Map<String, Object> mappedToscaTemplate,
3271                                                                          boolean needLock,
3272                                                                          Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
3273                                                                          List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
3274                                                                          Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo) {
3275         try {
3276             Either<String, ImportUtils.ResultStatusEnum> toscaVersion = findFirstToscaStringElement(mappedToscaTemplate,
3277                 TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION);
3278             if (toscaVersion.isRight()) {
3279                 throw new ComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE);
3280             }
3281             Map<String, Object> mapToConvert = new HashMap<>();
3282             mapToConvert.put(TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION.getElementName(), toscaVersion.left().value());
3283             Map<String, Object> nodeTypes = serviceImportParseLogic.getNodeTypesFromTemplate(mappedToscaTemplate);
3284             createNodeTypes(yamlName, service, needLock, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
3285                 mapToConvert, nodeTypes);
3286             return csarInfo.getCreatedNodes();
3287         } catch (Exception e) {
3288             log.debug("Exception occured when createResourcesFromYamlNodeTypesList,error is:{}", e.getMessage(), e);
3289             throw new ComponentException(ActionStatus.GENERAL_ERROR);
3290         }
3291     }
3292
3293     protected void createNodeTypes(String yamlName, Service service, boolean needLock,
3294                                    Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
3295                                    List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
3296                                    Map<String, Object> mapToConvert, Map<String, Object> nodeTypes) {
3297         Iterator<Map.Entry<String, Object>> nodesNameValueIter = nodeTypes.entrySet().iterator();
3298         Resource vfcCreated = null;
3299         while (nodesNameValueIter.hasNext()) {
3300             Map.Entry<String, Object> nodeType = nodesNameValueIter.next();
3301             String nodeTypeKey = nodeType.getKey();
3302             Map<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle =
3303                 nodeTypesArtifactsToHandle == null || nodeTypesArtifactsToHandle.isEmpty() ? null : nodeTypesArtifactsToHandle.get(nodeTypeKey);
3304             if (nodeTypesInfo.containsKey(nodeTypeKey)) {
3305                 vfcCreated = handleNestedVfc(service, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
3306                     nodeTypeKey);
3307                 log.trace("************* Finished to handle nested vfc {}", nodeTypeKey);
3308             } else if (csarInfo.getCreatedNodesToscaResourceNames() != null && !csarInfo.getCreatedNodesToscaResourceNames()
3309                 .containsKey(nodeTypeKey)) {
3310                 ImmutablePair<Resource, ActionStatus> resourceCreated = serviceImportParseLogic
3311                     .createNodeTypeResourceFromYaml(yamlName, nodeType, csarInfo.getModifier(), mapToConvert, service, needLock,
3312                         nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, true, csarInfo, true);
3313                 log.debug("************* Finished to create node {}", nodeTypeKey);
3314                 vfcCreated = resourceCreated.getLeft();
3315                 csarInfo.getCreatedNodesToscaResourceNames().put(nodeTypeKey, vfcCreated.getName());
3316             }
3317             if (vfcCreated != null) {
3318                 csarInfo.getCreatedNodes().put(nodeTypeKey, vfcCreated);
3319             }
3320             mapToConvert.remove(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName());
3321         }
3322     }
3323 }