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