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