[SDC] rebase 1710 code
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / components / impl / ResourceBusinessLogic.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.sdc.be.components.impl;
22
23 import static org.openecomp.sdc.be.tosca.CsarUtils.ARTIFACTS_PATH;
24 import static org.openecomp.sdc.be.tosca.CsarUtils.VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN;
25
26 import java.nio.charset.StandardCharsets;
27 import java.util.ArrayList;
28 import java.util.Collection;
29 import java.util.Collections;
30 import java.util.EnumMap;
31 import java.util.HashMap;
32 import java.util.HashSet;
33 import java.util.Iterator;
34 import java.util.List;
35 import java.util.Map;
36 import java.util.Map.Entry;
37 import java.util.Optional;
38 import java.util.Set;
39 import java.util.function.Function;
40 import java.util.regex.Matcher;
41 import java.util.regex.Pattern;
42 import java.util.stream.Collectors;
43
44 import javax.servlet.ServletContext;
45
46 import org.apache.commons.codec.binary.Base64;
47 import org.apache.commons.collections.CollectionUtils;
48 import org.apache.commons.collections.MapUtils;
49 import org.apache.commons.lang3.tuple.ImmutablePair;
50 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum;
51 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationInfo;
52 import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
53 import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaElementTypeEnum;
54 import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum;
55 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
56 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
57 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum;
58 import org.openecomp.sdc.be.config.BeEcompErrorManager;
59 import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
60 import org.openecomp.sdc.be.config.Configuration.VfModuleProperty;
61 import org.openecomp.sdc.be.config.ConfigurationManager;
62 import org.openecomp.sdc.be.dao.api.ActionStatus;
63 import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
64 import org.openecomp.sdc.be.datamodel.api.HighestFilterEnum;
65 import org.openecomp.sdc.be.datamodel.utils.ArtifactUtils;
66 import org.openecomp.sdc.be.datamodel.utils.UiComponentDataConverter;
67 import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
68 import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
69 import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
70 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
71 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
72 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
73 import org.openecomp.sdc.be.impl.ComponentsUtils;
74 import org.openecomp.sdc.be.impl.WebAppContextWrapper;
75 import org.openecomp.sdc.be.info.ArtifactTemplateInfo;
76 import org.openecomp.sdc.be.info.MergedArtifactInfo;
77 import org.openecomp.sdc.be.model.ArtifactDefinition;
78 import org.openecomp.sdc.be.model.CapabilityDefinition;
79 import org.openecomp.sdc.be.model.CapabilityTypeDefinition;
80 import org.openecomp.sdc.be.model.Component;
81 import org.openecomp.sdc.be.model.ComponentInstance;
82 import org.openecomp.sdc.be.model.ComponentInstanceInput;
83 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
84 import org.openecomp.sdc.be.model.ComponentParametersView;
85 import org.openecomp.sdc.be.model.DataTypeDefinition;
86 import org.openecomp.sdc.be.model.GroupDefinition;
87 import org.openecomp.sdc.be.model.GroupProperty;
88 import org.openecomp.sdc.be.model.GroupTypeDefinition;
89 import org.openecomp.sdc.be.model.HeatParameterDefinition;
90 import org.openecomp.sdc.be.model.ImportCsarInfo;
91 import org.openecomp.sdc.be.model.InputDefinition;
92 import org.openecomp.sdc.be.model.InterfaceDefinition;
93 import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
94 import org.openecomp.sdc.be.model.LifecycleStateEnum;
95 import org.openecomp.sdc.be.model.NodeTypeInfo;
96 import org.openecomp.sdc.be.model.Operation;
97 import org.openecomp.sdc.be.model.ParsedToscaYamlInfo;
98 import org.openecomp.sdc.be.model.PropertyDefinition;
99 import org.openecomp.sdc.be.model.RelationshipImpl;
100 import org.openecomp.sdc.be.model.RequirementAndRelationshipPair;
101 import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
102 import org.openecomp.sdc.be.model.RequirementDefinition;
103 import org.openecomp.sdc.be.model.Resource;
104 import org.openecomp.sdc.be.model.UploadCapInfo;
105 import org.openecomp.sdc.be.model.UploadComponentInstanceInfo;
106 import org.openecomp.sdc.be.model.UploadPropInfo;
107 import org.openecomp.sdc.be.model.UploadReqInfo;
108 import org.openecomp.sdc.be.model.UploadResourceInfo;
109 import org.openecomp.sdc.be.model.User;
110 import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
111 import org.openecomp.sdc.be.model.category.CategoryDefinition;
112 import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
113 import org.openecomp.sdc.be.model.heat.HeatParameterType;
114 import org.openecomp.sdc.be.model.operations.api.ICacheMangerOperation;
115 import org.openecomp.sdc.be.model.operations.api.ICapabilityTypeOperation;
116 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
117 import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation;
118 import org.openecomp.sdc.be.model.operations.api.IPropertyOperation;
119 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
120 import org.openecomp.sdc.be.model.operations.impl.CsarOperation;
121 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
122 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
123 import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
124 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
125 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
126 import org.openecomp.sdc.be.servlets.RepresentationUtils;
127 import org.openecomp.sdc.be.tosca.CsarUtils;
128 import org.openecomp.sdc.be.tosca.CsarUtils.NonMetaArtifactInfo;
129 import org.openecomp.sdc.be.tosca.ToscaUtils;
130 import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
131 import org.openecomp.sdc.be.user.IUserBusinessLogic;
132 import org.openecomp.sdc.be.user.Role;
133 import org.openecomp.sdc.be.user.UserBusinessLogic;
134 import org.openecomp.sdc.be.utils.CommonBeUtils;
135 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
136 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
137 import org.openecomp.sdc.common.api.Constants;
138 import org.openecomp.sdc.common.config.EcompErrorName;
139 import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
140 import org.openecomp.sdc.common.datastructure.FunctionalInterfaces;
141 import org.openecomp.sdc.common.datastructure.Wrapper;
142 import org.openecomp.sdc.common.kpi.api.ASDCKpiApi;
143 import org.openecomp.sdc.common.util.GeneralUtility;
144 import org.openecomp.sdc.common.util.ValidationUtils;
145 import org.openecomp.sdc.exception.ResponseFormat;
146 import org.slf4j.Logger;
147 import org.slf4j.LoggerFactory;
148 import org.springframework.beans.factory.annotation.Autowired;
149 import org.springframework.web.context.WebApplicationContext;
150 import org.yaml.snakeyaml.DumperOptions;
151 import org.yaml.snakeyaml.Yaml;
152
153 import com.google.gson.Gson;
154 import com.google.gson.JsonElement;
155 import com.google.gson.JsonObject;
156
157 import fj.data.Either;
158
159 @org.springframework.stereotype.Component("resourceBusinessLogic")
160 public class ResourceBusinessLogic extends ComponentBusinessLogic {
161
162         private static final String PLACE_HOLDER_RESOURCE_TYPES = "validForResourceTypes";
163         public static final String INITIAL_VERSION = "0.1";
164
165         private Pattern STR_REPLACE_PATTERN = Pattern.compile("^[ ]*\\{[ ]*" + "str_replace" + "=");
166         private Pattern TOKEN_PATTERN = Pattern.compile("[ ]*\\{[ ]*" + "token" + "=");
167         private Pattern GET_PROPERTY_PATTERN = Pattern.compile("[ ]*\\{[ ]*" + "get_property" + "=");
168         private Pattern CONCAT_PATTERN = Pattern.compile("[ ]*\\{[ ]*" + "concat" + "=");
169
170         private static Logger log = LoggerFactory.getLogger(ResourceBusinessLogic.class.getName());
171
172         private static Pattern pattern = Pattern.compile("\\..(.*?)\\..");
173
174         /**
175          * Default constructor
176          */
177         public ResourceBusinessLogic() {
178                 log.debug("ResourceBusinessLogic started");
179         }
180
181         @Autowired
182         private ICapabilityTypeOperation capabilityTypeOperation = null;
183
184         @Autowired
185         private IInterfaceLifecycleOperation interfaceTypeOperation = null;
186
187         @Autowired
188         private LifecycleBusinessLogic lifecycleBusinessLogic;
189
190         @Autowired
191         private IPropertyOperation propertyOperation;
192
193         @Autowired
194         private CsarOperation csarOperation;
195
196         @Autowired
197         private VFComponentInstanceBusinessLogic vfComponentInstanceBusinessLogic;
198
199         @Autowired
200         private ResourceImportManager resourceImportManager;
201
202         @Autowired
203         private GroupBusinessLogic groupBusinessLogic;
204
205         @Autowired
206         private InputsBusinessLogic inputsBusinessLogic;
207
208         @Autowired
209         private CompositionBusinessLogic compositionBusinessLogic;
210
211         @Autowired
212         private ICacheMangerOperation cacheManagerOperation;
213
214         @Autowired
215         private ApplicationDataTypeCache dataTypeCache;
216
217         private Gson gson = new Gson();
218
219         public CsarOperation getCsarOperation() {
220                 return csarOperation;
221         }
222
223         public void setCsarOperation(CsarOperation csarOperation) {
224                 this.csarOperation = csarOperation;
225         }
226
227         public LifecycleBusinessLogic getLifecycleBusinessLogic() {
228                 return lifecycleBusinessLogic;
229         }
230
231         public void setLifecycleManager(LifecycleBusinessLogic lifecycleBusinessLogic) {
232                 this.lifecycleBusinessLogic = lifecycleBusinessLogic;
233         }
234
235         public IElementOperation getElementDao() {
236                 return elementDao;
237         }
238
239         public void setElementDao(IElementOperation elementDao) {
240                 this.elementDao = elementDao;
241         }
242
243         public IUserBusinessLogic getUserAdmin() {
244                 return this.userAdmin;
245         }
246
247         public void setUserAdmin(UserBusinessLogic userAdmin) {
248                 this.userAdmin = userAdmin;
249         }
250
251         public ComponentsUtils getComponentsUtils() {
252                 return this.componentsUtils;
253         }
254
255         public void setComponentsUtils(ComponentsUtils componentsUtils) {
256                 this.componentsUtils = componentsUtils;
257         }
258
259         public ArtifactsBusinessLogic getArtifactsManager() {
260                 return artifactsBusinessLogic;
261         }
262
263         public void setArtifactsManager(ArtifactsBusinessLogic artifactsManager) {
264                 this.artifactsBusinessLogic = artifactsManager;
265         }
266
267         public void setPropertyOperation(IPropertyOperation propertyOperation) {
268                 this.propertyOperation = propertyOperation;
269         }
270
271         public ApplicationDataTypeCache getApplicationDataTypeCache() {
272                 return applicationDataTypeCache;
273         }
274
275         public void setApplicationDataTypeCache(ApplicationDataTypeCache applicationDataTypeCache) {
276                 this.applicationDataTypeCache = applicationDataTypeCache;
277         }
278
279         /**
280          * the method returns a list of all the resources that are certified, the returned resources are only abstract or only none abstract according to the given param
281          *
282          * @param getAbstract
283          * @param userId      TODO
284          * @return
285          */
286         public Either<List<Resource>, ResponseFormat> getAllCertifiedResources(boolean getAbstract, HighestFilterEnum highestFilter, String userId) {
287                 Either<User, ResponseFormat> resp = validateUserExists(userId, "get All Certified Resources", false);
288                 if (resp.isRight()) {
289                         return Either.right(resp.right().value());
290                 }
291                 Boolean isHighest = null;
292                 switch (highestFilter) {
293                 case ALL:
294                         break;
295                 case HIGHEST_ONLY:
296                         isHighest = true;
297                         break;
298                 case NON_HIGHEST_ONLY:
299                         isHighest = false;
300                         break;
301                 default:
302                         break;
303                 }
304                 Either<List<Resource>, StorageOperationStatus> getResponse = toscaOperationFacade.getAllCertifiedResources(getAbstract, isHighest);
305
306                 if (getResponse.isRight()) {
307                         return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getResponse.right().value())));
308                 }
309
310                 return Either.left(getResponse.left().value());
311         }
312
313         public Either<Map<String, Boolean>, ResponseFormat> validateResourceNameExists(String resourceName, ResourceTypeEnum resourceTypeEnum, String userId) {
314
315                 Either<User, ResponseFormat> resp = validateUserExists(userId, "validate Resource Name Exists", false);
316                 if (resp.isRight()) {
317                         return Either.right(resp.right().value());
318                 }
319
320                 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateComponentNameUniqueness(resourceName, resourceTypeEnum, ComponentTypeEnum.RESOURCE);
321                 // DE242223
322                 titanDao.commit();
323
324                 if (dataModelResponse.isLeft()) {
325                         Map<String, Boolean> result = new HashMap<>();
326                         result.put("isValid", dataModelResponse.left().value());
327                         log.debug("validation was successfully performed.");
328                         return Either.left(result);
329                 }
330
331                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()));
332
333                 return Either.right(responseFormat);
334         }
335
336         public Either<Resource, ResponseFormat> createResource(Resource resource, AuditingActionEnum auditingAction, User user, Map<String, byte[]> csarUIPayload, String payloadName) {
337                 Either<Resource, ResponseFormat> createResourceResponse = validateResourceBeforeCreate(resource, user, false);
338                 if (createResourceResponse.isRight()) {
339                         return createResourceResponse;
340                 }
341
342                 // Creating resource either by DAO or from CSAR
343                 String csarUUID = null;
344                 if (payloadName == null) {
345                         csarUUID = resource.getCsarUUID();
346                 } else {
347                         csarUUID = payloadName;
348                 }
349                 if (csarUUID != null && !csarUUID.isEmpty()) {
350                         // check if VF with the same Csar UUID or with he same name already
351                         // exists
352                         Either<Integer, StorageOperationStatus> validateCsarUuidUniquenessRes = toscaOperationFacade.validateCsarUuidUniqueness(csarUUID);
353                         if (validateCsarUuidUniquenessRes.isRight()) {
354                                 log.debug("Failed to validate uniqueness of CsarUUID {} for resource", csarUUID, resource.getSystemName());
355                                 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validateCsarUuidUniquenessRes.right().value())));
356                         }
357
358                         Integer existingResourceRes = validateCsarUuidUniquenessRes.left().value();
359                         if (existingResourceRes.intValue() > 0) {
360                                 log.debug("Failed to create resource {}, csarUUID {} already exist for a different VF ", resource.getSystemName(), csarUUID);
361                                 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VSP_ALREADY_EXISTS, csarUUID);
362                                 componentsUtils.auditResource(errorResponse, user, resource, "", "", auditingAction, null);
363                                 return Either.right(errorResponse);
364                         }
365
366                         log.debug("CsarUUID is {} - going to create resource from CSAR", csarUUID);
367                         createResourceResponse = createResourceFromCsar(resource, user, Either.left(csarUIPayload), csarUUID);
368                         return createResourceResponse;
369                 }
370
371                 return createResourceByDao(resource, user, auditingAction, false, false, null);
372         }
373
374         public Either<Resource, ResponseFormat> validateAndUpdateResourceFromCsar(Resource resource, User user, Map<String, byte[]> csarUIPayload, String payloadName, String resourceUniqueId) {
375                 Either<Resource, ResponseFormat> updateResourceResponse = null;
376                 Either<Resource, ResponseFormat> validateResourceResponse = null;
377                 Wrapper<ResponseFormat> responseWrapper = new Wrapper<ResponseFormat>();
378                 String csarUUID = null;
379                 String csarVersion = null;
380                 if (payloadName == null) {
381                         csarUUID = resource.getCsarUUID();
382                         csarVersion = resource.getCsarVersion();
383                 } else {
384                         csarUUID = payloadName;
385                 }
386                 if (csarUUID != null && !csarUUID.isEmpty()) {
387                         Resource oldResource = getResourceByUniqueId(responseWrapper, resourceUniqueId);
388                         if (responseWrapper.isEmpty()) {
389                                 validateCsarUuidMatching(responseWrapper, oldResource, resource, csarUUID, resourceUniqueId, user);
390                         }
391                         if (responseWrapper.isEmpty()) {
392                                 validateCsarIsNotAlreadyUsed(responseWrapper, oldResource, resource, csarUUID, user);
393                         }
394                         if (responseWrapper.isEmpty()) {
395                                 if (oldResource != null && ValidationUtils.hasBeenCertified(oldResource.getVersion())) {
396                                         overrideImmutableMetadata(oldResource, resource);
397                                 }
398                                 validateResourceResponse = validateResourceBeforeCreate(resource, user, false);
399                                 if (validateResourceResponse.isRight()) {
400                                         responseWrapper.setInnerElement(validateResourceResponse.right().value());
401                                 }
402                         }
403                         if (responseWrapper.isEmpty()) {
404                                 String oldCsarVersion = oldResource.getCsarVersion();
405                                 log.debug("CsarUUID is {} - going to update resource with UniqueId {} from CSAR", csarUUID, resourceUniqueId);
406                                 // (on boarding flow): If the update includes same csarUUID and
407                                 // same csarVersion as already in the VF - no need to import the
408                                 // csar (do only metadata changes if there are).
409                                 if (csarVersion != null && oldCsarVersion != null && oldCsarVersion.equals(csarVersion)) {
410                                         updateResourceResponse = updateResourceMetadata(resourceUniqueId, resource, oldResource, user, false);
411                                 } else {
412                                         updateResourceResponse = updateResourceFromCsar(oldResource, resource, user, AuditingActionEnum.UPDATE_RESOURCE_METADATA, false, Either.left(csarUIPayload), csarUUID);
413                                 }
414                         }
415                 } else {
416                         log.debug("Failed to update resource {}, csarUUID or payload name is missing", resource.getSystemName());
417                         ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CSAR_UUID, resource.getName());
418                         componentsUtils.auditResource(errorResponse, user, resource, "", "", AuditingActionEnum.CREATE_RESOURCE, null);
419                         responseWrapper.setInnerElement(errorResponse);
420                 }
421                 if (responseWrapper.isEmpty()) {
422                         return updateResourceResponse;
423                 }
424                 return Either.right(responseWrapper.getInnerElement());
425         }
426
427         private void validateCsarIsNotAlreadyUsed(Wrapper<ResponseFormat> responseWrapper, Resource oldResource, Resource resource, String csarUUID, User user) {
428                 // (on boarding flow): If the update includes a csarUUID: verify this
429                 // csarUUID is not in use by another VF, If it is - use same error as
430                 // above:
431                 // "Error: The VSP with UUID %1 was already imported for VF %2. Please
432                 // select another or update the existing VF." %1 - csarUUID, %2 - VF
433                 // name
434                 Either<Resource, StorageOperationStatus> resourceLinkedToCsarRes = toscaOperationFacade.getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUUID, resource.getSystemName());
435                 if (resourceLinkedToCsarRes.isRight()) {
436                         if (!StorageOperationStatus.NOT_FOUND.equals(resourceLinkedToCsarRes.right().value())) {
437                                 log.debug("Failed to find previous resource by CSAR {} and system name {}", csarUUID, resource.getSystemName());
438                                 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceLinkedToCsarRes.right().value())));
439                         }
440                 } else if (!resourceLinkedToCsarRes.left().value().getUniqueId().equals(oldResource.getUniqueId()) && !resourceLinkedToCsarRes.left().value().getName().equals(oldResource.getName())) {
441                         ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VSP_ALREADY_EXISTS, csarUUID, resourceLinkedToCsarRes.left().value().getName());
442                         componentsUtils.auditResource(errorResponse, user, resource, "", "", AuditingActionEnum.UPDATE_RESOURCE_METADATA, null);
443                         responseWrapper.setInnerElement(errorResponse);
444                 }
445         }
446
447         private void validateCsarUuidMatching(Wrapper<ResponseFormat> responseWrapper, Resource resource, Resource oldResource, String csarUUID, String resourceUniqueId, User user) {
448                 // (on boarding flow): If the update includes csarUUID which is
449                 // different from the csarUUID of the VF - fail with
450                 // error: "Error: Resource %1 cannot be updated using since it is linked
451                 // to a different VSP" %1 - VF name
452                 String oldCsarUUID = oldResource.getCsarUUID();
453                 if (oldCsarUUID != null && !oldCsarUUID.isEmpty() && !csarUUID.equals(oldCsarUUID)) {
454                         log.debug("Failed to update resource with UniqueId {} using Csar {}, since the resource is linked to a different VSP {}", resourceUniqueId, csarUUID, oldCsarUUID);
455                         ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_LINKED_TO_DIFFERENT_VSP, resource.getName(), csarUUID, oldCsarUUID);
456                         componentsUtils.auditResource(errorResponse, user, resource, "", "", AuditingActionEnum.UPDATE_RESOURCE_METADATA, null);
457                         responseWrapper.setInnerElement(errorResponse);
458                 }
459         }
460
461         private Resource getResourceByUniqueId(Wrapper<ResponseFormat> responseWrapper, String resourceUniqueId) {
462                 Either<Resource, StorageOperationStatus> oldResourceRes = toscaOperationFacade.getToscaElement(resourceUniqueId);
463                 if (oldResourceRes.isRight()) {
464                         log.debug("Failed to find previous resource by UniqueId {}, status: {}", resourceUniqueId, oldResourceRes.right().value());
465                         responseWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(oldResourceRes.right().value())));
466                         return null;
467                 }
468                 return oldResourceRes.left().value();
469         }
470
471         private void overrideImmutableMetadata(Resource oldRresource, Resource resource) {
472                 resource.setName(oldRresource.getName());
473                 resource.setIcon(oldRresource.getIcon());
474                 resource.setTags(oldRresource.getTags());
475                 resource.setVendorName(oldRresource.getVendorName());
476                 resource.setCategories(oldRresource.getCategories());
477                 resource.setDerivedFrom(oldRresource.getDerivedFrom());
478         }
479
480         private Either<Resource, ResponseFormat> updateResourceFromCsar(Resource oldRresource, Resource newRresource, User user, AuditingActionEnum updateResource, boolean inTransaction, Either<Map<String, byte[]>, StorageOperationStatus> csarUIPayload,
481                         String csarUUID) {
482
483                 // check state
484                 if (LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.equals(oldRresource.getLifecycleState())) {
485                         if (!oldRresource.getLastUpdaterUserId().equals(user.getUserId())) {
486                                 log.debug("Current user is not last updater, last updater userId: {}, current user userId: {}", oldRresource.getLastUpdaterUserId(), user.getUserId());
487                                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
488                         }
489                 }
490                 String lockedResourceId = oldRresource.getUniqueId();
491                 List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
492                 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>();
493
494                 Either<Map<String, byte[]>, StorageOperationStatus> csar = null;
495                 if (csarUIPayload != null && csarUIPayload.left() != null && csarUIPayload.left().value() != null) {
496                         csar = csarUIPayload;
497                 } else {
498                         csar = csarOperation.getCsar(csarUUID, user);
499                 }
500                 if (csar.isRight()) {
501                         log.debug("Failed to get csar for casrUUID{} ", csarUUID);
502                         return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(csar.right().value())));
503                 }
504
505                 Either<ImmutablePair<String, String>, ResponseFormat> toscaYamlCsarStatus = validateAndParseCsar(newRresource, user, csarUUID, csar);
506                 if (toscaYamlCsarStatus.isRight()) {
507                         return Either.right(toscaYamlCsarStatus.right().value());
508                 }
509                 Either<String, ResponseFormat> checksum = CsarValidationUtils.getToscaYamlChecksum(csar.left().value(), csarUUID, componentsUtils);
510                 if (checksum.isRight()) {
511                         log.debug("Failed to calculate checksum for casrUUID{} error {} ", csarUUID, checksum.right().value());
512                         return Either.right(checksum.right().value());
513                 }
514                 boolean isUpdateYaml = true;
515                 if (checksum.left().value().equals(oldRresource.getComponentMetadataDefinition().getMetadataDataDefinition().getImportedToscaChecksum())) {
516                         log.debug("The checksums are equals for csarUUID {}, existing checsum is {}, new one is {} ", csarUUID, oldRresource.getComponentMetadataDefinition().getMetadataDataDefinition().getImportedToscaChecksum(), checksum.left().value());
517                         if (oldRresource.getLifecycleState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT))
518                                 isUpdateYaml = false;
519                 } else {
520                         oldRresource.getComponentMetadataDefinition().getMetadataDataDefinition().setImportedToscaChecksum(checksum.left().value());
521                 }
522
523                 Either<Boolean, ResponseFormat> lockResult = lockComponent(lockedResourceId, oldRresource, "update Resource From Csar");
524                 if (lockResult.isRight()) {
525                         return Either.right(lockResult.right().value());
526                 }
527
528                 Either<Resource, ResponseFormat> result = null;
529                 String yamlFileName = toscaYamlCsarStatus.left().value().getKey();
530                 String yamlFileContents = toscaYamlCsarStatus.left().value().getValue();
531                 Either<Map<String, Resource>, ResponseFormat> parseNodeTypeInfoYamlEither = null;
532                 ImportCsarInfo importCsarInfo = new ImportCsarInfo(newRresource.getName(), user, csarUUID, csar.left().value());
533
534                 try {
535                         Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> prepareForUpdate = null;
536                         Resource preparedResource = null;
537                         Either<ParsedToscaYamlInfo, ResponseFormat> uploadComponentInstanceInfoMap = parseResourceInfoFromYaml(yamlFileName, newRresource, toscaYamlCsarStatus.left().value().getValue(), user, importCsarInfo.getCreatedNodesToscaResourceNames(), null, null);
538                         if (uploadComponentInstanceInfoMap.isRight()) {
539                                 ResponseFormat responseFormat = uploadComponentInstanceInfoMap.right().value();
540                                 componentsUtils.auditResource(responseFormat, user, newRresource, "", "", updateResource, null);
541                                 result = Either.right(responseFormat);
542                                 return result;
543                         }
544                         Map<String, NodeTypeInfo> nodeTypesInfo = extractNodeTypesInfo(csar.left().value(), yamlFileContents);
545                         Map<String, UploadComponentInstanceInfo> instances = uploadComponentInstanceInfoMap.left().value().getInstances();
546                         Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(nodeTypesInfo, csar.left().value(), csarUUID, yamlFileName, oldRresource, user, true,
547                                         instances);
548                         if (findNodeTypesArtifactsToHandleRes.isRight()) {
549                                 log.debug("failed to find node types for update with artifacts during import csar {}. ", csarUUID);
550                                 result = Either.right(findNodeTypesArtifactsToHandleRes.right().value());
551                                 return result;
552                         }
553                         Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = findNodeTypesArtifactsToHandleRes.left().value();
554                         if (isUpdateYaml || !nodeTypesArtifactsToHandle.isEmpty()) {
555
556                                 prepareForUpdate = updateExistingResourceByImport(newRresource, oldRresource, user, true, false);
557                                 if (prepareForUpdate.isRight()) {
558                                         log.debug("Failed to prepare resource for update : {}", prepareForUpdate.right().value());
559                                         result = Either.right(prepareForUpdate.right().value());
560                                         return result;
561                                 }
562                                 preparedResource = prepareForUpdate.left().value().left;
563
564                                 log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContents);
565
566                                 parseNodeTypeInfoYamlEither = this.handleNodeTypes(yamlFileName, preparedResource, yamlFileContents, false, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, importCsarInfo);
567                                 if (parseNodeTypeInfoYamlEither.isRight()) {
568                                         ResponseFormat responseFormat = parseNodeTypeInfoYamlEither.right().value();
569                                         componentsUtils.auditResource(responseFormat, user, preparedResource, "", "", updateResource, null);
570                                         result = Either.right(responseFormat);
571                                         return result;
572                                 }
573
574                                 Map<String, InputDefinition> inputs = uploadComponentInstanceInfoMap.left().value().getInputs();
575                                 Either<Resource, ResponseFormat> createInputsOnResource = createInputsOnResource(preparedResource, user, inputs, true);
576                                 if (createInputsOnResource.isRight()) {
577                                         log.debug("failed to create resource inputs status is {}", createInputsOnResource.right().value());
578                                         ResponseFormat responseFormat = createInputsOnResource.right().value();
579                                         componentsUtils.auditResource(createInputsOnResource.right().value(), user, preparedResource, "", "", updateResource, null);
580                                         result = Either.right(responseFormat);
581                                         return result;
582                                 }
583                                 preparedResource = createInputsOnResource.left().value();
584
585                                 Either<Resource, ResponseFormat> createResourcesInstancesEither = createResourceInstances(user, yamlFileName, preparedResource, instances, true, false, parseNodeTypeInfoYamlEither.left().value());
586                                 if (createResourcesInstancesEither.isRight()) {
587                                         log.debug("failed to create resource instances status is {}", createResourcesInstancesEither.right().value());
588                                         ResponseFormat responseFormat = createResourcesInstancesEither.right().value();
589                                         componentsUtils.auditResource(createResourcesInstancesEither.right().value(), user, preparedResource, "", "", updateResource, null);
590                                         result = Either.right(responseFormat);
591                                         return result;
592                                 }
593                                 preparedResource = createResourcesInstancesEither.left().value();
594
595                                 createResourcesInstancesEither = createResourceInstancesRelations(user, yamlFileName, preparedResource, instances, true, false);
596                                 if (createResourcesInstancesEither.isRight()) {
597                                         log.debug("failed to create relation between resource instances status is {}", createResourcesInstancesEither.right().value());
598                                         result = Either.right(createResourcesInstancesEither.right().value());
599                                         return result;
600                                 }
601
602                                 preparedResource = createResourcesInstancesEither.left().value();
603
604                                 Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic.validateUpdateVfGroupNames(uploadComponentInstanceInfoMap.left().value().getGroups(), preparedResource.getSystemName());
605                                 if (validateUpdateVfGroupNamesRes.isRight()) {
606
607                                         return Either.right(validateUpdateVfGroupNamesRes.right().value());
608                                 }
609                                 // add groups to resource
610                                 Map<String, GroupDefinition> groups;
611
612                                 if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
613                                         groups = validateUpdateVfGroupNamesRes.left().value();
614                                 } else {
615                                         groups = uploadComponentInstanceInfoMap.left().value().getGroups();
616                                 }
617                                 Either<Resource, ResponseFormat> updatedGroupsOnResource = updateGroupsOnResource(preparedResource, user, groups);
618                                 if (updatedGroupsOnResource.isRight()) {
619
620                                         return updatedGroupsOnResource;
621                                 }
622                                 preparedResource = updatedGroupsOnResource.left().value();
623
624                         } else {
625                                 Either<Resource, ResponseFormat> dataModelResponse = updateResourceMetadata(oldRresource.getUniqueId(), newRresource, user, oldRresource, false, true);
626                                 if (dataModelResponse.isRight()) {
627                                         log.debug("failed to update resource metadata {}", dataModelResponse.right().value());
628                                         result = Either.right(dataModelResponse.right().value());
629                                         return result;
630                                 }
631                                 preparedResource = dataModelResponse.left().value();
632                         }
633
634                         Either<Resource, ResponseFormat> createdCsarArtifactsEither = handleVfCsarArtifacts(preparedResource, importCsarInfo, createdArtifacts,
635                                         artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Update), false, true);
636                         if (createdCsarArtifactsEither.isRight()) {
637
638                                 return createdCsarArtifactsEither;
639                         }
640                         preparedResource = createdCsarArtifactsEither.left().value();
641
642                         Either<List<ComponentInstance>, ResponseFormat> eitherSetPosition = compositionBusinessLogic.setPositionsForComponentInstances(preparedResource, user.getUserId());
643                         result = eitherSetPosition.isRight() ? Either.right(eitherSetPosition.right().value()) : Either.left(preparedResource);
644
645                         return result;
646
647                 } finally {
648                         if (result == null || result.isRight()) {
649                                 log.warn("operation failed. do rollback");
650                                 titanDao.rollback();
651                                 if (!createdArtifacts.isEmpty() || !nodeTypesNewCreatedArtifacts.isEmpty()) {
652                                         createdArtifacts.addAll(nodeTypesNewCreatedArtifacts);
653                                         StorageOperationStatus deleteFromEsRes = artifactsBusinessLogic.deleteAllComponentArtifactsIfNotOnGraph(createdArtifacts);
654                                         if (!deleteFromEsRes.equals(StorageOperationStatus.OK)) {
655                                                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(deleteFromEsRes);
656                                                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, oldRresource.getName());
657                                         }
658                                         log.debug("component and all its artifacts were deleted, id = {}", oldRresource.getName());
659                                 }
660                         } else {
661                                 log.debug("operation success. do commit");
662                                 titanDao.commit();
663                         }
664                         log.debug("unlock resource {}", lockedResourceId);
665                         graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
666                 }
667
668         }
669
670         private Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandle(Map<String, NodeTypeInfo> nodeTypesInfo, Map<String, byte[]> csar, String csarUUID, String yamlFileName, Resource oldResource, User user,
671                         boolean inTransaction, Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap) {
672
673                 Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts = CsarUtils.extractVfcsArtifactsFromCsar(csar);
674                 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = new HashMap<>();
675                 Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> nodeTypesArtifactsToHandleRes;
676
677                 try {
678                         nodeTypesArtifactsToHandleRes = Either.left(nodeTypesArtifactsToHandle);
679                         Map<String, String> extractedVfcToscaNames = extractVfcToscaNames(nodeTypesInfo, yamlFileName, oldResource.getSystemName(), uploadComponentInstanceInfoMap);
680                         Either<EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>, ResponseFormat> curNodeTypeArtifactsToHandleRes = null;
681                         EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> curNodeTypeArtifactsToHandle = null;
682                         log.debug("Going to fetch node types for resource with name {} during import csar with UUID {}. ", oldResource.getName(), csarUUID);
683
684                         for (Entry<String, String> currVfcToscaNameEntry : extractedVfcToscaNames.entrySet()) {
685                                 String currVfcToscaName = currVfcToscaNameEntry.getValue();
686                                 String currNamespace = currVfcToscaNameEntry.getKey();
687                                 log.debug("Going to fetch node type with tosca name {}. ", currVfcToscaName);
688
689                                 Either<Resource, StorageOperationStatus> curVfcRes = toscaOperationFacade.getLatestByToscaResourceName(currVfcToscaName);
690                                 Resource curNodeType = null;
691                                 if (curVfcRes.isRight() && curVfcRes.right().value() != StorageOperationStatus.NOT_FOUND) {
692                                         log.debug("Error occured during fetching node type with tosca name {}, error: {}", currVfcToscaName, curVfcRes.right().value());
693                                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(curVfcRes.right().value()), csarUUID);
694                                         componentsUtils.auditResource(responseFormat, user, oldResource, "", "", AuditingActionEnum.CREATE_RESOURCE, null);
695                                         nodeTypesArtifactsToHandleRes = Either.right(responseFormat);
696                                         break;
697                                 } else if (curVfcRes.isLeft()) {
698                                         curNodeType = curVfcRes.left().value();
699                                 }
700                                 if (!MapUtils.isEmpty(extractedVfcsArtifacts)) {
701                                         List<ArtifactDefinition> currArtifacts = new ArrayList<>();
702                                         if (extractedVfcsArtifacts.containsKey(currNamespace)) {
703                                                 handleAndAddExtractedVfcsArtifacts(currArtifacts, extractedVfcsArtifacts.get(currNamespace));
704                                         }
705                                         curNodeTypeArtifactsToHandleRes = findNodeTypeArtifactsToHandle(curNodeType, currArtifacts);
706                                         if (curNodeTypeArtifactsToHandleRes.isRight()) {
707                                                 nodeTypesArtifactsToHandleRes = Either.right(curNodeTypeArtifactsToHandleRes.right().value());
708                                                 break;
709                                         }
710                                         curNodeTypeArtifactsToHandle = curNodeTypeArtifactsToHandleRes.left().value();
711
712                                 } else if (curNodeType != null) {
713                                         // delete all artifacts if have not received artifacts from csar
714                                         curNodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
715                                         List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
716                                         // delete all informational artifacts
717                                         artifactsToDelete.addAll(curNodeType.getArtifacts().values().stream().filter(a -> a.getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL).collect(Collectors.toList()));
718                                         // delete all deployment artifacts
719                                         artifactsToDelete.addAll(curNodeType.getDeploymentArtifacts().values());
720                                         if (!artifactsToDelete.isEmpty()) {
721                                                 curNodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Delete, artifactsToDelete);
722                                         }
723                                 }
724                                 if (MapUtils.isNotEmpty(curNodeTypeArtifactsToHandle)) {
725                                         nodeTypesArtifactsToHandle.put(currVfcToscaNameEntry.getKey(), curNodeTypeArtifactsToHandle);
726                                 }
727                         }
728                 } catch (Exception e) {
729                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
730                         nodeTypesArtifactsToHandleRes = Either.right(responseFormat);
731                         log.debug("Exception occured when findNodeTypesUpdatedArtifacts, error is:{}", e.getMessage(), e);
732                 }
733                 return nodeTypesArtifactsToHandleRes;
734         }
735
736         private Either<EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>, ResponseFormat> findNodeTypeArtifactsToHandle(Resource curNodeType, List<ArtifactDefinition> extractedArtifacts) {
737
738                 Either<EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>, ResponseFormat> nodeTypeArtifactsToHandleRes = null;
739                 EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null;
740                 Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
741                 try {
742                         List<ArtifactDefinition> artifactsToUpload = new ArrayList<>(extractedArtifacts);
743                         List<ArtifactDefinition> artifactsToUpdate = new ArrayList<>();
744                         List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
745                         if (curNodeType != null) {
746                                 Map<String, ArtifactDefinition> existingArtifacts = new HashMap<>();
747                                 if (curNodeType.getDeploymentArtifacts() != null) {
748                                         existingArtifacts.putAll(curNodeType.getDeploymentArtifacts());
749                                 }
750                                 if (curNodeType.getArtifacts() != null) {
751                                         existingArtifacts.putAll(curNodeType.getArtifacts().entrySet().stream().filter(e -> e.getValue().getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL).collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue())));
752                                 }
753                                 for (ArtifactDefinition currNewArtifact : extractedArtifacts) {
754                                         ArtifactDefinition foundArtifact;
755
756                                         if (!existingArtifacts.isEmpty()) {
757                                                 foundArtifact = existingArtifacts.values().stream().filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst().orElse(null);
758                                                 if (foundArtifact != null) {
759                                                         if (foundArtifact.getArtifactType().equals(currNewArtifact.getArtifactType())) {
760                                                                 if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) {
761                                                                         foundArtifact.setPayload(currNewArtifact.getPayloadData());
762                                                                         foundArtifact.setPayloadData(Base64.encodeBase64String(currNewArtifact.getPayloadData()));
763                                                                         foundArtifact.setArtifactChecksum(GeneralUtility.calculateMD5ByByteArray(currNewArtifact.getPayloadData()));
764                                                                         artifactsToUpdate.add(foundArtifact);
765                                                                 }
766                                                                 existingArtifacts.remove(foundArtifact.getArtifactLabel());
767                                                                 artifactsToUpload.remove(currNewArtifact);
768                                                         } else {
769                                                                 log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName());
770                                                                 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(),
771                                                                                 foundArtifact.getArtifactType());
772                                                                 responseWrapper.setInnerElement(responseFormat);
773                                                                 break;
774                                                         }
775                                                 }
776                                         }
777                                 }
778                                 if (responseWrapper.isEmpty()) {
779                                         artifactsToDelete.addAll(existingArtifacts.values());
780                                 }
781                         }
782                         if (responseWrapper.isEmpty()) {
783                                 if (!artifactsToUpload.isEmpty() || !artifactsToUpdate.isEmpty() || !artifactsToDelete.isEmpty()) {
784                                         nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
785                                         if (!artifactsToUpload.isEmpty())
786                                                 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Create, artifactsToUpload);
787                                         if (!artifactsToUpdate.isEmpty())
788                                                 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Update, artifactsToUpdate);
789                                         if (!artifactsToDelete.isEmpty())
790                                                 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Delete, artifactsToDelete);
791                                 }
792                                 nodeTypeArtifactsToHandleRes = Either.left(nodeTypeArtifactsToHandle);
793                         }
794                         if (!responseWrapper.isEmpty()) {
795                                 nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement());
796                         }
797                 } catch (Exception e) {
798                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
799                         responseWrapper.setInnerElement(responseFormat);
800                         log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
801                 }
802                 return nodeTypeArtifactsToHandleRes;
803         }
804
805         /**
806          * Changes resource life cycle state to checked out
807          *
808          * @param resource
809          * @param user
810          * @param inTransaction
811          * @return
812          */
813         private Either<Resource, ResponseFormat> checkoutResource(Resource resource, User user, boolean inTransaction) {
814                 Either<Resource, ResponseFormat> checkoutResourceRes;
815                 try {
816                         if (!resource.getComponentMetadataDefinition().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
817                                 log.debug("************* Going to change life cycle state of resource {} to not certified checked out. ", resource.getName());
818                                 Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(resource.getComponentType(), resource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
819                                                 new LifecycleChangeInfoWithAction("certification on import", LifecycleChanceActionEnum.CREATE_FROM_CSAR), inTransaction, true);
820                                 if (checkoutRes.isRight()) {
821                                         log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ", resource.getComponentType().getNodeType(), resource.getUniqueId(), checkoutRes.right().value().getStatus());
822                                         checkoutResourceRes = Either.right(checkoutRes.right().value());
823                                 } else {
824                                         checkoutResourceRes = Either.left((Resource) checkoutRes.left().value());
825                                 }
826                         } else {
827                                 checkoutResourceRes = Either.left(resource);
828                         }
829                 } catch (Exception e) {
830                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
831                         checkoutResourceRes = Either.right(responseFormat);
832                         log.debug("Exception occured when checkoutResource {} , error is:{}", resource.getName(), e.getMessage(), e);
833                 }
834                 return checkoutResourceRes;
835         }
836
837         /**
838          * Handles Artifacts of NodeType
839          *
840          * @param nodeTypeResource
841          * @param nodeTypeArtifactsToHandle
842          * @param vfcsNewCreatedArtifacts
843          * @param user
844          * @param inTransaction
845          * @return
846          */
847         public Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifacts(Resource nodeTypeResource, Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle, List<ArtifactDefinition> vfcsNewCreatedArtifacts,
848                         User user, boolean inTransaction) {
849                 Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRequestRes;
850                 Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = null;
851                 Either<Resource, ResponseFormat> changeStateResponse;
852                 try {
853                         changeStateResponse = checkoutResource(nodeTypeResource, user, inTransaction);
854                         if (changeStateResponse.isRight()) {
855                                 return Either.right(changeStateResponse.right().value());
856                         }
857                         nodeTypeResource = changeStateResponse.left().value();
858
859                         List<ArtifactDefinition> handledNodeTypeArtifacts = new ArrayList<>();
860                         log.debug("************* Going to handle artifacts of node type resource {}. ", nodeTypeResource.getName());
861                         for (Entry<ArtifactOperationEnum, List<ArtifactDefinition>> curOperationEntry : nodeTypeArtifactsToHandle.entrySet()) {
862                                 ArtifactOperationEnum curOperation = curOperationEntry.getKey();
863                                 List<ArtifactDefinition> curArtifactsToHandle = curOperationEntry.getValue();
864                                 if (curArtifactsToHandle != null && !curArtifactsToHandle.isEmpty()) {
865                                         log.debug("************* Going to {} artifact to vfc {}", curOperation.name(), nodeTypeResource.getName());
866                                         handleNodeTypeArtifactsRequestRes = artifactsBusinessLogic.handleArtifactsRequestForInnerVfcComponent(curArtifactsToHandle, nodeTypeResource, user, vfcsNewCreatedArtifacts,
867                                                         artifactsBusinessLogic.new ArtifactOperationInfo(false, false, curOperation), false, inTransaction);
868                                         if (handleNodeTypeArtifactsRequestRes.isRight()) {
869                                                 handleNodeTypeArtifactsRes = Either.right(handleNodeTypeArtifactsRequestRes.right().value());
870                                                 break;
871                                         }
872                                         if (curOperation == ArtifactOperationEnum.Create) {
873                                                 vfcsNewCreatedArtifacts.addAll(handleNodeTypeArtifactsRequestRes.left().value());
874                                         }
875                                         handledNodeTypeArtifacts.addAll(handleNodeTypeArtifactsRequestRes.left().value());
876                                 }
877                         }
878                         if (handleNodeTypeArtifactsRes == null) {
879                                 handleNodeTypeArtifactsRes = Either.left(handledNodeTypeArtifacts);
880                         }
881                 } catch (Exception e) {
882                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
883                         handleNodeTypeArtifactsRes = Either.right(responseFormat);
884                         log.debug("Exception occured when handleVfcArtifacts, error is:{}", e.getMessage(), e);
885                 }
886                 return handleNodeTypeArtifactsRes;
887         }
888
889         @SuppressWarnings("unchecked")
890         private Map<String, String> extractVfcToscaNames(Map<String, NodeTypeInfo> nodeTypesInfo, String yamlFileName, String vfResourceName, Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap) {
891                 Map<String, String> vfcToscaNames = new HashMap<>();
892                         
893                 Map<String, Object> nodes = extractAllNodes(nodeTypesInfo);
894                 if (!nodes.isEmpty()) {
895                         Iterator<Entry<String, Object>> nodesNameEntry = nodes.entrySet().iterator();
896                         while (nodesNameEntry.hasNext()) {
897                                 Entry<String, Object> nodeType = nodesNameEntry.next();
898                                 String toscaResourceName = buildNodeToscaResourceName(vfResourceName, nodeType.getKey());
899                                 vfcToscaNames.put(nodeType.getKey(), toscaResourceName);
900                         }
901                 }
902                 return vfcToscaNames;
903         }
904
905         private Map<String, Object> extractAllNodes(Map<String, NodeTypeInfo> nodeTypesInfo) {
906                 Map<String, Object> nodes = new HashMap<>();
907                 for(NodeTypeInfo nodeTypeInfo: nodeTypesInfo.values()){
908                         Either<Map<String, Object>, ResultStatusEnum> eitherNodeTypes = ImportUtils.findFirstToscaMapElement(nodeTypeInfo.getMappedToscaTemplate(), ToscaTagNamesEnum.NODE_TYPES);
909                         if (eitherNodeTypes.isLeft()) {
910                                 nodes.putAll(eitherNodeTypes.left().value());
911                         }
912                 }
913                 return nodes;
914         }
915
916         @SuppressWarnings("unchecked")
917         private void putNodeTypesFromYaml(Map<String, byte[]> csar, String yamlFileName, Map<String, Object> nodeTypes) {
918
919                 if (csar.containsKey(yamlFileName)) {
920                         Map<String, Object> mappedToscaTemplate;
921                         Either<Map<String, Object>, ResultStatusEnum> eitherNodeTypes;
922                         mappedToscaTemplate = (Map<String, Object>) new Yaml().load(new String(csar.get(yamlFileName), StandardCharsets.UTF_8));
923                         eitherNodeTypes = ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TYPES);
924                         if (eitherNodeTypes.isLeft()) {
925                                 nodeTypes.putAll(eitherNodeTypes.left().value());
926                         }
927                 }
928         }
929
930         private void addSubstituteToscaNamespacesRecursively(Map<String, byte[]> csar, String yamlFileName, List<String> toscaNameSpaces, Map<String, String> nestedServiceTemplatesMap) {
931
932                 Map<String, Object> nodeTypes = new HashMap<>();
933
934                 if (csar.containsKey(yamlFileName)) {
935                         putNodeTypesFromYaml(csar, yamlFileName, nodeTypes);
936                 }
937                 if (!nodeTypes.isEmpty()) {
938                         Iterator<Entry<String, Object>> nodesNameEntry = nodeTypes.entrySet().iterator();
939                         while (nodesNameEntry.hasNext()) {
940                                 Entry<String, Object> nodeType = nodesNameEntry.next();
941                                 String nodeTypeFullName = nodeType.getKey();
942                                 String toscaNameSpace = buildNestedVfcToscaNamespace(nodeTypeFullName);
943                                 if (toscaNameSpaces.contains(toscaNameSpace)) {
944                                         break;
945                                 }
946                                 toscaNameSpaces.add(toscaNameSpace);
947
948                                 String nodeTypeTemplateYamlName = null;
949                                 if (nestedServiceTemplatesMap.containsKey(nodeTypeFullName)) {
950                                         nodeTypeTemplateYamlName = nestedServiceTemplatesMap.get(nodeTypeFullName);
951                                 }
952
953                                 if (nodeTypeTemplateYamlName != null && csar.containsKey(nodeTypeTemplateYamlName)) {
954                                         addSubstituteToscaNamespacesRecursively(csar, nodeTypeTemplateYamlName, toscaNameSpaces, nestedServiceTemplatesMap);
955                                 }
956                         }
957                 }
958         }
959
960         public Either<Resource, ResponseFormat> createResourceFromCsar(Resource resource, User user, Either<Map<String, byte[]>, StorageOperationStatus> csarUIPayload, String csarUUID) {
961                 log.trace("************* created successfully from YAML, resource TOSCA ");
962
963                 Either<Map<String, byte[]>, StorageOperationStatus> csar = null;
964                 if (csarUIPayload != null && csarUIPayload.left() != null && csarUIPayload.left().value() != null) {
965                         csar = csarUIPayload;
966                 } else {
967                         csar = csarOperation.getCsar(csarUUID, user);
968                 }
969
970                 Either<ImmutablePair<String, String>, ResponseFormat> toscaYamlCsarStatus = validateAndParseCsar(resource, user, csarUUID, csar);
971                 if (toscaYamlCsarStatus.isRight()) {
972                         return Either.right(toscaYamlCsarStatus.right().value());
973                 }
974                 Either<String, ResponseFormat> toscaYamlChecksum = CsarValidationUtils.getToscaYamlChecksum(csar.left().value(), csarUUID, componentsUtils);
975                 if (toscaYamlChecksum.isRight()) {
976                         log.debug("Failed to calculate checksum for CSAR {}, error  {}", csarUUID, toscaYamlChecksum.right().value());
977                         return Either.right(toscaYamlChecksum.right().value());
978                 }
979                 resource.getComponentMetadataDefinition().getMetadataDataDefinition().setImportedToscaChecksum(toscaYamlChecksum.left().value());
980
981                 String yamlFileName = toscaYamlCsarStatus.left().value().getKey();
982                 String yamlFileContents = toscaYamlCsarStatus.left().value().getValue();
983                 log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContents);
984
985                 Map<String, NodeTypeInfo> nodeTypesInfo = extractNodeTypesInfo(csar.left().value(), yamlFileContents);
986                 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate = findNodeTypeArtifactsToCreate(csar.left().value(), resource);
987                 ImportCsarInfo importCsarInfo = new ImportCsarInfo(resource.getName(), user, csarUUID, csar.left().value());
988                 Either<Resource, ResponseFormat> createResourceFromYaml = createResourceFromYaml(resource, yamlFileContents, yamlFileName, nodeTypesInfo, importCsarInfo, nodeTypesArtifactsToCreate, true, false, null);
989                 if (createResourceFromYaml.isRight()) {
990                         log.debug("Couldn't create resource from YAML");
991                         return Either.right(createResourceFromYaml.right().value());
992                 }
993
994                 Resource vfResource = createResourceFromYaml.left().value();
995                 log.trace("*************VF Resource created successfully from YAML, resource TOSCA name: {}", vfResource.getToscaResourceName());
996                 return Either.left(vfResource);
997         }
998
999         @SuppressWarnings("unchecked")
1000         private Map<String, NodeTypeInfo> extractNodeTypesInfo(Map<String, byte[]> csar, String yamlFileContent) {
1001                 Map<String, NodeTypeInfo> nodeTypesInfo = new HashMap<>();
1002                 List<Entry<String, byte[]>> globalSubstitutes = new ArrayList<>();
1003                 for (Map.Entry<String, byte[]> entry : csar.entrySet()) {
1004                         if (Pattern.compile(CsarUtils.SERVICE_TEMPLATE_PATH_PATTERN).matcher(entry.getKey()).matches()) {
1005                                 if (!isGlobalSubstitute(entry.getKey())) {
1006                                         String yamlFileContents = new String(entry.getValue());
1007                                         Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(yamlFileContents);
1008                                         Either<Object, ResultStatusEnum> substitutionMappingsEither = ImportUtils.findToscaElement(mappedToscaTemplate, ToscaTagNamesEnum.SUBSTITUTION_MAPPINGS, ToscaElementTypeEnum.MAP);
1009                                         if (substitutionMappingsEither.isLeft()) {
1010                                                 Map<String, Object> substitutionMappings = (Map<String, Object>) substitutionMappingsEither.left().value();
1011                                                 if (substitutionMappings.containsKey(ToscaTagNamesEnum.NODE_TYPE.getElementName())) {
1012                                                         NodeTypeInfo nodeTypeInfo = new NodeTypeInfo();
1013                                                         nodeTypeInfo.setType((String) substitutionMappings.get(ToscaTagNamesEnum.NODE_TYPE.getElementName()));
1014                                                         nodeTypeInfo.setTemplateFileName(entry.getKey());
1015                                                         nodeTypeInfo.setMappedToscaTemplate(mappedToscaTemplate);
1016                                                         nodeTypesInfo.put(nodeTypeInfo.getType(), nodeTypeInfo);
1017                                                 }
1018                                         }
1019                                 } else {
1020                                         globalSubstitutes.add(entry);
1021                                 }
1022                         }
1023                 }
1024                 if (CollectionUtils.isNotEmpty(globalSubstitutes)) {
1025                         for (Map.Entry<String, byte[]> entry : globalSubstitutes) {
1026                                 String yamlFileContents = new String(entry.getValue());
1027                                 Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(yamlFileContents);
1028                                 Either<Object, ResultStatusEnum> nodeTypesEither = ImportUtils.findToscaElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TYPES, ToscaElementTypeEnum.MAP);
1029                                 if (nodeTypesEither.isLeft()) {
1030                                         Map<String, Object> nodeTypes = (Map<String, Object>) nodeTypesEither.left().value();
1031                                         for (Entry<String, Object> nodeType : nodeTypes.entrySet()) {
1032                                                 Map<String, Object> nodeTypeMap = (Map<String, Object>) nodeType.getValue();
1033                                                 if (nodeTypeMap.containsKey(ToscaTagNamesEnum.DERIVED_FROM.getElementName())) {
1034                                                         if (nodeTypesInfo.containsKey(nodeType.getKey())) {
1035                                                                 NodeTypeInfo nodeTypeInfo = nodeTypesInfo.get(nodeType.getKey());
1036                                                                 List<String> derivedFrom = new ArrayList<>();
1037                                                                 derivedFrom.add((String) nodeTypeMap.get(ToscaTagNamesEnum.DERIVED_FROM.getElementName()));
1038                                                                 nodeTypeInfo.setDerivedFrom(derivedFrom);
1039                                                         }
1040                                                 }
1041                                         }
1042                                 }
1043                         }
1044                 }
1045                 markNestedVfc(yamlFileContent, nodeTypesInfo);
1046                 return nodeTypesInfo;
1047         }
1048
1049         private void markNestedVfc(String yamlFileContent, Map<String, NodeTypeInfo> nodeTypesInfo) {
1050                 Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(yamlFileContent);
1051                 Either<Object, ResultStatusEnum> nodeTemplatesEither = ImportUtils.findToscaElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TEMPLATES, ToscaElementTypeEnum.MAP);
1052                 if (nodeTemplatesEither.isLeft()) {
1053                         Map<String, Object> nodeTemplates = (Map<String, Object>) nodeTemplatesEither.left().value();
1054                         for (Entry<String, Object> nodeTemplateEntry : nodeTemplates.entrySet()) {
1055                                 Map<String, Object> nodeTemplate = (Map<String, Object>) nodeTemplateEntry.getValue();
1056                                 if (nodeTemplate.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) {
1057                                         String type = (String) nodeTemplate.get(ToscaTagNamesEnum.TYPE.getElementName());
1058                                         if (nodeTypesInfo.containsKey(type)) {
1059                                                 NodeTypeInfo nodeTypeInfo = nodeTypesInfo.get(type);
1060                                                 nodeTypeInfo.setNested(true);
1061                                         }
1062                                 }
1063                         }
1064                 }
1065         }
1066
1067         private boolean isGlobalSubstitute(String fileName) {
1068                 return fileName.equalsIgnoreCase(Constants.GLOBAL_SUBSTITUTION_TYPES_SERVICE_TEMPLATE) || fileName.equalsIgnoreCase(Constants.ABSTRACT_SUBSTITUTE_GLOBAL_TYPES_SERVICE_TEMPLATE);
1069         }
1070
1071         private Either<ImmutablePair<String, String>, ResponseFormat> validateAndParseCsar(Resource resource, User user, String csarUUID, Either<Map<String, byte[]>, StorageOperationStatus> csar) {
1072                 if (csar.isRight()) {
1073                         StorageOperationStatus value = csar.right().value();
1074                         log.debug("Error when fetching csar with ID {}, error: {}", csarUUID, value);
1075                         BeEcompErrorManager.getInstance().logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed");
1076                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(value), csarUUID);
1077                         componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.CREATE_RESOURCE, null);
1078                         return Either.right(responseFormat);
1079                 }
1080
1081                 Either<Boolean, ResponseFormat> validateCsarStatus = CsarValidationUtils.validateCsar(csar.left().value(), csarUUID, componentsUtils);
1082                 if (validateCsarStatus.isRight()) {
1083                         ResponseFormat responseFormat = validateCsarStatus.right().value();
1084                         log.debug("Error when validate csar with ID {}, error: {}", csarUUID, responseFormat);
1085                         BeEcompErrorManager.getInstance().logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed");
1086                         componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.CREATE_RESOURCE, null);
1087                         return Either.right(responseFormat);
1088                 }
1089
1090                 Either<ImmutablePair<String, String>, ResponseFormat> toscaYamlCsarStatus = CsarValidationUtils.getToscaYaml(csar.left().value(), csarUUID, componentsUtils);
1091
1092                 if (toscaYamlCsarStatus.isRight()) {
1093                         ResponseFormat responseFormat = toscaYamlCsarStatus.right().value();
1094                         log.debug("Error when try to get csar toscayamlFile with csar ID {}, error: {}", csarUUID, responseFormat);
1095                         BeEcompErrorManager.getInstance().logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed");
1096                         componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.CREATE_RESOURCE, null);
1097                         return Either.right(responseFormat);
1098                 }
1099                 return toscaYamlCsarStatus;
1100         }
1101
1102         private Either<Resource, ResponseFormat> validateResourceBeforeCreate(Resource resource, User user, boolean inTransaction) {
1103                 log.trace("validating resource before create");
1104                 Either<User, ResponseFormat> eitherCreator = validateUser(user, "Create Resource", resource, AuditingActionEnum.CREATE_RESOURCE, false);
1105                 if (eitherCreator.isRight()) {
1106                         return Either.right(eitherCreator.right().value());
1107                 }
1108                 user.copyData(eitherCreator.left().value());
1109
1110                 // validate user role
1111                 Either<Boolean, ResponseFormat> validateRes = validateUserRole(user, resource, new ArrayList<Role>(), AuditingActionEnum.CREATE_RESOURCE, null);
1112                 if (validateRes.isRight()) {
1113                         return Either.right(validateRes.right().value());
1114                 }
1115                 // VF / PNF "derivedFrom" should be null (or ignored)
1116                 if (ToscaUtils.isAtomicType(resource)) {
1117                         Either<Boolean, ResponseFormat> validateDerivedFromNotEmpty = validateDerivedFromNotEmpty(user, resource, AuditingActionEnum.CREATE_RESOURCE);
1118                         if (validateDerivedFromNotEmpty.isRight()) {
1119                                 return Either.right(validateDerivedFromNotEmpty.right().value());
1120                         }
1121                 }
1122                 return validateResourceBeforeCreate(resource, user, AuditingActionEnum.CREATE_RESOURCE, inTransaction);
1123
1124         }
1125 //resource, yamlFileContents, yamlFileName, nodeTypesInfo,importCsarInfo, nodeTypesArtifactsToCreate, true, false, null
1126         private Either<Resource, ResponseFormat> createResourceFromYaml(Resource resource, String topologyTemplateYaml, String yamlName,
1127                         Map<String, NodeTypeInfo> nodeTypesInfo, ImportCsarInfo importCsarInfo,
1128                         Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
1129                         boolean shouldLock, boolean inTransaction, String nodeTypeName) {
1130
1131                 List<ArtifactDefinition> createdArtifacts = new ArrayList<ArtifactDefinition>();
1132                 log.trace("************* createResourceFromYaml before parse yaml ");
1133                 Either<ParsedToscaYamlInfo, ResponseFormat> parseResourceInfoFromYamlEither = parseResourceInfoFromYaml(yamlName, resource, topologyTemplateYaml, importCsarInfo.getModifier(), importCsarInfo.getCreatedNodesToscaResourceNames(), nodeTypesInfo, nodeTypeName);
1134                 if (parseResourceInfoFromYamlEither.isRight()) {
1135                         ResponseFormat responseFormat = parseResourceInfoFromYamlEither.right().value();
1136                         componentsUtils.auditResource(responseFormat, importCsarInfo.getModifier(), resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
1137                         return Either.right(responseFormat);
1138                 }
1139                 log.trace("************* createResourceFromYaml after parse yaml ");
1140                 ParsedToscaYamlInfo parsedToscaYamlInfo = parseResourceInfoFromYamlEither.left().value();
1141                 log.debug("The parsed tosca yaml info is {}", parsedToscaYamlInfo);
1142                 log.trace("************* createResourceFromYaml before create ");
1143                 Either<Resource, ResponseFormat> createdResourceResponse = createResourceAndRIsFromYaml(yamlName, resource, parsedToscaYamlInfo, 
1144                                 AuditingActionEnum.IMPORT_RESOURCE, false, createdArtifacts, topologyTemplateYaml,
1145                                 nodeTypesInfo, importCsarInfo, nodeTypesArtifactsToCreate, shouldLock, inTransaction, nodeTypeName);
1146                 log.trace("************* createResourceFromYaml after create ");
1147                 if (createdResourceResponse.isRight()) {
1148                         ResponseFormat responseFormat = createdResourceResponse.right().value();
1149                         componentsUtils.auditResource(responseFormat, importCsarInfo.getModifier(), resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
1150                         return Either.right(responseFormat);
1151                 }
1152
1153                 return createdResourceResponse;
1154
1155         }
1156
1157         @SuppressWarnings("unchecked")
1158         public Either<Map<String, Resource>, ResponseFormat> createResourcesFromYamlNodeTypesList(String yamlName, Resource resource, String resourceYml, Map<String, Object> mappedToscaTemplate, boolean needLock,
1159                                                                                                                                                                                           Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
1160                                                                                                                                                                                           Map<String, NodeTypeInfo> nodeTypesInfo, ImportCsarInfo importCsarInfo) {
1161
1162                 Either<String, ResultStatusEnum> tosca_version = ImportUtils.findFirstToscaStringElement(mappedToscaTemplate, ToscaTagNamesEnum.TOSCA_VERSION);
1163                 if (tosca_version.isRight()) {
1164                         ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE);
1165                         return Either.right(responseFormat);
1166                 }
1167                 Either<Map<String, Object>, ResultStatusEnum> eitherNodeTypes = ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TYPES);
1168                 Map<String, Resource> nodeTypesResources = new HashMap<>();
1169                 Either<Map<String, Resource>, ResponseFormat> result = Either.left(nodeTypesResources);
1170                 Map<String, Object> mapToConvert = new HashMap<String, Object>();
1171                 mapToConvert.put(ToscaTagNamesEnum.TOSCA_VERSION.getElementName(), tosca_version.left().value());
1172                 Resource vfcCreated = null;
1173                 if (eitherNodeTypes.isLeft()) {
1174                         Iterator<Entry<String, Object>> nodesNameValue = eitherNodeTypes.left().value().entrySet().iterator();
1175                         while (nodesNameValue.hasNext()) {
1176                                 Entry<String, Object> nodeType = nodesNameValue.next();
1177                                 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = nodeTypesArtifactsToHandle == null || nodeTypesArtifactsToHandle.isEmpty() ? null : nodeTypesArtifactsToHandle.get(nodeType.getKey());
1178
1179                                 if (nodeTypesInfo.containsKey(nodeType.getKey())) {
1180                                         log.trace("************* Going to handle nested vfc {}", nodeType.getKey());
1181                                         Either<Resource, ResponseFormat> handleNeatedVfcYaml = handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, importCsarInfo, nodeType.getKey(), nodeTypesResources);
1182                                         log.trace("************* Finished to handle nested vfc {}", nodeType.getKey());
1183                                         if (handleNeatedVfcYaml.isRight()) {
1184                                                 return Either.right(handleNeatedVfcYaml.right().value());
1185                                         }
1186                                         vfcCreated = handleNeatedVfcYaml.left().value();
1187                                 } else if(importCsarInfo.getCreatedNodesToscaResourceNames()!= null && !importCsarInfo.getCreatedNodesToscaResourceNames().containsKey(nodeType.getKey())){
1188                                         log.trace("************* Going to create node {}", nodeType.getKey());
1189                                         Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> resourceCreated = this.createNodeTypeResourceFromYaml(yamlName, nodeType, importCsarInfo.getModifier(), mapToConvert, resource, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, true);
1190                                         log.debug("************* Finished to create node {}", nodeType.getKey());
1191
1192                                         if (resourceCreated.isRight()) {
1193                                                 return Either.right(resourceCreated.right().value());
1194                                         }
1195                                         vfcCreated = resourceCreated.left().value().getLeft();
1196                                         importCsarInfo.getCreatedNodesToscaResourceNames().put(nodeType.getKey(),vfcCreated.getToscaResourceName());
1197                                 }
1198                                 if (vfcCreated != null) {
1199                                         nodeTypesResources.put(nodeType.getKey(), vfcCreated);
1200                                 }
1201                                 mapToConvert.remove(ToscaTagNamesEnum.NODE_TYPES.getElementName());
1202                         }
1203                 }
1204                 return result;
1205         }
1206
1207         private Either<Resource, ResponseFormat> handleNestedVfc(Resource resource, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
1208                         List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo, ImportCsarInfo importCsarInfo,
1209                         String nodeType, Map<String, Resource> createdResourcesFromdNodeTypeMap) {
1210
1211                 Either<Resource, ResponseFormat> handleNestedVfcRes = Either.left(resource);
1212                 String serviceTemplateFileFullName = nodeTypesInfo.get(nodeType).getTemplateFileName();
1213                 String serviceTemplateFileContent =  new String(importCsarInfo.getCsar().get(serviceTemplateFileFullName));
1214                 Map<String, Object> nestedVfcJsonMap = nodeTypesInfo.get(nodeType).getMappedToscaTemplate();
1215
1216                 Either<Map<String, Resource>, ResponseFormat> createdResourcesFromdNodeTypeMapEither =  createResourcesFromYamlNodeTypesList(serviceTemplateFileFullName, resource, serviceTemplateFileContent, 
1217                                                 nestedVfcJsonMap, false, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, importCsarInfo);
1218                 log.debug("************* Finished to create all nodes from yaml {}", serviceTemplateFileFullName);
1219                 if (createdResourcesFromdNodeTypeMapEither.isRight()) {
1220                         log.debug("failed to resources from node types status is {}", createdResourcesFromdNodeTypeMapEither.right().value());
1221                         return Either.right(createdResourcesFromdNodeTypeMapEither.right().value());
1222                 }
1223                 createdResourcesFromdNodeTypeMap.putAll(createdResourcesFromdNodeTypeMapEither.left().value());
1224
1225                 if (nestedVfcJsonMap.containsKey(ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) {
1226                         Resource complexVfc = new Resource();
1227                         fillComplexVfcMetadata(resource, importCsarInfo, complexVfc, nodeType, nodeTypesInfo, false);
1228                         if(!importCsarInfo.getCvfcToCreateQueue().contains(nodeType)){
1229                                 importCsarInfo.getCvfcToCreateQueue().add(nodeType);
1230                         } else {
1231                                 log.debug("CFVC LOOP DETECTED, VSP {}, CVFC {}", importCsarInfo.getVfResourceName(), complexVfc.getName());
1232                                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.CFVC_LOOP_DETECTED, importCsarInfo.getVfResourceName(), complexVfc.getName()));
1233                         }
1234                         Either<Resource, ResponseFormat> validationRes = validateResourceBeforeCreate(complexVfc, importCsarInfo.getModifier(), AuditingActionEnum.IMPORT_RESOURCE, true);
1235                         if(validationRes.isRight()){
1236                                 log.debug("Failed to validate complex VFC {}. ", complexVfc.getName());
1237                                 return validationRes;
1238                         }
1239                         Map<String, NodeTypeInfo> newNodeTypesInfo = nodeTypesInfo.entrySet().stream().collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue().getUnmarkedCopy()));
1240                         markNestedVfc(serviceTemplateFileContent, newNodeTypesInfo);
1241                         handleNestedVfcRes = createResourceFromYaml(complexVfc, serviceTemplateFileContent, serviceTemplateFileFullName,
1242                                         newNodeTypesInfo, importCsarInfo, nodeTypesArtifactsToHandle, false, true, nodeType);
1243                         if (handleNestedVfcRes.isRight()) {
1244                                 log.debug("Couldn't create resource from YAML");
1245                                 return Either.right(handleNestedVfcRes.right().value());
1246                         }
1247                         importCsarInfo.getCreatedNodesToscaResourceNames().put(nodeType, handleNestedVfcRes.left().value().getToscaResourceName());
1248                         LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction("certification on import", LifecycleChanceActionEnum.CREATE_FROM_CSAR);
1249                         log.debug("Going to certify cvfc {}. ", handleNestedVfcRes.left().value().getName());
1250                         Either<Resource, ResponseFormat> certRes = propagateStateToCertified(importCsarInfo.getModifier(),  handleNestedVfcRes.left().value(), lifecycleChangeInfo, true, false, true);
1251                         if (certRes.isRight()) {
1252                                 log.debug("Couldn't certify resource {}. ", handleNestedVfcRes.left().value());
1253                                 return certRes;
1254                         }
1255                         createdResourcesFromdNodeTypeMap.put(nodeType, certRes.left().value());
1256                         importCsarInfo.getCvfcToCreateQueue().remove();
1257                 }
1258
1259                 return handleNestedVfcRes;
1260         }
1261
1262         private String getNodeTypeActualName(String fullName) {
1263                 String nameWithouNamespacePrefix = fullName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1264                 String[] findTypes = nameWithouNamespacePrefix.split("\\.");
1265                 String resourceType = findTypes[0];
1266                 return nameWithouNamespacePrefix.substring(resourceType.length());
1267         }
1268
1269         private Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createNodeTypeResourceFromYaml(String yamlName, Entry<String, Object> nodeNameValue, User user, Map<String, Object> mapToConvert, Resource resourceVf, boolean needLock,
1270                         Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed) {
1271
1272                 Either<UploadResourceInfo, ResponseFormat> resourceMetaData = fillResourceMetadata(yamlName, resourceVf, nodeNameValue.getKey(), user);
1273                 if (resourceMetaData.isRight()) {
1274                         return Either.right(resourceMetaData.right().value());
1275                 }
1276                 String csarVfName = resourceVf.getSystemName();
1277                 String singleVfcYaml = buildNodeTypeYaml(nodeNameValue, mapToConvert, resourceMetaData.left().value().getResourceType(), csarVfName);
1278
1279                 Either<User, ResponseFormat> eitherCreator = validateUser(user, "CheckIn Resource", resourceVf, AuditingActionEnum.CHECKIN_RESOURCE, true);
1280                 if (eitherCreator.isRight()) {
1281                         return Either.right(eitherCreator.right().value());
1282                 }
1283                 user = eitherCreator.left().value();
1284
1285                 return this.createResourceFromNodeType(singleVfcYaml, resourceMetaData.left().value(), user, true, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed);
1286         }
1287
1288         private String buildNodeTypeYaml(Entry<String, Object> nodeNameValue, Map<String, Object> mapToConvert, String nodeResourceType, String csarVfName) {
1289                 // We need to create a Yaml from each node_types in order to create
1290                 // resource from each node type using import normative flow.
1291                 DumperOptions options = new DumperOptions();
1292                 options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
1293                 Yaml yaml = new Yaml(options);
1294
1295                 Map<String, Object> node = new HashMap<>();
1296                 node.put(buildNestedToscaResourceName(nodeResourceType, csarVfName, nodeNameValue.getKey()), nodeNameValue.getValue());
1297                 mapToConvert.put(ToscaTagNamesEnum.NODE_TYPES.getElementName(), node);
1298
1299                 return yaml.dumpAsMap(mapToConvert);
1300         }
1301
1302         private String buildNestedToscaResourceName(String nodeResourceType, String csarVfName, String originToscaResourceName) {
1303                 String actualName = getNodeTypeActualName(originToscaResourceName);
1304                 if (!actualName.startsWith(Constants.ABSTRACT)) {
1305                         actualName = "." + Constants.ABSTRACT + actualName;
1306                 }
1307                 return ImportUtils.Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + nodeResourceType.toLowerCase() + '.' + ValidationUtils.convertToSystemName(csarVfName) + actualName;
1308         }
1309
1310         public Either<Boolean, ResponseFormat> validateResourceCreationFromNodeType(Resource resource, User creator) {
1311
1312                 Either<Boolean, ResponseFormat> validateDerivedFromNotEmpty = this.validateDerivedFromNotEmpty(creator, resource, AuditingActionEnum.CREATE_RESOURCE);
1313                 if (validateDerivedFromNotEmpty.isRight()) {
1314                         return Either.right(validateDerivedFromNotEmpty.right().value());
1315                 }
1316                 return Either.left(true);
1317         }
1318
1319         public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createResourceFromNodeType(String nodeTypeYaml, UploadResourceInfo resourceMetaData, User creator, boolean isInTransaction, boolean needLock,
1320                         Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed) {
1321
1322                 LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction("certification on import", LifecycleChanceActionEnum.CREATE_FROM_CSAR);
1323                 Function<Resource, Either<Boolean, ResponseFormat>> validator = (resource) -> this.validateResourceCreationFromNodeType(resource, creator);
1324                 return this.resourceImportManager.importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator, lifecycleChangeInfo, isInTransaction, true, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed);
1325         }
1326
1327         private Either<UploadResourceInfo, ResponseFormat> fillResourceMetadata(String yamlName, Resource resourceVf, String nodeTypeName, User user) {
1328                 UploadResourceInfo resourceMetaData = new UploadResourceInfo();
1329
1330                 // validate nodetype name prefix
1331                 if (!nodeTypeName.startsWith(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX)) {
1332                         log.debug("invalid nodeTypeName:{} does not start with {}.", nodeTypeName, Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
1333                         ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, resourceMetaData.getName(), nodeTypeName);
1334                         return Either.right(responseFormat);
1335                 }
1336
1337                 String actualName = this.getNodeTypeActualName(nodeTypeName);
1338                 String namePrefix = nodeTypeName.replace(actualName, "");
1339                 String resourceType = namePrefix.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1340
1341                 // if we import from csar, the node_type name can be
1342                 // org.openecomp.resource.abstract.node_name - in this case we always
1343                 // create a vfc
1344                 if (resourceType.equals(Constants.ABSTRACT)) {
1345                         resourceType = ResourceTypeEnum.VFC.name().toLowerCase();
1346                 }
1347                 // validating type
1348                 if (!ResourceTypeEnum.containsName(resourceType.toUpperCase())) {
1349                         log.debug("invalid resourceType:{} the type is not one of the valide types:{}.", resourceType.toUpperCase(), ResourceTypeEnum.values());
1350                         ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, resourceMetaData.getName(), nodeTypeName);
1351                         return Either.right(responseFormat);
1352                 }
1353
1354                 // Setting name
1355                 resourceMetaData.setName(resourceVf.getSystemName() + actualName);
1356
1357                 // Setting type from name
1358                 String type = resourceType.toUpperCase();
1359                 resourceMetaData.setResourceType(type);
1360
1361                 resourceMetaData.setDescription(ImportUtils.Constants.INNER_VFC_DESCRIPTION);
1362                 resourceMetaData.setIcon(ImportUtils.Constants.DEFAULT_ICON);
1363                 resourceMetaData.setContactId(user.getUserId());
1364                 resourceMetaData.setVendorName(resourceVf.getVendorName());
1365                 resourceMetaData.setVendorRelease(resourceVf.getVendorRelease());
1366
1367                 // Setting tag
1368                 List<String> tags = new ArrayList<>();
1369                 tags.add(resourceMetaData.getName());
1370                 resourceMetaData.setTags(tags);
1371
1372                 // Setting category
1373                 CategoryDefinition category = new CategoryDefinition();
1374                 category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
1375                 SubCategoryDefinition subCategory = new SubCategoryDefinition();
1376                 subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
1377                 category.addSubCategory(subCategory);
1378                 List<CategoryDefinition> categories = new ArrayList<>();
1379                 categories.add(category);
1380                 resourceMetaData.setCategories(categories);
1381
1382                 return Either.left(resourceMetaData);
1383         }
1384
1385         private void fillComplexVfcMetadata(Resource resourceVf, ImportCsarInfo importCsarInfo, Resource cvfc, String nodeTypeName, Map<String, NodeTypeInfo> nodeTypesInfo, boolean shouldBeCertified) {
1386                 NodeTypeInfo nodeTypeInfo = nodeTypesInfo.get(nodeTypeName);
1387                 cvfc.setName(buildCvfcName(importCsarInfo.getVfResourceName(), nodeTypeName));
1388                 cvfc.setNormalizedName(ValidationUtils.normaliseComponentName(cvfc.getName()));
1389                 cvfc.setSystemName(ValidationUtils.convertToSystemName(cvfc.getName()));
1390                 cvfc.setResourceType(ResourceTypeEnum.CVFC);
1391                 cvfc.setAbstract(true);
1392                 cvfc.setDerivedFrom(nodeTypeInfo.getDerivedFrom());
1393                 cvfc.setDescription(ImportUtils.Constants.CVFC_DESCRIPTION);
1394                 cvfc.setIcon(ImportUtils.Constants.DEFAULT_ICON);
1395                 cvfc.setContactId(importCsarInfo.getModifier().getUserId());
1396                 cvfc.setCreatorUserId(importCsarInfo.getModifier().getUserId());
1397                 cvfc.setVendorName(resourceVf.getVendorName());
1398                 cvfc.setVendorRelease(resourceVf.getVendorRelease());
1399                 cvfc.setResourceVendorModelNumber(resourceVf.getResourceVendorModelNumber());
1400                 cvfc.setToscaResourceName(buildNestedToscaResourceName(ResourceTypeEnum.VFC.name(), importCsarInfo.getVfResourceName(), nodeTypeName));
1401                 cvfc.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID());
1402                 
1403                 List<String> tags = new ArrayList<>();
1404                 tags.add(cvfc.getName());
1405                 cvfc.setTags(tags);
1406
1407                 CategoryDefinition category = new CategoryDefinition();
1408                 category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
1409                 SubCategoryDefinition subCategory = new SubCategoryDefinition();
1410                 subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
1411                 category.addSubCategory(subCategory);
1412                 List<CategoryDefinition> categories = new ArrayList<>();
1413                 categories.add(category);
1414                 cvfc.setCategories(categories);
1415
1416                 String version;
1417                 LifecycleStateEnum state;
1418
1419                 if (shouldBeCertified) {
1420                         version = ImportUtils.Constants.FIRST_CERTIFIED_VERSION_VERSION;
1421                         state = ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE;
1422                 } else {
1423                         version = ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION;
1424                         state = ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT;
1425                 }
1426                 cvfc.setVersion(version);
1427                 cvfc.setLifecycleState(state);
1428                 cvfc.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION);
1429         }
1430
1431         private String buildCvfcName(String resourceVfName, String nodeTypeName) {
1432                 String nameWithouNamespacePrefix = nodeTypeName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1433                 String[] findTypes = nameWithouNamespacePrefix.split("\\.");
1434                 String resourceType = findTypes[0];
1435                 return resourceVfName + "-" + nameWithouNamespacePrefix.substring(resourceType.length() + 1);
1436         }
1437
1438         private Either<Resource, ResponseFormat> createResourceAndRIsFromYaml(String yamlName, Resource resource, ParsedToscaYamlInfo parsedToscaYamlInfo, AuditingActionEnum actionEnum, boolean isNormative,
1439                                                                                                                                                   List<ArtifactDefinition> createdArtifacts, String topologyTemplateYaml, Map<String, NodeTypeInfo> nodeTypesInfo,
1440                                                                                                                                                   ImportCsarInfo importCsarInfo, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
1441                                                                                                                                                   boolean shouldLock, boolean inTransaction, String nodeTypeName) {
1442
1443                 boolean result = true;
1444                 Map<String, Resource> createdVfcs = new HashMap<>();
1445                 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>();
1446
1447                 if (shouldLock) {
1448                         Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource, "Create Resource");
1449                         if (lockResult.isRight()) {
1450                                 ResponseFormat responseFormat = lockResult.right().value();
1451                                 return Either.right(responseFormat);
1452                         }
1453                         log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
1454                 }
1455                 try {
1456                         log.trace("************* createResourceFromYaml before full create resource {}", yamlName);
1457                         Either<Resource, ResponseFormat> genericResourceEither = fetchAndSetDerivedFromGenericType(resource);
1458                         if (genericResourceEither.isRight()) {
1459                                 result = false;
1460                                 return genericResourceEither;
1461                         }
1462                         Either<Resource, ResponseFormat> createResourcesEither = createResourceTransaction(resource, importCsarInfo.getModifier(), isNormative, inTransaction);
1463                         log.trace("************* createResourceFromYaml after full create resource {}", yamlName);
1464                         if (createResourcesEither.isRight()) {
1465                                 result = false;
1466                                 return createResourcesEither;
1467                         }
1468                         resource = createResourcesEither.left().value();
1469                         // add groups to resource
1470                         log.trace("************* Going to add inputs from yaml {}", yamlName);
1471                         if (resource.shouldGenerateInputs())
1472                                 generateInputsFromGenericTypeProperties(resource, genericResourceEither.left().value());
1473
1474                         Map<String, InputDefinition> inputs = parsedToscaYamlInfo.getInputs();
1475                         Either<Resource, ResponseFormat> createInputsOnResource = createInputsOnResource(resource, importCsarInfo.getModifier(), inputs, inTransaction);
1476                         if (createInputsOnResource.isRight()) {
1477                                 result = false;
1478                                 return createInputsOnResource;
1479                         }
1480                         resource = createInputsOnResource.left().value();
1481                         log.trace("************* Finish to add inputs from yaml {}", yamlName);
1482
1483                         Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap = parsedToscaYamlInfo.getInstances();
1484                         log.trace("************* Going to create nodes, RI's and Relations  from yaml {}", yamlName);
1485
1486                         createResourcesEither = createRIAndRelationsFromYaml(yamlName, resource, uploadComponentInstanceInfoMap, actionEnum, topologyTemplateYaml,
1487                                         nodeTypesNewCreatedArtifacts, createdVfcs, nodeTypesInfo, importCsarInfo, nodeTypesArtifactsToCreate);
1488                         log.trace("************* Finished to create nodes, RI and Relation  from yaml {}", yamlName);
1489                         if (createResourcesEither.isRight()) {
1490                                 result = false;
1491                                 return createResourcesEither;
1492                         }
1493
1494                         resource = createResourcesEither.left().value();
1495                         // validate update vf module group names
1496                         Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic.validateUpdateVfGroupNames(parsedToscaYamlInfo.getGroups(), resource.getSystemName());
1497                         if (validateUpdateVfGroupNamesRes.isRight()) {
1498                                 result = false;
1499                                 return Either.right(validateUpdateVfGroupNamesRes.right().value());
1500                         }
1501                         // add groups to resource
1502                         Map<String, GroupDefinition> groups;
1503                         log.trace("************* Going to add groups from yaml {}", yamlName);
1504
1505                         if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
1506                                 groups = validateUpdateVfGroupNamesRes.left().value();
1507                         } else {
1508                                 groups = parsedToscaYamlInfo.getGroups();
1509                         }
1510                         Either<Resource, ResponseFormat> createGroupsOnResource = createGroupsOnResource(resource, importCsarInfo.getModifier(), groups);
1511                         if (createGroupsOnResource.isRight()) {
1512                                 result = false;
1513                                 return createGroupsOnResource;
1514                         }
1515                         resource = createGroupsOnResource.left().value();
1516                         log.trace("************* Finished to add groups from yaml {}", yamlName);
1517
1518                         log.trace("************* Going to add artifacts from yaml {}", yamlName);
1519
1520                         if(resource.getResourceType() == ResourceTypeEnum.CVFC){
1521                                 if(nodeTypesArtifactsToCreate.containsKey(nodeTypeName) && nodeTypesArtifactsToCreate.get(nodeTypeName) !=null && !nodeTypesArtifactsToCreate.get(nodeTypeName).isEmpty()){
1522                                         Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = 
1523                                                         handleNodeTypeArtifacts(resource, nodeTypesArtifactsToCreate.get(nodeTypeName), nodeTypesNewCreatedArtifacts, importCsarInfo.getModifier(), true);
1524                                         if(handleNodeTypeArtifactsRes.isRight()){
1525                                                 return Either.right(handleNodeTypeArtifactsRes.right().value());
1526                                         }
1527                                 }
1528                         } else {
1529                                 Either<Resource, ResponseFormat> createdCsarArtifactsEither = this.handleVfCsarArtifacts(resource, importCsarInfo, createdArtifacts, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create), false,
1530                                                 inTransaction);
1531                                 log.trace("************* Finished to add artifacts from yaml {}", yamlName);
1532                                 if (createdCsarArtifactsEither.isRight()) {
1533                                         result = false;
1534                                         return createdCsarArtifactsEither;
1535                                 }
1536                                 resource = createdCsarArtifactsEither.left().value();
1537                         }
1538                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
1539                         componentsUtils.auditResource(responseFormat, importCsarInfo.getModifier(), resource, "", "", actionEnum, null);
1540                         ASDCKpiApi.countCreatedResourcesKPI();
1541                         return Either.left(resource);
1542
1543                 } finally {
1544                         if (!inTransaction) {
1545                                 if (!result) {
1546                                         log.warn("operation failed. do rollback");
1547                                         titanDao.rollback();
1548                                         if (!createdArtifacts.isEmpty() || !nodeTypesNewCreatedArtifacts.isEmpty()) {
1549                                                 createdArtifacts.addAll(nodeTypesNewCreatedArtifacts);
1550                                                 StorageOperationStatus deleteFromEsRes = artifactsBusinessLogic.deleteAllComponentArtifactsIfNotOnGraph(createdArtifacts);
1551                                                 if (!deleteFromEsRes.equals(StorageOperationStatus.OK)) {
1552                                                         ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(deleteFromEsRes);
1553                                                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, resource.getName());
1554                                                 }
1555                                                 log.debug("component and all its artifacts were deleted, id = {}", resource.getName());
1556                                         }
1557
1558                                 } else {
1559                                         log.debug("operation success. do commit");
1560                                         titanDao.commit();
1561                                 }
1562                         }
1563                         if (shouldLock) {
1564                                 graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(), NodeTypeEnum.Resource);
1565                         }
1566                 }
1567         }
1568
1569         private Either<Resource, ResponseFormat> createGroupsOnResource(Resource resource, User user, Map<String, GroupDefinition> groups) {
1570                 if (groups != null && !groups.isEmpty()) {
1571                         Either<List<GroupDefinition>, ResponseFormat> mergeGroupsUsingResource = updateGroupMembersUsingResource(groups, resource);
1572
1573                         if (mergeGroupsUsingResource.isRight()) {
1574                                 log.debug("Failed to prepare groups for creation");
1575                                 return Either.right(mergeGroupsUsingResource.right().value());
1576                         }
1577                         List<GroupDefinition> groupsAsList = mergeGroupsUsingResource.left().value();
1578                         Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.createGroups(resource, user, ComponentTypeEnum.RESOURCE, groupsAsList);
1579                         if (createGroups.isRight()) {
1580                                 return Either.right(createGroups.right().value());
1581                         }
1582                 } else {
1583                         return Either.left(resource);
1584                 }
1585                 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
1586                 if (updatedResource.isRight()) {
1587                         ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource);
1588                         return Either.right(responseFormat);
1589                 }
1590                 return Either.left(updatedResource.left().value());
1591         }
1592
1593         private Either<Resource, ResponseFormat> updateGroupsOnResource(Resource resource, User user, Map<String, GroupDefinition> groups) {
1594                 if (groups != null && false == groups.isEmpty()) {
1595                         List<GroupDefinition> groupsFromResource = resource.getGroups();
1596                         Either<List<GroupDefinition>, ResponseFormat> mergeGroupsUsingResource = updateGroupMembersUsingResource(groups, resource);
1597
1598                         if (mergeGroupsUsingResource.isRight()) {
1599                                 log.debug("Failed to prepare groups for creation");
1600                                 return Either.right(mergeGroupsUsingResource.right().value());
1601                         }
1602                         List<GroupDefinition> groupsAsList = mergeGroupsUsingResource.left().value();
1603                         List<GroupDefinition> groupsToUpdate = new ArrayList<GroupDefinition>();
1604                         List<GroupDefinition> groupsToDelete = new ArrayList<GroupDefinition>();
1605                         List<GroupDefinition> groupsToCreate = new ArrayList<GroupDefinition>();
1606                         if (groupsFromResource != null && !groupsFromResource.isEmpty()) {
1607                                 for (GroupDefinition group : groupsAsList) {
1608                                         Optional<GroupDefinition> op = groupsFromResource.stream().filter(p -> p.getName().equals(group.getName())).findAny();
1609                                         if (op.isPresent()) {
1610                                                 GroupDefinition groupToUpdate = op.get();
1611                                                 groupToUpdate.setMembers(group.getMembers());
1612                                                 groupsToUpdate.add(groupToUpdate);
1613                                         } else {
1614                                                 groupsToCreate.add(group);
1615                                         }
1616                                 }
1617                                 for (GroupDefinition group : groupsFromResource) {
1618                                         Optional<GroupDefinition> op = groupsAsList.stream().filter(p -> p.getName().equals(group.getName())).findAny();
1619                                         if (!op.isPresent() && (group.getArtifacts() == null || group.getArtifacts().isEmpty())) {
1620
1621                                                 groupsToDelete.add(group);
1622                                         }
1623
1624                                 }
1625                         } else
1626                                 groupsToCreate.addAll(groupsAsList);
1627                         Either<List<GroupDefinition>, ResponseFormat> prepareGroups = null;
1628                         if (!groupsToCreate.isEmpty()) {
1629
1630                                 if (groupsFromResource != null && !groupsFromResource.isEmpty()) {
1631                                         prepareGroups = groupBusinessLogic.addGroups(resource, user, ComponentTypeEnum.RESOURCE, groupsToCreate);
1632                                 } else {
1633                                         prepareGroups = groupBusinessLogic.createGroups(resource, user, ComponentTypeEnum.RESOURCE, groupsToCreate);
1634                                 }
1635
1636                                 if (prepareGroups.isRight()) {
1637                                         return Either.right(prepareGroups.right().value());
1638                                 }
1639                         }
1640
1641                         if (!groupsToDelete.isEmpty()) {
1642                                 prepareGroups = groupBusinessLogic.deleteGroups(resource, user, ComponentTypeEnum.RESOURCE, groupsToDelete);
1643                                 if (prepareGroups.isRight()) {
1644                                         return Either.right(prepareGroups.right().value());
1645                                 }
1646                         }
1647
1648                         if (groupsToUpdate != null && !groupsToUpdate.isEmpty()) {
1649                                 prepareGroups = groupBusinessLogic.updateGroups(resource, ComponentTypeEnum.RESOURCE, groupsToUpdate);
1650                                 if (prepareGroups.isRight()) {
1651                                         return Either.right(prepareGroups.right().value());
1652                                 }
1653                         }
1654
1655                 } else {
1656                         return Either.left(resource);
1657                 }
1658
1659                 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
1660                 if (updatedResource.isRight()) {
1661                         ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource);
1662                         return Either.right(responseFormat);
1663                 }
1664                 return Either.left(updatedResource.left().value());
1665         }
1666
1667         private Either<Resource, ResponseFormat> createInputsOnResource(Resource resource, User user, Map<String, InputDefinition> inputs, boolean inTransaction) {
1668                 List<InputDefinition> resourceProperties = resource.getInputs();
1669                 if ( (inputs != null && false == inputs.isEmpty()) || (resourceProperties != null && false == resourceProperties.isEmpty()) ) {
1670
1671                         Either<List<InputDefinition>, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs, resource, user, inTransaction);
1672                         if (createInputs.isRight()) {
1673                                 return Either.right(createInputs.right().value());
1674                         }
1675                 } else {
1676                         return Either.left(resource);
1677                 }
1678
1679                 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
1680                 if (updatedResource.isRight()) {
1681                         ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource);
1682                         return Either.right(responseFormat);
1683                 }
1684                 return Either.left(updatedResource.left().value());
1685         }
1686
1687         private Either<List<GroupDefinition>, ResponseFormat> updateGroupMembersUsingResource(Map<String, GroupDefinition> groups, Resource component) {
1688
1689                 List<GroupDefinition> result = new ArrayList<>();
1690
1691                 List<ComponentInstance> componentInstances = component.getComponentInstances();
1692
1693                 if (groups != null) {
1694                         Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies = validateCyclicGroupsDependencies(groups);
1695                         if (validateCyclicGroupsDependencies.isRight()) {
1696                                 return FunctionalInterfaces.convertEitherRight(validateCyclicGroupsDependencies);
1697                         }
1698                         for (Entry<String, GroupDefinition> entry : groups.entrySet()) {
1699                                 String groupName = entry.getKey();
1700
1701                                 GroupDefinition groupDefinition = entry.getValue();
1702
1703                                 GroupDefinition updatedGroupDefinition = new GroupDefinition(groupDefinition);
1704                                 updatedGroupDefinition.setMembers(null);
1705
1706                                 // get the members of the group
1707                                 Map<String, String> members = groupDefinition.getMembers();
1708                                 if (members != null) {
1709                                         Set<String> compInstancesNames = members.keySet();
1710
1711                                         if (componentInstances == null || true == componentInstances.isEmpty()) {
1712                                                 String membersAstString = compInstancesNames.stream().collect(Collectors.joining(","));
1713                                                 log.debug("The members: {}, in group: {}, cannot be found in component {}. There are no component instances.", membersAstString, groupName, component.getNormalizedName());
1714                                                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, component.getNormalizedName(), getComponentTypeForResponse(component)));
1715                                         }
1716                                         // Find all component instances with the member names
1717                                         Map<String, String> memberNames = componentInstances.stream().collect(Collectors.toMap(ComponentInstance::getName, ComponentInstance::getUniqueId));
1718                                         memberNames.putAll(groups.keySet().stream().collect(Collectors.toMap(g -> g, g -> "")));
1719                                         Map<String, String> relevantInstances = memberNames.entrySet().stream().filter(n -> compInstancesNames.contains(n.getKey())).collect(Collectors.toMap(n -> n.getKey(), n -> n.getValue()));
1720
1721                                         if (relevantInstances == null || relevantInstances.size() != compInstancesNames.size()) {
1722
1723                                                 List<String> foundMembers = new ArrayList<>();
1724                                                 if (relevantInstances != null) {
1725                                                         foundMembers = relevantInstances.keySet().stream().collect(Collectors.toList());
1726                                                 }
1727                                                 compInstancesNames.removeAll(foundMembers);
1728                                                 String membersAstString = compInstancesNames.stream().collect(Collectors.joining(","));
1729                                                 log.debug("The members: {}, in group: {}, cannot be found in component: {}", membersAstString, groupName, component.getNormalizedName());
1730                                                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, component.getNormalizedName(), getComponentTypeForResponse(component)));
1731                                         }
1732
1733                                         updatedGroupDefinition.setMembers(relevantInstances);
1734                                 }
1735
1736                                 result.add(updatedGroupDefinition);
1737                         }
1738                 }
1739                 return Either.left(result);
1740         }
1741
1742         /**
1743          * This Method validates that there is no cyclic group dependencies. meaning group A as member in group B which is member in group A
1744          *
1745          * @param allGroups
1746          * @return
1747          */
1748         private Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies(Map<String, GroupDefinition> allGroups) {
1749
1750                 Either<Boolean, ResponseFormat> result = Either.left(true);
1751                 try {
1752                         Iterator<Entry<String, GroupDefinition>> allGroupsItr = allGroups.entrySet().iterator();
1753                         while (allGroupsItr.hasNext() && result.isLeft()) {
1754                                 Entry<String, GroupDefinition> groupAEntry = allGroupsItr.next();
1755                                 // Fetches a group member A
1756                                 String groupAName = groupAEntry.getKey();
1757                                 // Finds all group members in group A
1758                                 Set<String> allGroupAMembersNames = new HashSet<>();
1759                                 fillAllGroupMemebersRecursivly(groupAEntry.getKey(), allGroups, allGroupAMembersNames);
1760                                 // If A is a group member of itself found cyclic dependency
1761                                 if (allGroupAMembersNames.contains(groupAName)) {
1762                                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GROUP_HAS_CYCLIC_DEPENDENCY, groupAName);
1763                                         result = Either.right(responseFormat);
1764                                 }
1765                         }
1766                 } catch (Exception e) {
1767                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1768                         result = Either.right(responseFormat);
1769                         log.debug("Exception occured when validateCyclicGroupsDependencies, error is:{}", e.getMessage(), e);
1770                 }
1771                 return result;
1772         }
1773
1774         /**
1775          * This Method fills recursively the set groupMembers with all the members of the given group which are also of type group.
1776          *
1777          * @param groupName
1778          * @param allGroups
1779          * @param allGroupMembers
1780          * @return
1781          */
1782         private void fillAllGroupMemebersRecursivly(String groupName, Map<String, GroupDefinition> allGroups, Set<String> allGroupMembers) {
1783
1784                 // Found Cyclic dependency
1785                 if (isfillGroupMemebersRecursivlyStopCondition(groupName, allGroups, allGroupMembers)) {
1786                         return;
1787                 }
1788                 GroupDefinition groupDefinition = allGroups.get(groupName);
1789                 // All Members Of Current Group Resource Instances & Other Groups
1790                 Set<String> currGroupMembers = groupDefinition.getMembers().keySet();
1791                 // Filtered Members Of Current Group containing only members which
1792                 // are groups
1793                 List<String> currGroupFilteredMembers = currGroupMembers.stream().
1794                 // Keep Only Elements of type group and not Resource Instances
1795                                 filter(innerGroupName -> allGroups.containsKey(innerGroupName)).
1796                                 // Add Filtered Elements to main Set
1797                                 peek(innerGroupName -> allGroupMembers.add(innerGroupName)).
1798                                 // Collect results
1799                                 collect(Collectors.toList());
1800
1801                 // Recursively call the method for all the filtered group members
1802                 for (String innerGroupName : currGroupFilteredMembers) {
1803                         fillAllGroupMemebersRecursivly(innerGroupName, allGroups, allGroupMembers);
1804                 }
1805
1806         }
1807
1808         private boolean isfillGroupMemebersRecursivlyStopCondition(String groupName, Map<String, GroupDefinition> allGroups, Set<String> allGroupMembers) {
1809
1810                 boolean stop = false;
1811                 // In Case Not Group Stop
1812                 if (!allGroups.containsKey(groupName)) {
1813                         stop = true;
1814                 }
1815                 // In Case Group Has no members stop
1816                 if (!stop) {
1817                         GroupDefinition groupDefinition = allGroups.get(groupName);
1818                         stop = MapUtils.isEmpty(groupDefinition.getMembers());
1819
1820                 }
1821                 // In Case all group members already contained stop
1822                 if (!stop) {
1823                         final Set<String> allMembers = allGroups.get(groupName).getMembers().keySet();
1824                         Set<String> membersOfTypeGroup = allMembers.stream().
1825                         // Filter In Only Group members
1826                                         filter(innerGroupName -> allGroups.containsKey(innerGroupName)).
1827                                         // Collect
1828                                         collect(Collectors.toSet());
1829                         stop = allGroupMembers.containsAll(membersOfTypeGroup);
1830                 }
1831                 return stop;
1832         }
1833
1834         private Either<Resource, ResponseFormat> createRIAndRelationsFromYaml(String yamlName, Resource resource, Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap, AuditingActionEnum actionEnum,
1835                                                                                                                                                   String topologyTemplateYaml, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, Resource> createdVfcs,
1836                                                                                                                                                   Map<String, NodeTypeInfo> nodeTypesInfo, ImportCsarInfo importCsarInfo, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate) {
1837
1838                 Either<Resource, ResponseFormat> result;
1839                 Either<Resource, ResponseFormat> createResourcesInstancesEither;
1840
1841                 log.debug("************* Going to create all nodes {}", yamlName);
1842                 Either<Map<String, Resource>, ResponseFormat> createdResourcesFromdNodeTypeMap = this.handleNodeTypes(yamlName, resource, topologyTemplateYaml, false, nodeTypesArtifactsToCreate, nodeTypesNewCreatedArtifacts, nodeTypesInfo, importCsarInfo);
1843                 log.debug("************* Finished to create all nodes {}", yamlName);
1844                 if (createdResourcesFromdNodeTypeMap.isRight()) {
1845                         log.debug("failed to resources from node types status is {}", createdResourcesFromdNodeTypeMap.right().value());
1846                         return Either.right(createdResourcesFromdNodeTypeMap.right().value());
1847                 }
1848
1849                 createdVfcs.putAll(createdResourcesFromdNodeTypeMap.left().value());
1850
1851                 log.debug("************* Going to create all resource instances {}", yamlName);
1852                 createResourcesInstancesEither = createResourceInstances(importCsarInfo.getModifier(), yamlName, resource, uploadComponentInstanceInfoMap, true, false, createdResourcesFromdNodeTypeMap.left().value());
1853
1854                 log.debug("************* Finished to create all resource instances {}", yamlName);
1855                 if (createResourcesInstancesEither.isRight()) {
1856                         log.debug("failed to create resource instances status is {}", createResourcesInstancesEither.right().value());
1857                         result = createResourcesInstancesEither;
1858                         return createResourcesInstancesEither;
1859                 }
1860                 resource = createResourcesInstancesEither.left().value();
1861                 log.debug("************* Going to create all relations {}", yamlName);
1862                 createResourcesInstancesEither = createResourceInstancesRelations(importCsarInfo.getModifier(), yamlName, resource, uploadComponentInstanceInfoMap, true, false);
1863
1864                 log.debug("************* Finished to create all relations {}", yamlName);
1865
1866                 if (createResourcesInstancesEither.isRight()) {
1867                         log.debug("failed to create relation between resource instances status is {}", createResourcesInstancesEither.right().value());
1868                         result = createResourcesInstancesEither;
1869                         return result;
1870                 } else {
1871                         resource = createResourcesInstancesEither.left().value();
1872                 }
1873
1874                 log.debug("************* Going to create positions {}", yamlName);
1875                 Either<List<ComponentInstance>, ResponseFormat> eitherSetPosition = compositionBusinessLogic.setPositionsForComponentInstances(resource, importCsarInfo.getModifier().getUserId());
1876                 log.debug("************* Finished to set positions {}", yamlName);
1877                 result = eitherSetPosition.isRight() ? Either.right(eitherSetPosition.right().value()) : Either.left(resource);
1878
1879                 return result;
1880         }
1881
1882         private Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> findNodeTypeArtifactsToCreate(Map<String, byte[]> csar, Resource resource) {
1883
1884                 Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts = CsarUtils.extractVfcsArtifactsFromCsar(csar);
1885                 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = new HashMap<>();
1886                 for (Map.Entry<String, List<ArtifactDefinition>> currArts : extractedVfcsArtifacts.entrySet()) {
1887                         EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> artifactsToCreate = new EnumMap<>(ArtifactOperationEnum.class);
1888                         artifactsToCreate.put(ArtifactOperationEnum.Create, currArts.getValue());
1889                         nodeTypesArtifactsToHandle.put(currArts.getKey(), artifactsToCreate);
1890                 }
1891                 return nodeTypesArtifactsToHandle;
1892         }
1893
1894         private void handleAndAddExtractedVfcsArtifacts(List<ArtifactDefinition> vfcArtifacts, List<ArtifactDefinition> artifactsToAdd) {
1895                 List<String> vfcArtifactNames = vfcArtifacts.stream().map(a -> a.getArtifactName()).collect(Collectors.toList());
1896                 artifactsToAdd.stream().forEach(a -> {
1897                         if (!vfcArtifactNames.contains(a.getArtifactName())) {
1898                                 vfcArtifacts.add(a);
1899                         } else {
1900                                 log.error("Can't upload two artifact with the same name {}. ", a.getArtifactName());
1901                         }
1902                 });
1903
1904         }
1905
1906         @SuppressWarnings("unchecked")
1907         private Either<Map<String, Resource>, ResponseFormat> handleNodeTypes(String yamlName, Resource resource, String topologyTemplateYaml, boolean needLock,
1908                                                                                                                                                  Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
1909                                                                                                                                                   Map<String, NodeTypeInfo> nodeTypesInfo, ImportCsarInfo importCsarInfo) {
1910
1911                 Map<String, Resource> createdResourcesFromdNodeTypeMap = new HashMap<>();
1912                 Either<Map<String, Resource>, ResponseFormat> result = Either.left(createdResourcesFromdNodeTypeMap);
1913                 for (Entry<String, NodeTypeInfo> nodeTypeEntry : nodeTypesInfo.entrySet()) {
1914                         if (nodeTypeEntry.getValue().isNested()) {
1915
1916                                 Either<Resource, ResponseFormat> createResourceFromYaml = handleNestedVfc(resource, nodeTypesArtifactsToHandle, 
1917                                                 nodeTypesNewCreatedArtifacts, nodeTypesInfo, importCsarInfo, nodeTypeEntry.getKey(), createdResourcesFromdNodeTypeMap);
1918                                 log.trace("************* finished to create node {}", nodeTypeEntry.getKey());
1919                                 if (createResourceFromYaml.isRight()) {
1920                                         return Either.right(createResourceFromYaml.right().value());
1921                                 }
1922                         }
1923                 }
1924                 Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(topologyTemplateYaml);
1925                 Either<Map<String, Resource>, ResponseFormat> createdNodeTypeFromMainTemplateEither = createResourcesFromYamlNodeTypesList(yamlName, resource, topologyTemplateYaml, mappedToscaTemplate, needLock, nodeTypesArtifactsToHandle, 
1926                                 nodeTypesNewCreatedArtifacts, nodeTypesInfo, importCsarInfo);
1927                 if (createdNodeTypeFromMainTemplateEither.isRight()) {
1928                         ResponseFormat responseFormat = createdNodeTypeFromMainTemplateEither.right().value();
1929                         componentsUtils.auditResource(responseFormat, importCsarInfo.getModifier(), resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
1930                         return Either.right(responseFormat);
1931                 }
1932
1933                 createdResourcesFromdNodeTypeMap.putAll(createdNodeTypeFromMainTemplateEither.left().value());
1934
1935                 // add the created node types to the cache although they are not in the
1936                 // graph.
1937                 createdResourcesFromdNodeTypeMap.values().stream().forEach(p -> cacheManagerOperation.storeComponentInCache(p, NodeTypeEnum.Resource));
1938
1939                 return result;
1940         }
1941
1942         private Either<Resource, ResponseFormat> handleVfCsarArtifacts(Resource resource, ImportCsarInfo importCsarInfo, List<ArtifactDefinition> createdArtifacts, ArtifactOperationInfo artifactOperation, boolean shouldLock,
1943                         boolean inTransaction) {
1944
1945                 if (importCsarInfo.getCsar() != null) {
1946                         String vendorLicenseModelId = null;
1947                         String vfLicenseModelId = null;
1948
1949                         if (artifactOperation.getArtifactOperationEnum() == ArtifactOperationEnum.Update) {
1950                                 Map<String, ArtifactDefinition> deploymentArtifactsMap = resource.getDeploymentArtifacts();
1951                                 if (deploymentArtifactsMap != null && !deploymentArtifactsMap.isEmpty()) {
1952                                         for (Entry<String, ArtifactDefinition> artifactEntry : deploymentArtifactsMap.entrySet()) {
1953                                                 if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VENDOR_LICENSE_MODEL))
1954                                                         vendorLicenseModelId = artifactEntry.getValue().getUniqueId();
1955                                                 if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VF_LICENSE_MODEL))
1956                                                         vfLicenseModelId = artifactEntry.getValue().getUniqueId();
1957                                         }
1958                                 }
1959
1960                         }
1961                         // Specific Behavior for license artifacts
1962                         createOrUpdateSingleNonMetaArtifact(resource, importCsarInfo, CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL, Constants.VENDOR_LICENSE_MODEL, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
1963                                         Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME, Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId, artifactOperation, null, shouldLock, inTransaction);
1964                         createOrUpdateSingleNonMetaArtifact(resource, importCsarInfo, CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL, ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
1965                                         Constants.VF_LICENSE_LABEL, Constants.VF_LICENSE_DISPLAY_NAME, Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId, artifactOperation, null, shouldLock, inTransaction);
1966
1967                         Either<Resource, ResponseFormat> eitherCreateResult = createOrUpdateNonMetaArtifacts(importCsarInfo, resource, createdArtifacts, shouldLock, inTransaction, artifactOperation);
1968                         if (eitherCreateResult.isRight()) {
1969                                 return Either.right(eitherCreateResult.right().value());
1970                         }
1971
1972                         Either<ImmutablePair<String, String>, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils.getArtifactsMeta(importCsarInfo.getCsar(), importCsarInfo.getCsarUUID(), componentsUtils);
1973                         if (artifacsMetaCsarStatus.isLeft()) {
1974
1975                                 String artifactsFileName = artifacsMetaCsarStatus.left().value().getKey();
1976                                 String artifactsContents = artifacsMetaCsarStatus.left().value().getValue();
1977                                 Either<Resource, ResponseFormat> createArtifactsFromCsar = Either.left(resource);
1978                                 if (artifactOperation.getArtifactOperationEnum() == ArtifactOperationEnum.Create)
1979                                         createArtifactsFromCsar = createResourceArtifactsFromCsar(importCsarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction);
1980                                 else
1981                                         createArtifactsFromCsar = updateResourceArtifactsFromCsar(importCsarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction);
1982                                 if (createArtifactsFromCsar.isRight()) {
1983                                         log.debug("Couldn't create artifacts from artifacts.meta");
1984                                         return Either.right(createArtifactsFromCsar.right().value());
1985                                 }
1986
1987                                 resource = createArtifactsFromCsar.left().value();
1988                         } else {
1989                                 List<GroupDefinition> groupsToDelete = resource.getGroups();
1990
1991                                 if (groupsToDelete != null && !groupsToDelete.isEmpty()) {
1992                                         Set<String> artifactsToDelete = new HashSet<String>();
1993                                         /*
1994                                          * for (GroupDefinition group : groupsToDelete) { List<String> artifacts = group.getArtifacts(); if (artifacts != null) { artifactsToDelete.addAll(artifacts); Either<GroupDefinition, StorageOperationStatus> deleteGroupEither =
1995                                          * groupOperation.deleteGroup(group.getUniqueId(), inTransaction); if (deleteGroupEither.isRight()) { StorageOperationStatus storageOperationStatus = deleteGroupEither.right().value(); ActionStatus actionStatus =
1996                                          * componentsUtils.convertFromStorageResponse(storageOperationStatus); log.debug("Failed to delete group {} under component {}, error: {}", group.getUniqueId(), resource.getNormalizedName(), actionStatus.name()); return
1997                                          * Either.right(componentsUtils.getResponseFormat(actionStatus)); } } }
1998                                          */
1999                                         for (String artifactId : artifactsToDelete) {
2000                                                 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resource.getUniqueId(), artifactId, importCsarInfo.getModifier(), AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE,
2001                                                                 resource, null, null, shouldLock, inTransaction);
2002                                                 if (handleDelete.isRight()) {
2003                                                         log.debug("Couldn't delete  artifact {}", artifactId);
2004                                                         return Either.right(handleDelete.right().value());
2005                                                 }
2006                                         }
2007                                         Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
2008                                         if (eitherGetResource.isRight()) {
2009                                                 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource);
2010
2011                                                 return Either.right(responseFormat);
2012
2013                                         }
2014                                         resource = eitherGetResource.left().value();
2015                                 }
2016                         }
2017                 }
2018                 return Either.left(resource);
2019         }
2020
2021         private Either<Boolean, ResponseFormat> createOrUpdateSingleNonMetaArtifact(Resource resource, ImportCsarInfo importCsarInfo, String artifactPath, String artifactFileName, String artifactType,
2022                         ArtifactGroupTypeEnum artifactGroupType, String artifactLabel, String artifactDisplayName, String artifactDescription, String artifactId, ArtifactOperationInfo operation, List<ArtifactDefinition> createdArtifacts, boolean shouldLock,
2023                         boolean inTransaction) {
2024                 byte[] artifactFileBytes = null;
2025
2026                 if (importCsarInfo.getCsar().containsKey(artifactPath)) {
2027                         artifactFileBytes = importCsarInfo.getCsar().get(artifactPath);
2028                 }
2029                 Either<Boolean, ResponseFormat> result = Either.left(true);
2030                 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Update || operation.getArtifactOperationEnum() == ArtifactOperationEnum.Delete) {
2031                         if (artifactId != null && !artifactId.isEmpty() && artifactFileBytes == null) {
2032                                 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resource.getUniqueId(), artifactId, importCsarInfo.getModifier(), AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, resource, null,
2033                                                 null, shouldLock, inTransaction);
2034                                 if (handleDelete.isRight()) {
2035                                         result = Either.right(handleDelete.right().value());
2036                                 }
2037                                 return result;
2038                         }
2039
2040                         if ((artifactId == null || artifactId.isEmpty()) && artifactFileBytes != null) {
2041                                 operation = artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create);
2042                         }
2043
2044                 }
2045                 if (artifactFileBytes != null) {
2046                         Map<String, Object> vendorLicenseModelJson = buildJsonForUpdateArtifact(artifactId, artifactFileName, artifactType, artifactGroupType, artifactLabel, artifactDisplayName, artifactDescription, artifactFileBytes, null);
2047                         Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts = createOrUpdateCsarArtifactFromJson(resource, importCsarInfo.getModifier(), vendorLicenseModelJson, operation, shouldLock, inTransaction);
2048                         addNonMetaCreatedArtifactsToSupportRollback(operation, createdArtifacts, eitherNonMetaArtifacts);
2049                         if (eitherNonMetaArtifacts.isRight()) {
2050                                 BeEcompErrorManager.getInstance().logInternalFlowError("UploadLicenseArtifact", "Failed to upload license artifact: " + artifactFileName + "With csar uuid: " + importCsarInfo.getCsarUUID(), ErrorSeverity.WARNING);
2051                                 return Either.right(eitherNonMetaArtifacts.right().value());
2052                         }
2053                 }
2054                 return result;
2055         }
2056
2057         private void addNonMetaCreatedArtifactsToSupportRollback(ArtifactOperationInfo operation, List<ArtifactDefinition> createdArtifacts, Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts) {
2058                 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create && createdArtifacts != null && eitherNonMetaArtifacts.isLeft()) {
2059                         Either<ArtifactDefinition, Operation> eitherResult = eitherNonMetaArtifacts.left().value();
2060                         if (eitherResult.isLeft()) {
2061                                 createdArtifacts.add(eitherResult.left().value());
2062                         }
2063                 }
2064         }
2065
2066         private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createOrUpdateCsarArtifactFromJson(Resource resource, User user, Map<String, Object> json, ArtifactOperationInfo operation, boolean shoudLock, boolean inTransaction) {
2067
2068                 String jsonStr = gson.toJson(json);
2069
2070                 String origMd5 = GeneralUtility.calculateMD5ByString(jsonStr);
2071                 ArtifactDefinition artifactDefinitionFromJson = RepresentationUtils.convertJsonToArtifactDefinition(jsonStr, ArtifactDefinition.class);
2072                 String artifactUniqueId = artifactDefinitionFromJson == null ? null : artifactDefinitionFromJson.getUniqueId();
2073                 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = artifactsBusinessLogic.validateAndHandleArtifact(resource.getUniqueId(), ComponentTypeEnum.RESOURCE, operation, artifactUniqueId,
2074                                 artifactDefinitionFromJson, origMd5, jsonStr, null, null, null, user, resource, false, true, false);
2075                 if (uploadArtifactToService.isRight())
2076                         return Either.right(uploadArtifactToService.right().value());
2077
2078                 return Either.left(uploadArtifactToService.left().value());
2079         }
2080
2081         public Either<Resource, ResponseFormat> updateResourceArtifactsFromCsar(ImportCsarInfo importCsarInfo, Resource resource, String artifactsMetaFile, String artifactsMetaFileName, List<ArtifactDefinition> createdNewArtifacts,
2082                         boolean shouldLock, boolean inTransaction) {
2083
2084                 Either<Map<String, List<ArtifactTemplateInfo>>, ResponseFormat> parseResourceInfoFromYamlEither = parseResourceArtifactsInfoFromFile(resource, artifactsMetaFile, artifactsMetaFileName, importCsarInfo.getModifier());
2085                 if (parseResourceInfoFromYamlEither.isRight()) {
2086                         ResponseFormat responseFormat = parseResourceInfoFromYamlEither.right().value();
2087                         componentsUtils.auditResource(responseFormat, importCsarInfo.getModifier(), resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
2088                         return Either.right(responseFormat);
2089                 }
2090
2091                 List<GroupDefinition> groups = resource.getGroups();
2092                 Map<String, ArtifactDefinition> deplymentArtifact = resource.getDeploymentArtifacts();
2093                 List<ArtifactDefinition> createdDeplymentArtifactsAfterDelete = new ArrayList<ArtifactDefinition>();
2094                 if (deplymentArtifact != null && !deplymentArtifact.isEmpty()) {
2095                         for (Entry<String, ArtifactDefinition> entry : deplymentArtifact.entrySet()) {
2096                                 createdDeplymentArtifactsAfterDelete.add(entry.getValue());
2097                         }
2098                 }
2099                 int labelCounter = createdDeplymentArtifactsAfterDelete.size();
2100
2101                 if (deplymentArtifact == null || deplymentArtifact.isEmpty()) {
2102                         if (groups != null && !groups.isEmpty()) {
2103                                 for (GroupDefinition group : groups) {
2104                                         if (group.getArtifacts() != null && !group.getArtifacts().isEmpty()) {
2105                                                 log.debug("failed to update artifacts from csar. List of emty but group not empty");
2106                                                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
2107                                                 return Either.right(responseFormat);
2108                                         }
2109                                 }
2110                         }
2111                         return createResourceArtifacts(importCsarInfo, resource, parseResourceInfoFromYamlEither.left().value(), AuditingActionEnum.CREATE_RESOURCE, createdNewArtifacts, shouldLock, inTransaction);
2112                 }
2113
2114                 // find master in group
2115                 Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupArtifact = findMasterArtifactInGroup(groups, deplymentArtifact);
2116
2117                 ////////////////////////////////////// create set parsed
2118                 ////////////////////////////////////// artifacts///////////////////////////////////////////
2119                 Map<String, List<ArtifactTemplateInfo>> parsedArtifactsMap = parseResourceInfoFromYamlEither.left().value();
2120                 Collection<List<ArtifactTemplateInfo>> parsedArifactsCollection = parsedArtifactsMap.values();
2121                 Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup = new HashMap<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>>();
2122
2123                 for (List<ArtifactTemplateInfo> parsedGroupTemplateList : parsedArifactsCollection) {
2124                         for (ArtifactTemplateInfo parsedGroupTemplate : parsedGroupTemplateList) {
2125                                 parsedGroupTemplate.setGroupName("");
2126                                 Set<ArtifactTemplateInfo> parsedArtifactsNames = new HashSet<ArtifactTemplateInfo>();
2127                                 parsedArtifactsNames.add(parsedGroupTemplate);
2128                                 List<ArtifactTemplateInfo> relatedGroupTemplateList = parsedGroupTemplate.getRelatedArtifactsInfo();
2129                                 if (relatedGroupTemplateList != null && !relatedGroupTemplateList.isEmpty()) {
2130                                         createArtifactsGroupSet(parsedGroupTemplateList, parsedArtifactsNames);
2131                                 }
2132                                 parsedGroup.put(parsedGroupTemplate, parsedArtifactsNames);
2133                         }
2134                 }
2135
2136                 ///////////////////////////////// find artifacts to
2137                 ///////////////////////////////// delete////////////////////////////////////////////////////
2138
2139                 Set<ArtifactDefinition> artifactsToDelete = new HashSet<ArtifactDefinition>();
2140                 Map<String, List<ArtifactDefinition>> groupToDelete = new HashMap<String, List<ArtifactDefinition>>();
2141                 Map<String, List<String>> dissocArtifactFromGroup = new HashMap<String, List<String>>();
2142
2143                 Set<ArtifactTemplateInfo> jsonMasterArtifacts = parsedGroup.keySet();
2144                 Map<GroupDefinition, MergedArtifactInfo> mergedgroup = mergeGroupInUpdateFlow(groupArtifact, parsedGroup, artifactsToDelete, groupToDelete, jsonMasterArtifacts, createdDeplymentArtifactsAfterDelete);
2145
2146                 // Set<String> deletedArtifactsName = new HashSet<String>();
2147                 Either<List<ArtifactDefinition>, ResponseFormat> deletedArtifactsEither = deleteArtifactsInUpdateCsarFlow(resource, importCsarInfo.getModifier(), shouldLock, inTransaction, artifactsToDelete, groupToDelete);
2148                 if (deletedArtifactsEither.isRight()) {
2149                         log.debug("Failed to delete artifacts. Status is {} ", deletedArtifactsEither.right().value());
2150
2151                         return Either.right(deletedArtifactsEither.right().value());
2152
2153                 }
2154                 List<ArtifactDefinition> deletedArtifacts = deletedArtifactsEither.left().value();
2155
2156                 // need to update resource if we updated artifacts
2157                 if (deletedArtifacts != null && !deletedArtifacts.isEmpty()) {
2158                         for (ArtifactDefinition deletedArtifact : deletedArtifacts) {
2159                                 ArtifactDefinition artToRemove = null;
2160                                 for (ArtifactDefinition artFromResource : createdDeplymentArtifactsAfterDelete) {
2161                                         if (deletedArtifact.getUniqueId().equalsIgnoreCase(artFromResource.getUniqueId())) {
2162                                                 artToRemove = artFromResource;
2163                                                 break;
2164                                         }
2165                                 }
2166                                 if (artToRemove != null)
2167                                         createdDeplymentArtifactsAfterDelete.remove(artToRemove);
2168
2169                         }
2170                 }
2171
2172                 ////////////// dissociate, associate or create
2173                 ////////////// artifacts////////////////////////////
2174                 Either<Resource, ResponseFormat> assDissotiateEither = associateAndDissociateArtifactsToGroup(importCsarInfo, resource, createdNewArtifacts, labelCounter, shouldLock, inTransaction, createdDeplymentArtifactsAfterDelete,
2175                                 mergedgroup, deletedArtifacts);
2176
2177                 if (assDissotiateEither.isRight()) {
2178                         log.debug("Failed to delete artifacts. Status is {} ", assDissotiateEither.right().value());
2179
2180                         return Either.right(assDissotiateEither.right().value());
2181
2182                 }
2183                 resource = assDissotiateEither.left().value();
2184                 deplymentArtifact = resource.getDeploymentArtifacts();
2185                 createdDeplymentArtifactsAfterDelete.clear();
2186                 if (deplymentArtifact != null && !deplymentArtifact.isEmpty()) {
2187                         for (Entry<String, ArtifactDefinition> entry : deplymentArtifact.entrySet()) {
2188                                 createdDeplymentArtifactsAfterDelete.add(entry.getValue());
2189                         }
2190                 }
2191
2192                 groups = resource.getGroups();
2193
2194                 // update vfModule names
2195                 Set<GroupDefinition> groupForAssociateWithMembers = mergedgroup.keySet();
2196                 if (groups != null && !groups.isEmpty()) {
2197                         Either<List<GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic.validateUpdateVfGroupNamesOnGraph(groups, resource, inTransaction);
2198                         if (validateUpdateVfGroupNamesRes.isRight()) {
2199                                 return Either.right(validateUpdateVfGroupNamesRes.right().value());
2200                         }
2201                         List<GroupDefinition> heatGroups = null;
2202
2203                         heatGroups = groups.stream().filter(e -> e.getMembers() != null).collect(Collectors.toList());
2204                         ;
2205
2206                         for (GroupDefinition updatedGroupDef : groupForAssociateWithMembers) {
2207
2208                                 if (updatedGroupDef.getMembers() != null && !updatedGroupDef.getMembers().isEmpty()) {
2209                                         updatedGroupDef.getMembers().clear();
2210                                 }
2211                                 Map<String, String> members = new HashMap<String, String>();
2212                                 Set<String> artifactsGroup = new HashSet<String>();
2213                                 artifactsGroup.addAll(updatedGroupDef.getArtifacts());
2214                                 associateMembersToArtifacts(createdNewArtifacts, createdDeplymentArtifactsAfterDelete, heatGroups, artifactsGroup, members);
2215                                 if (!members.isEmpty()) {
2216                                         updatedGroupDef.setMembers(members);
2217
2218                                 }
2219
2220
2221                         }
2222
2223
2224                 }
2225
2226                 //////////////// create new artifacts in update
2227                 //////////////// flow////////////////////////////
2228                 List<ArtifactTemplateInfo> newArtifactsGroup = new ArrayList<ArtifactTemplateInfo>();
2229
2230                 for (Entry<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroupSetEntry : parsedGroup.entrySet()) {
2231                         ArtifactTemplateInfo parsedArtifactMaster = parsedGroupSetEntry.getKey();
2232                         boolean isNewGroup = true;
2233                         for (Entry<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupListEntry : groupArtifact.entrySet()) {
2234                                 Map<ArtifactDefinition, List<ArtifactDefinition>> groupArtifacts = groupListEntry.getValue();
2235                                 Set<ArtifactDefinition> group = groupArtifacts.keySet();
2236                                 for (ArtifactDefinition artifactInfo : group) {
2237                                         if (parsedArtifactMaster.getFileName().equalsIgnoreCase(artifactInfo.getArtifactName())) {
2238                                                 parsedArtifactMaster.setGroupName(groupListEntry.getKey().getName());
2239                                                 isNewGroup = false;
2240                                         }
2241                                 }
2242                         }
2243                         if (isNewGroup)
2244                                 newArtifactsGroup.add(parsedArtifactMaster);
2245
2246                 }
2247                 if (!newArtifactsGroup.isEmpty()) {
2248                         Collections.sort(newArtifactsGroup, (art1, art2) -> ArtifactTemplateInfo.compareByGroupName(art1, art2));
2249                         int startGroupCounter = groupBusinessLogic.getNextVfModuleNameCounter(groups);
2250                         Either<Boolean, ResponseFormat> validateGroupNamesRes = groupBusinessLogic.validateGenerateVfModuleGroupNames(newArtifactsGroup, resource.getSystemName(), startGroupCounter);
2251                         if (validateGroupNamesRes.isRight()) {
2252                                 return Either.right(validateGroupNamesRes.right().value());
2253                         }
2254                         Either<Resource, ResponseFormat> resStatus = createGroupDeploymentArtifactsFromCsar(importCsarInfo, resource, newArtifactsGroup, createdNewArtifacts, createdDeplymentArtifactsAfterDelete, labelCounter, shouldLock, inTransaction);
2255                         if (resStatus.isRight())
2256                                 return resStatus;
2257                 }
2258
2259                 // updatedGroup
2260                 if (!groupForAssociateWithMembers.isEmpty()) {
2261
2262                         List<GroupDefinition> groupsId = groupForAssociateWithMembers.stream().map(e -> e).collect(Collectors.toList());
2263
2264                         Either<List<GroupDefinition>, ResponseFormat> updateVersionEither = groupBusinessLogic.updateGroups(resource, ComponentTypeEnum.RESOURCE, groupsId);
2265                         if (updateVersionEither.isRight()) {
2266                                 log.debug("Failed to update groups version. Status is {} ", updateVersionEither.right().value());
2267
2268                                 return Either.right(updateVersionEither.right().value());
2269
2270                         }
2271                 }
2272
2273                 Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
2274                 if (eitherGerResource.isRight()) {
2275                         ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
2276
2277                         return Either.right(responseFormat);
2278
2279                 }
2280                 return Either.left(eitherGerResource.left().value());
2281
2282         }
2283
2284         private Either<List<ArtifactDefinition>, ResponseFormat> deleteArtifactsInUpdateCsarFlow(Resource resource, User user, boolean shouldLock, boolean inTransaction, Set<ArtifactDefinition> artifactsToDelete,
2285                         Map<String, List<ArtifactDefinition>> groupToDelete) {
2286                 List<ArtifactDefinition> deletedArtifacts = new ArrayList<ArtifactDefinition>();
2287                 String resourceId = resource.getUniqueId();
2288                 if (!artifactsToDelete.isEmpty()) {
2289                         for (ArtifactDefinition artifact : artifactsToDelete) {
2290                                 String artifactType = artifact.getArtifactType();
2291                                 ArtifactTypeEnum artifactTypeEnum = ArtifactTypeEnum.findType(artifactType);
2292                                 if (artifactTypeEnum == ArtifactTypeEnum.HEAT_ENV) {
2293
2294                                         /*
2295                                          * Either<ArtifactDefinition, StorageOperationStatus> removeArifactFromGraph = artifactOperation.removeArifactFromResource(resourceId, artifact.getUniqueId(), NodeTypeEnum.Resource, true, true); if
2296                                          * (removeArifactFromGraph.isRight()) { StorageOperationStatus status = removeArifactFromGraph.right().value(); log.debug("Failed to delete heat env artifact  {} . status is {}", artifact.getUniqueId(), status); ActionStatus
2297                                          * actionStatus = componentsUtils.convertFromStorageResponse(status); return Either.right(componentsUtils.getResponseFormat(actionStatus)); }
2298                                          *
2299                                          * deletedArtifacts.add(removeArifactFromGraph.left().value());
2300                                          */
2301
2302                                 } else {
2303                                         Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resourceId, artifact.getUniqueId(), user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, resource,
2304                                                         null, null, shouldLock, inTransaction);
2305                                         if (handleDelete.isRight()) {
2306                                                 return Either.right(handleDelete.right().value());
2307                                         }
2308
2309                                         deletedArtifacts.add(handleDelete.left().value().left().value());
2310                                 }
2311
2312                         }
2313                 }
2314                 if (!groupToDelete.isEmpty()) {
2315                         log.debug("try to delete group");
2316                         List<GroupDefinition> groupDefinitionstoDelete = new ArrayList<>();
2317                         List<GroupDefinition> groups = resource.getGroups();
2318                         for (Entry<String, List<ArtifactDefinition>> deleteGroup : groupToDelete.entrySet()) {
2319                                 Optional<GroupDefinition> op = groups.stream().filter(gr -> gr.getUniqueId().equals(deleteGroup.getKey())).findAny();
2320                                 if (op.isPresent()) {
2321                                         groupDefinitionstoDelete.add(op.get());
2322                                 }
2323
2324                         }
2325                         if (!groupDefinitionstoDelete.isEmpty()) {
2326                                 Either<List<GroupDefinition>, ResponseFormat> prepareGroups = groupBusinessLogic.deleteGroups(resource, user, ComponentTypeEnum.RESOURCE, groupDefinitionstoDelete);
2327                                 if (prepareGroups.isRight()) {
2328                                         return Either.right(prepareGroups.right().value());
2329                                 }
2330                         }
2331                 }
2332                 return Either.left(deletedArtifacts);
2333         }
2334
2335         private Either<Resource, ResponseFormat> associateAndDissociateArtifactsToGroup(ImportCsarInfo importCsarInfo, Resource resource, List<ArtifactDefinition> createdNewArtifacts, int labelCounter, boolean shouldLock,
2336                         boolean inTransaction, List<ArtifactDefinition> createdDeplymentArtifactsAfterDelete, Map<GroupDefinition, MergedArtifactInfo> mergedgroup, List<ArtifactDefinition> deletedArtifacts) {
2337                 Map<GroupDefinition, List<ArtifactTemplateInfo>> artifactsToAssotiate = new HashMap<GroupDefinition, List<ArtifactTemplateInfo>>();
2338                 Map<GroupDefinition, List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>>> artifactsToUpdateMap = new HashMap<GroupDefinition, List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>>>();
2339                 Either<Resource, ResponseFormat> resEither = Either.left(resource);
2340                 for (Entry<GroupDefinition, MergedArtifactInfo> entry : mergedgroup.entrySet()) {
2341                         List<ArtifactDefinition> dissArtifactsInGroup = entry.getValue().getListToDissotiateArtifactFromGroup(deletedArtifacts);
2342                         GroupDefinition grDef = entry.getKey();
2343                         if (dissArtifactsInGroup != null && !dissArtifactsInGroup.isEmpty()) {
2344                                 for (ArtifactDefinition art : dissArtifactsInGroup) {
2345                                         grDef.getArtifacts().remove(art.getUniqueId());
2346                                         grDef.getArtifactsUuid().remove(art.getArtifactUUID());
2347                                 }
2348                         }
2349
2350                         List<ArtifactTemplateInfo> newArtifactsInGroup = entry.getValue().getListToAssociateArtifactToGroup();
2351                         if (newArtifactsInGroup != null && !newArtifactsInGroup.isEmpty())
2352                                 artifactsToAssotiate.put(entry.getKey(), newArtifactsInGroup);
2353
2354                         List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>> artifactsToUpdate = entry.getValue().getListToUpdateArtifactInGroup();
2355                         if (artifactsToUpdate != null && !artifactsToUpdate.isEmpty())
2356                                 artifactsToUpdateMap.put(entry.getKey(), artifactsToUpdate);
2357                 }
2358
2359                 if (!artifactsToUpdateMap.isEmpty()) {
2360                         List<ArtifactDefinition> updatedArtifacts = new ArrayList<ArtifactDefinition>();
2361                         for (Entry<GroupDefinition, List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>>> artifactsToUpdateEntry : artifactsToUpdateMap.entrySet()) {
2362                                 List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>> artifactsToUpdateList = artifactsToUpdateEntry.getValue();
2363                                 GroupDefinition groupToUpdate = artifactsToUpdateEntry.getKey();
2364
2365                                 for (ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo> artifact : artifactsToUpdateList) {
2366                                         String prevUUID = artifact.getKey().getArtifactUUID();
2367                                         String prevId = artifact.getKey().getUniqueId();
2368                                         Either<ArtifactDefinition, ResponseFormat> updateArtifactEither = updateDeploymentArtifactsFromCsar(importCsarInfo, resource, artifact.getKey(), artifact.getValue(), updatedArtifacts,
2369                                                         artifact.getRight().getRelatedArtifactsInfo(), shouldLock, inTransaction);
2370                                         if (updateArtifactEither.isRight()) {
2371                                                 log.debug("failed to update artifacts. status is {}", updateArtifactEither.right().value());
2372                                                 resEither = Either.right(updateArtifactEither.right().value());
2373                                                 return resEither;
2374                                         }
2375                                         ArtifactDefinition artAfterUpdate = updateArtifactEither.left().value();
2376                                         if (!prevUUID.equals(artAfterUpdate.getArtifactUUID()) || !prevId.equals(artAfterUpdate.getUniqueId())) {
2377                                                 groupToUpdate.getArtifacts().remove(prevId);
2378                                                 groupToUpdate.getArtifactsUuid().remove(prevUUID);
2379                                                 groupToUpdate.getArtifacts().add(artAfterUpdate.getUniqueId());
2380                                                 groupToUpdate.getArtifactsUuid().add(artAfterUpdate.getArtifactUUID());
2381                                         }
2382                                 }
2383                         }
2384                 }
2385
2386                 List<GroupDefinition> associateArtifactGroup = new ArrayList<GroupDefinition>();
2387
2388                 for (Entry<GroupDefinition, List<ArtifactTemplateInfo>> associateEntry : artifactsToAssotiate.entrySet()) {
2389                         List<ArtifactTemplateInfo> associatedArtifact = associateEntry.getValue();
2390                         Set<String> arifactsUids = new HashSet<String>();
2391                         Set<String> arifactsUuids = new HashSet<String>();
2392                         for (ArtifactTemplateInfo artifactTemplate : associatedArtifact) { // try
2393                                 // to
2394                                 // find
2395                                 // artifact
2396                                 // in
2397                                 // resource
2398                                 boolean isCreate = true;
2399                                 for (ArtifactDefinition createdArtifact : createdDeplymentArtifactsAfterDelete) {
2400                                         if (artifactTemplate.getFileName().equalsIgnoreCase(createdArtifact.getArtifactName())) {
2401                                                 arifactsUids.add(createdArtifact.getUniqueId());
2402                                                 arifactsUuids.add(createdArtifact.getUniqueId());
2403                                                 isCreate = false;
2404                                                 String heatEnvId = checkAndGetHeatEnvId(createdArtifact);
2405                                                 if (!heatEnvId.isEmpty()) {
2406                                                         arifactsUids.add(heatEnvId);
2407                                                         Optional<ArtifactDefinition> op = createdDeplymentArtifactsAfterDelete.stream().filter(p -> p.getUniqueId().equals(heatEnvId)).findAny();
2408                                                         if (op.isPresent()) {
2409                                                                 this.artifactToscaOperation.updateHeatEnvPlaceholder(op.get(), resource.getUniqueId(), resource.getComponentType().getNodeType());
2410
2411                                                         }
2412                                                 }
2413
2414                                                 break;
2415                                         }
2416
2417                                 }
2418                                 if (isCreate) { // check if already created
2419                                         for (ArtifactDefinition createdNewArtifact : createdNewArtifacts) {
2420                                                 if (artifactTemplate.getFileName().equalsIgnoreCase(createdNewArtifact.getArtifactName())) {
2421                                                         arifactsUids.add(createdNewArtifact.getUniqueId());
2422                                                         arifactsUuids.add(createdNewArtifact.getUniqueId());
2423                                                         isCreate = false;
2424                                                         String heatEnvId = checkAndGetHeatEnvId(createdNewArtifact);
2425                                                         if (!heatEnvId.isEmpty()) {
2426                                                                 arifactsUids.add(heatEnvId);
2427                                                         }
2428                                                         break;
2429                                                 }
2430                                         }
2431                                 }
2432
2433                                 if (isCreate) {
2434                                         Either<ArtifactDefinition, ResponseFormat> createArtifactEither = createDeploymentArtifact(importCsarInfo, resource, ARTIFACTS_PATH, artifactTemplate, createdNewArtifacts, labelCounter, shouldLock, inTransaction);
2435                                         if (createArtifactEither.isRight()) {
2436                                                 resEither = Either.right(createArtifactEither.right().value());
2437                                                 return resEither;
2438                                         }
2439                                         ArtifactDefinition createdArtifact = createArtifactEither.left().value();
2440                                         arifactsUids.add(createdArtifact.getUniqueId());
2441                                         arifactsUuids.add(createdArtifact.getUniqueId());
2442                                         ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(createdArtifact.getArtifactType());
2443                                         if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_VOL) {
2444                                                 Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactsBusinessLogic.createHeatEnvPlaceHolder(createdArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME, resource.getUniqueId(), NodeTypeEnum.Resource,
2445                                                                 resource.getName(), importCsarInfo.getModifier(), resource, null);
2446                                                 if (createHeatEnvPlaceHolder.isRight()) {
2447                                                         return Either.right(createHeatEnvPlaceHolder.right().value());
2448                                                 }
2449                                                 String heatEnvId = createHeatEnvPlaceHolder.left().value().getUniqueId();
2450                                                 arifactsUids.add(heatEnvId);
2451                                         }
2452                                 }
2453
2454                         }
2455                         if (arifactsUids.size() > 0) {
2456                                 List<String> artifactsToAssociate = new ArrayList<String>();
2457                                 artifactsToAssociate.addAll(arifactsUids);
2458                                 GroupDefinition assotiateGroup = associateEntry.getKey();
2459                                 assotiateGroup.getArtifacts().addAll(arifactsUids);
2460                                 assotiateGroup.getArtifactsUuid().addAll(arifactsUuids);
2461                         }
2462                 }
2463
2464                 /*
2465                  * if (!associateArtifactGroup.isEmpty()) {
2466                  *
2467                  * log.debug("Try to associate artifacts to groups.");
2468                  *
2469                  * Either<List<GroupDefinition>, ResponseFormat> assotiateGroupEither = groupBusinessLogic.associateArtifactsToGroup(resource.getUniqueId(), user.getUserId(), ComponentTypeEnum.RESOURCE, associateArtifactGroup, shouldLock, inTransaction); if
2470                  * (assotiateGroupEither.isRight()) { log.debug("Failed to associate artifacts to groups. Status is {} ", assotiateGroupEither.right().value()); resEither = Either.right(assotiateGroupEither.right().value()); return resEither;
2471                  *
2472                  * } }
2473                  */
2474
2475                 ComponentParametersView parametersView = new ComponentParametersView();
2476                 parametersView.disableAll();
2477                 parametersView.setIgnoreComponentInstances(false);
2478                 parametersView.setIgnoreUsers(false);
2479                 parametersView.setIgnoreArtifacts(false);
2480                 parametersView.setIgnoreGroups(false);
2481
2482                 Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId(), parametersView);
2483
2484                 if (eitherGerResource.isRight()) {
2485                         ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
2486
2487                         resEither = Either.right(responseFormat);
2488                         return resEither;
2489
2490                 }
2491                 resEither = Either.left(eitherGerResource.left().value());
2492                 return resEither;
2493         }
2494
2495         private Map<GroupDefinition, MergedArtifactInfo> mergeGroupInUpdateFlow(Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupArtifact, Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup,
2496                         Set<ArtifactDefinition> artifactsToDelete, Map<String, List<ArtifactDefinition>> groupToDelete, Set<ArtifactTemplateInfo> jsonMasterArtifacts, List<ArtifactDefinition> createdDeplymentArtifacts) {
2497                 Map<GroupDefinition, MergedArtifactInfo> mergedgroup = new HashMap<GroupDefinition, MergedArtifactInfo>();
2498                 for (Entry<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupListEntry : groupArtifact.entrySet()) {
2499                         Map<ArtifactDefinition, List<ArtifactDefinition>> createdArtifactMap = groupListEntry.getValue();
2500                         boolean isNeedToDeleteGroup = true;
2501                         List<ArtifactDefinition> listToDelete = null;
2502                         for (ArtifactDefinition maserArtifact : createdArtifactMap.keySet()) {
2503                                 listToDelete = createdArtifactMap.get(maserArtifact);
2504                                 for (ArtifactDefinition artToDelete : listToDelete) {
2505                                         findArtifactToDelete(parsedGroup, artifactsToDelete, groupListEntry.getKey().getUniqueId(), artToDelete, createdDeplymentArtifacts);
2506                                 }
2507                                 if (artifactsToDelete != null && !artifactsToDelete.isEmpty()) {
2508                                         GroupDefinition group = groupListEntry.getKey();
2509                                         for (ArtifactDefinition artifactDefinition : artifactsToDelete) {
2510                                                 if (CollectionUtils.isNotEmpty(group.getArtifacts()) && group.getArtifacts().contains(artifactDefinition.getUniqueId())) {
2511                                                         group.getArtifacts().remove(artifactDefinition.getUniqueId());
2512
2513                                                 }
2514                                                 if (CollectionUtils.isNotEmpty(group.getArtifactsUuid()) && group.getArtifactsUuid().contains(artifactDefinition.getArtifactUUID())) {
2515                                                         group.getArtifactsUuid().remove(artifactDefinition.getArtifactUUID());
2516
2517                                                 }
2518                                         }
2519
2520                                 }
2521
2522                                 for (ArtifactTemplateInfo jsonMasterArtifact : jsonMasterArtifacts) {
2523                                         if (maserArtifact.getArtifactName().equalsIgnoreCase(jsonMasterArtifact.getFileName())) {
2524                                                 MergedArtifactInfo mergedGroup = new MergedArtifactInfo();
2525                                                 mergedGroup.setJsonArtifactTemplate(jsonMasterArtifact);
2526                                                 mergedGroup.setCreatedArtifact(createdArtifactMap.get(maserArtifact));
2527                                                 mergedgroup.put(groupListEntry.getKey(), mergedGroup);
2528                                                 isNeedToDeleteGroup = false;
2529
2530                                         }
2531                                 }
2532
2533                         }
2534                         if (isNeedToDeleteGroup) {
2535                                 groupToDelete.put(groupListEntry.getKey().getUniqueId(), listToDelete);
2536                         }
2537
2538                 }
2539                 return mergedgroup;
2540         }
2541
2542         private void findArtifactToDelete(Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup, Set<ArtifactDefinition> artifactsToDelete, String deleteGroupId, ArtifactDefinition artifact,
2543                         List<ArtifactDefinition> createdDeplymentArtifacts) {
2544                 boolean isNeedToDeleteArtifact = true;
2545                 String artifactType = artifact.getArtifactType();
2546                 ArtifactDefinition generatedFromArt = null;
2547                 if (artifact.getGeneratedFromId() != null && !artifact.getGeneratedFromId().isEmpty()) {
2548                         Optional<ArtifactDefinition> op = createdDeplymentArtifacts.stream().filter(p -> p.getUniqueId().equals(artifact.getGeneratedFromId())).findAny();
2549                         if (op.isPresent())
2550                                 generatedFromArt = op.get();
2551
2552                 }
2553
2554                 for (Entry<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroupSetEntry : parsedGroup.entrySet()) {
2555                         Set<ArtifactTemplateInfo> artifactsNames = parsedGroupSetEntry.getValue();
2556                         for (ArtifactTemplateInfo template : artifactsNames) {
2557                                 if (artifact.getArtifactName().equalsIgnoreCase(template.getFileName()) && artifactType.equalsIgnoreCase(template.getType())) {
2558                                         isNeedToDeleteArtifact = false;
2559                                         break;
2560
2561                                 } else {
2562                                         if (generatedFromArt != null) {
2563                                                 if (generatedFromArt.getArtifactName().equalsIgnoreCase(template.getFileName()) && generatedFromArt.getArtifactType().equalsIgnoreCase(template.getType())) {
2564                                                         isNeedToDeleteArtifact = false;
2565                                                         break;
2566                                                 }
2567                                         }
2568                                 }
2569                         }
2570
2571                 }
2572                 if (isNeedToDeleteArtifact) {
2573                         artifactsToDelete.add(artifact);
2574
2575                 }
2576         }
2577
2578         private Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> findMasterArtifactInGroup(List<GroupDefinition> groups, Map<String, ArtifactDefinition> deplymentArtifact) {
2579                 Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupArtifact = new HashMap<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>>();
2580
2581                 for (GroupDefinition group : groups) {
2582                         Map<ArtifactDefinition, List<ArtifactDefinition>> gupsMap = new HashMap<ArtifactDefinition, List<ArtifactDefinition>>();
2583                         List<ArtifactDefinition> artifacts = new ArrayList<ArtifactDefinition>();
2584                         List<String> artifactsList = group.getArtifacts();
2585                         if (artifactsList != null && !artifactsList.isEmpty()) {
2586
2587                                 ArtifactDefinition masterArtifact = ArtifactUtils.findMasterArtifact(deplymentArtifact, artifacts, artifactsList);
2588                                 if (masterArtifact != null)
2589                                         gupsMap.put(masterArtifact, artifacts);
2590                                 groupArtifact.put(group, gupsMap);
2591
2592                         }
2593                 }
2594                 return groupArtifact;
2595         }
2596
2597         private void createArtifactsGroupSet(List<ArtifactTemplateInfo> parsedGroupTemplateList, Set<ArtifactTemplateInfo> parsedArtifactsName) {
2598
2599                 for (ArtifactTemplateInfo parsedGroupTemplate : parsedGroupTemplateList) {
2600                         parsedArtifactsName.add(parsedGroupTemplate);
2601                         List<ArtifactTemplateInfo> relatedArtifacts = parsedGroupTemplate.getRelatedArtifactsInfo();
2602                         if (relatedArtifacts != null && !relatedArtifacts.isEmpty()) {
2603                                 createArtifactsGroupSet(relatedArtifacts, parsedArtifactsName);
2604                         }
2605                 }
2606         }
2607
2608         public Either<Resource, ResponseFormat> createResourceArtifactsFromCsar(ImportCsarInfo importCsarInfo, Resource resource, String artifactsMetaFile, String artifactsMetaFileName, List<ArtifactDefinition> createdArtifacts,
2609                         boolean shouldLock, boolean inTransaction) {
2610
2611                 log.debug("parseResourceArtifactsInfoFromFile start");
2612                 Either<Map<String, List<ArtifactTemplateInfo>>, ResponseFormat> parseResourceInfoFromYamlEither = parseResourceArtifactsInfoFromFile(resource, artifactsMetaFile, artifactsMetaFileName, importCsarInfo.getModifier());
2613                 if (parseResourceInfoFromYamlEither.isRight()) {
2614                         ResponseFormat responseFormat = parseResourceInfoFromYamlEither.right().value();
2615                         componentsUtils.auditResource(responseFormat, importCsarInfo.getModifier(), resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
2616                         return Either.right(responseFormat);
2617                 }
2618                 log.debug("parseResourceArtifactsInfoFromFile end");
2619
2620                 log.debug("createResourceArtifacts start");
2621                 Either<Resource, ResponseFormat> respStatus = createResourceArtifacts(importCsarInfo, resource, parseResourceInfoFromYamlEither.left().value(), AuditingActionEnum.CREATE_RESOURCE, createdArtifacts, shouldLock, inTransaction);
2622                 if (respStatus.isRight()) {
2623                         return respStatus;
2624                 }
2625                 log.debug("createResourceArtifacts end");
2626                 log.debug("getResource start");
2627                 Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
2628                 log.debug("getResource end");
2629                 if (eitherGerResource.isRight()) {
2630                         ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
2631
2632                         return Either.right(responseFormat);
2633
2634                 }
2635                 return Either.left(eitherGerResource.left().value());
2636
2637         }
2638
2639         private Either<Resource, ResponseFormat> createGroupDeploymentArtifactsFromCsar(ImportCsarInfo importCsarInfo, Resource resource, List<ArtifactTemplateInfo> artifactsTemplateList,
2640                         List<ArtifactDefinition> createdNewArtifacts, List<ArtifactDefinition> artifactsFromResource, int labelCounter, boolean shouldLock, boolean inTransaction) {
2641                 Either<Resource, ResponseFormat> resStatus = Either.left(resource);
2642                 List<GroupDefinition> createdGroups = resource.getGroups();
2643                 List<GroupDefinition> heatGroups = null;
2644                 if (createdGroups != null && !createdGroups.isEmpty()) {
2645                         heatGroups = createdGroups.stream().filter(e -> e.getMembers() != null).collect(Collectors.toList());
2646                 }
2647
2648                 List<GroupDefinition> needToAdd = new ArrayList<>();
2649                 for (ArtifactTemplateInfo groupTemplateInfo : artifactsTemplateList) {
2650                         String groupName = groupTemplateInfo.getGroupName();
2651                         Set<String> artifactsGroup = new HashSet<String>();
2652                         Set<String> artifactsUUIDGroup = new HashSet<String>();
2653
2654                         resStatus = createDeploymentArtifactsFromCsar(importCsarInfo, resource, artifactsGroup, artifactsUUIDGroup, groupTemplateInfo, createdNewArtifacts, artifactsFromResource, labelCounter, shouldLock, inTransaction);
2655                         if (resStatus.isRight())
2656                                 return resStatus;
2657
2658                         Map<String, String> members = new HashMap<String, String>();
2659                         associateMembersToArtifacts(createdNewArtifacts, artifactsFromResource, heatGroups, artifactsGroup, members);
2660
2661                         List<String> artifactsList = new ArrayList<String>(artifactsGroup);
2662                         List<String> artifactsUUIDList = new ArrayList<String>(artifactsUUIDGroup);
2663
2664                         GroupDefinition groupDefinition = new GroupDefinition();
2665                         groupDefinition.setName(groupName);
2666                         groupDefinition.setType(Constants.DEFAULT_GROUP_VF_MODULE);
2667                         groupDefinition.setArtifacts(artifactsList);
2668                         groupDefinition.setArtifactsUuid(artifactsUUIDList);
2669
2670                         if (!members.isEmpty())
2671                                 groupDefinition.setMembers(members);
2672
2673                         List<GroupProperty> properties = new ArrayList<GroupProperty>();
2674                         GroupProperty prop = new GroupProperty();
2675                         prop.setName(Constants.IS_BASE);
2676                         prop.setValue(Boolean.toString(groupTemplateInfo.isBase()));
2677                         properties.add(prop);
2678
2679                         List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
2680                         createdArtifacts.addAll(createdNewArtifacts);
2681                         createdArtifacts.addAll(artifactsFromResource);
2682                         Either<GroupTypeDefinition, StorageOperationStatus> getLatestGroupTypeRes = groupTypeOperation.getLatestGroupTypeByType(Constants.DEFAULT_GROUP_VF_MODULE, true);
2683                         if (getLatestGroupTypeRes.isRight()) {
2684                                 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getLatestGroupTypeRes.right().value())));
2685                         }
2686                         properties = createVfModuleAdditionalProperties(groupTemplateInfo.isBase(), groupName, properties, createdArtifacts, artifactsList, getLatestGroupTypeRes.left().value());
2687                         groupDefinition.convertFromGroupProperties(properties);
2688
2689                         // Either<GroupDefinition, ResponseFormat> createGroup = groupBusinessLogic.createGroup(resource.getUniqueId(), user.getUserId(), ComponentTypeEnum.RESOURCE, groupDefinition, inTransaction);
2690                         // if (createGroup.isRight())
2691                         // return Either.right(createGroup.right().value());
2692                         needToAdd.add(groupDefinition);
2693                 }
2694                 ComponentParametersView componentParametersView = new ComponentParametersView();
2695                 componentParametersView.disableAll();
2696                 componentParametersView.setIgnoreArtifacts(false);
2697                 componentParametersView.setIgnoreGroups(false);
2698                 componentParametersView.setIgnoreComponentInstances(false);
2699
2700                 Either<Resource, StorageOperationStatus> component = toscaOperationFacade.getToscaElement(resource.getUniqueId(), componentParametersView);
2701                 if (component.isRight()) {
2702                         return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
2703                 }
2704                 resource = component.left().value();
2705
2706                 Either<List<GroupDefinition>, ResponseFormat> addGroups = groupBusinessLogic.addGroups(resource, importCsarInfo.getModifier(), ComponentTypeEnum.RESOURCE, needToAdd);
2707                 if (addGroups.isRight())
2708                         return Either.right(addGroups.right().value());
2709
2710                 return resStatus;
2711         }
2712
2713         private Either<Resource, ResponseFormat> createDeploymentArtifactsFromCsar(ImportCsarInfo importCsarInfo, Resource resource, Set<String> artifactsGroup, Set<String> artifactsUUIDGroup,
2714                         ArtifactTemplateInfo artifactTemplateInfo, List<ArtifactDefinition> createdArtifacts, List<ArtifactDefinition> artifactsFromResource, int labelCounter, boolean shoudLock, boolean inTransaction) {
2715                 Either<Resource, ResponseFormat> resStatus = Either.left(resource);
2716                 String artifactFileName = artifactTemplateInfo.getFileName();
2717                 String artifactUid = "";
2718                 String artifactUUID = "";
2719                 String artifactEnvUid = "";
2720                 boolean alreadyExist = false;
2721
2722                 // check if artifacts already exist
2723                 if (artifactsFromResource != null && !artifactsFromResource.isEmpty()) {
2724                         for (ArtifactDefinition artifactFromResource : artifactsFromResource) {
2725                                 if (artifactFromResource.getArtifactName().equals(artifactFileName)) {
2726                                         artifactUid = artifactFromResource.getUniqueId();
2727                                         artifactUUID = artifactFromResource.getArtifactUUID();
2728                                         if (!artifactFromResource.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) {
2729                                                 log.debug("Artifact with name {} and type {} already exist with type  {}", artifactFileName, artifactTemplateInfo.getType(), artifactFromResource.getArtifactType());
2730                                                 BeEcompErrorManager.getInstance().logInternalDataError("Artifact  file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
2731                                                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName, artifactTemplateInfo.getType(), artifactFromResource.getArtifactType()));
2732                                         }
2733                                         alreadyExist = true;
2734                                         artifactEnvUid = checkAndGetHeatEnvId(artifactFromResource);
2735                                         break;
2736                                 }
2737
2738                         }
2739
2740                 }
2741                 if (!alreadyExist) {
2742                         for (ArtifactDefinition createdArtifact : createdArtifacts) {
2743                                 if (createdArtifact.getArtifactName().equals(artifactFileName)) {
2744                                         artifactUid = createdArtifact.getUniqueId();
2745                                         artifactUUID = createdArtifact.getArtifactUUID();
2746
2747                                         if (!createdArtifact.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) {
2748                                                 log.debug("Artifact with name {} and type {} already exist with type  {}", artifactFileName, artifactTemplateInfo.getType(), createdArtifact.getArtifactType());
2749                                                 BeEcompErrorManager.getInstance().logInternalDataError("Artifact  file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
2750                                                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName, artifactTemplateInfo.getType(), createdArtifact.getArtifactType()));
2751                                         }
2752                                         alreadyExist = true;
2753                                         artifactEnvUid = checkAndGetHeatEnvId(createdArtifact);
2754                                         break;
2755                                 }
2756
2757                         }
2758                 }
2759                 // if not exist need to create
2760                 if (!alreadyExist) {
2761
2762                         Either<ArtifactDefinition, ResponseFormat> newArtifactEither = createDeploymentArtifact(importCsarInfo, resource, ARTIFACTS_PATH, artifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction);
2763                         if (newArtifactEither.isRight()) {
2764                                 resStatus = Either.right(newArtifactEither.right().value());
2765                                 return resStatus;
2766                         }
2767                         ArtifactDefinition newArtifact = newArtifactEither.left().value();
2768                         artifactUid = newArtifact.getUniqueId();
2769                         artifactUUID = newArtifact.getArtifactUUID();
2770                         ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(newArtifact.getArtifactType());
2771                         if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_VOL) {
2772                                 Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactsBusinessLogic.createHeatEnvPlaceHolder(newArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME, resource.getUniqueId(), NodeTypeEnum.Resource,
2773                                                 resource.getName(), importCsarInfo.getModifier(), resource, null);
2774                                 if (createHeatEnvPlaceHolder.isRight()) {
2775                                         return Either.right(createHeatEnvPlaceHolder.right().value());
2776                                 }
2777                                 artifactEnvUid = createHeatEnvPlaceHolder.left().value().getUniqueId();
2778                         }
2779                 }
2780
2781                 artifactsGroup.add(artifactUid);
2782                 artifactsUUIDGroup.add(artifactUUID);
2783                 if (!artifactEnvUid.isEmpty()) {
2784                         artifactsGroup.add(artifactEnvUid);
2785                 }
2786
2787                 List<ArtifactTemplateInfo> relatedArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo();
2788                 if (relatedArtifacts != null) {
2789                         for (ArtifactTemplateInfo relatedArtifactTemplateInfo : relatedArtifacts) {
2790                                 resStatus = createDeploymentArtifactsFromCsar(importCsarInfo, resource, artifactsGroup, artifactsUUIDGroup, relatedArtifactTemplateInfo, createdArtifacts, artifactsFromResource, labelCounter, shoudLock, inTransaction);
2791                                 if (resStatus.isRight())
2792                                         return resStatus;
2793                         }
2794                 }
2795                 return resStatus;
2796         }
2797
2798         private Either<Resource, ResponseFormat> createResourceArtifacts(ImportCsarInfo importCsarInfo, Resource resource, Map<String, List<ArtifactTemplateInfo>> artifactsMap, AuditingActionEnum createResource,
2799                         List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction) {
2800
2801                 Either<Resource, ResponseFormat> resStatus = Either.left(resource);
2802
2803                 Collection<List<ArtifactTemplateInfo>> arifactsCollection = artifactsMap.values();
2804
2805                 for (List<ArtifactTemplateInfo> groupTemplateList : arifactsCollection) {
2806                         if (groupTemplateList != null) {
2807                                 resStatus = createGroupDeploymentArtifactsFromCsar(importCsarInfo, resource, groupTemplateList, createdArtifacts, 0, shouldLock, inTransaction);
2808                                 if (resStatus.isRight())
2809                                         return resStatus;
2810                         }
2811                 }
2812
2813                 return resStatus;
2814
2815         }
2816
2817         private Either<Resource, ResponseFormat> createOrUpdateNonMetaArtifacts(ImportCsarInfo importCsarInfo, Resource resource, List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction, ArtifactOperationInfo artifactOperation) {
2818
2819                 Either<Resource, ResponseFormat> resStatus = null;
2820                 Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
2821
2822                 try {
2823                         List<NonMetaArtifactInfo> artifactPathAndNameList =
2824                                         // Stream of file paths contained in csar
2825                                         importCsarInfo.getCsar().entrySet().stream()
2826                                                         // Filter in only VF artifact path location
2827                                                         .filter(e -> Pattern.compile(VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey()).matches())
2828                                                         // Validate and add warnings
2829                                                         .map(e -> CsarUtils.validateNonMetaArtifact(e.getKey(), e.getValue(), collectedWarningMessages))
2830                                                         // Filter in Non Warnings
2831                                                         .filter(e -> e.isLeft())
2832                                                         // Convert from Either to NonMetaArtifactInfo
2833                                                         .map(e -> e.left().value())
2834                                                         // collect to List
2835                                                         .collect(Collectors.toList());
2836
2837                         Either<Boolean, String> responseFormatEither = validateArtifactNames(artifactPathAndNameList);
2838                         if (responseFormatEither.isRight()) {
2839                                 return Either.right(getComponentsUtils().getResponseFormatByArtifactId(ActionStatus.ARTIFACT_NAME_INVALID, responseFormatEither.right().value()));
2840                         }
2841
2842
2843                         EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> vfCsarArtifactsToHandle = null;
2844
2845                         if (artifactOperation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) {
2846                                 vfCsarArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
2847                                 vfCsarArtifactsToHandle.put(artifactOperation.getArtifactOperationEnum(), artifactPathAndNameList);
2848                         } else {
2849                                 Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes = findVfCsarArtifactsToHandle(resource, artifactPathAndNameList, importCsarInfo.getModifier());
2850
2851                                 if (findVfCsarArtifactsToHandleRes.isRight()) {
2852                                         resStatus = Either.right(findVfCsarArtifactsToHandleRes.right().value());
2853                                 }
2854                                 if (resStatus == null) {
2855                                         vfCsarArtifactsToHandle = findVfCsarArtifactsToHandleRes.left().value();
2856                                 }
2857                         }
2858                         if (resStatus == null && vfCsarArtifactsToHandle != null) {
2859                                 for (Entry<ArtifactOperationEnum, List<NonMetaArtifactInfo>> currArtifactOperationPair : vfCsarArtifactsToHandle.entrySet()) {
2860
2861                                         Optional<ResponseFormat> optionalCreateInDBError =
2862                                                         // Stream of artifacts to be created
2863                                                         currArtifactOperationPair.getValue().stream()
2864                                                                         // create each artifact
2865                                                                         .map(e -> createOrUpdateSingleNonMetaArtifact(resource, importCsarInfo, e.getPath(), e.getArtifactName(), e.getArtifactType().getType(), e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(),
2866                                                                                         CsarUtils.ARTIFACT_CREATED_FROM_CSAR, e.getArtifactUniqueId(), artifactsBusinessLogic.new ArtifactOperationInfo(false, false, currArtifactOperationPair.getKey()), createdArtifacts, shouldLock,
2867                                                                                         inTransaction))
2868                                                                         // filter in only error
2869                                                                         .filter(e -> e.isRight()).
2870                                                                         // Convert the error from either to ResponseFormat
2871                                                                         map(e -> e.right().value()).
2872                                                                         // Check if an error occurred
2873                                                                         findAny();
2874                                         // Error found on artifact Creation
2875                                         if (optionalCreateInDBError.isPresent()) {
2876                                                 resStatus = Either.right(optionalCreateInDBError.get());
2877                                                 break;
2878                                         }
2879                                 }
2880                         }
2881                         if (resStatus == null) {
2882                                 resStatus = Either.left(resource);
2883                         }
2884                 } catch (Exception e) {
2885                         resStatus = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
2886                         log.debug("Exception occured in createNonMetaArtifacts, message:{}", e.getMessage(), e);
2887                 } finally {
2888                         CsarUtils.handleWarningMessages(collectedWarningMessages);
2889                 }
2890                 return resStatus;
2891         }
2892
2893         private Either<Boolean, String> validateArtifactNames(List<NonMetaArtifactInfo> artifactPathAndNameList) {
2894                 Pattern englishNumbersAndUnderScoresOnly = Pattern.compile(CsarUtils.VALID_ENGLISH_ARTIFACT_NAME);
2895                 for (NonMetaArtifactInfo nonMetaArtifactInfo : artifactPathAndNameList) {
2896                         if (!englishNumbersAndUnderScoresOnly.matcher(nonMetaArtifactInfo.getDisplayName()).matches()) {
2897                                 return Either.right(nonMetaArtifactInfo.getArtifactName());
2898                         }
2899                 }
2900                 return Either.left(true);
2901         }
2902
2903
2904         private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandle(Resource resource, List<NonMetaArtifactInfo> artifactPathAndNameList, User user) {
2905
2906                 List<ArtifactDefinition> existingArtifacts = new ArrayList<>();
2907                 // collect all Deployment and Informational artifacts of VF
2908                 if (resource.getDeploymentArtifacts() != null && !resource.getDeploymentArtifacts().isEmpty()) {
2909                         existingArtifacts.addAll(resource.getDeploymentArtifacts().values());
2910                 }
2911                 if (resource.getArtifacts() != null && !resource.getArtifacts().isEmpty()) {
2912                         existingArtifacts.addAll(resource.getArtifacts().values());
2913                 }
2914                 existingArtifacts = existingArtifacts.stream()
2915                                 // filter MANDATORY artifacts, LICENSE artifacts and artifacts was created from HEAT.meta
2916                                 .filter(this::isNonMetaArtifact).collect(Collectors.toList());
2917
2918                 List<String> artifactsToIgnore = new ArrayList<>();
2919                 // collect IDs of Artifacts of VF which belongs to any group
2920                 if (resource.getGroups() != null) {
2921                         resource.getGroups().stream().forEach(g -> {
2922                                 if (g.getArtifacts() != null && !g.getArtifacts().isEmpty())
2923                                         artifactsToIgnore.addAll(g.getArtifacts());
2924                         });
2925                 }
2926                 existingArtifacts = existingArtifacts.stream()
2927                                 // filter artifacts which belongs to any group
2928                                 .filter(a -> !artifactsToIgnore.contains(a.getUniqueId())).collect(Collectors.toList());
2929                 return organizeVfCsarArtifactsByArtifactOperation(artifactPathAndNameList, existingArtifacts, resource, user);
2930         }
2931
2932         private boolean isNonMetaArtifact(ArtifactDefinition artifact) {
2933                 boolean result = true;
2934                 if (artifact.getMandatory() || artifact.getArtifactName() == null || !isValidArtifactType(artifact)) {
2935                         result = false;
2936                 }
2937                 return result;
2938         }
2939
2940         private boolean isValidArtifactType(ArtifactDefinition artifact) {
2941                 boolean result = true;
2942                 if (artifact.getArtifactType() == null || ArtifactTypeEnum.findType(artifact.getArtifactType()) == ArtifactTypeEnum.VENDOR_LICENSE || ArtifactTypeEnum.findType(artifact.getArtifactType()) == ArtifactTypeEnum.VF_LICENSE) {
2943                         result = false;
2944                 }
2945                 return result;
2946         }
2947
2948         private Either<Resource, ResponseFormat> createGroupDeploymentArtifactsFromCsar(ImportCsarInfo importCsarInfo, Resource resource, List<ArtifactTemplateInfo> artifactsTemplateList, List<ArtifactDefinition> createdArtifacts,
2949                         int labelCounter, boolean shouldLock, boolean inTransaction) {
2950                 Either<Resource, ResponseFormat> resStatus = Either.left(resource);
2951                 List<GroupDefinition> createdGroups = resource.getGroups();
2952                 List<GroupDefinition> heatGroups = null;
2953                 if (createdGroups != null && !createdGroups.isEmpty()) {
2954
2955                         // List<IArtifactInfo> collect = resources.stream().flatMap( e ->
2956                         // e.getArtifacts().stream()).filter(p ->
2957                         // relevantArtifactTypes.contains(p.getArtifactType()
2958                         // )).collect(Collectors.toList());
2959                         // List<GroupDefinition> heatGroups = createdGroups.stream().filter(
2960                         // e -> e.getProperties().stream().filter(p ->
2961                         // p.getName().contains(Constants.HEAT_FILE_PROPS))).collect(Collectors.toList());
2962                         heatGroups = createdGroups.stream().filter(e -> e.getMembers() != null).collect(Collectors.toList());
2963                         ;
2964                 }
2965                 List<GroupDefinition> needToCreate = new ArrayList<>();
2966                 for (ArtifactTemplateInfo groupTemplateInfo : artifactsTemplateList) {
2967                         String groupName = groupTemplateInfo.getGroupName();
2968                         Set<String> artifactsGroup = new HashSet<String>();
2969                         Set<String> artifactsUUIDGroup = new HashSet<String>();
2970
2971                         log.debug("createDeploymentArtifactsFromCsar start");
2972                         resStatus = createDeploymentArtifactFromCsar(importCsarInfo, ARTIFACTS_PATH, resource, artifactsGroup, artifactsUUIDGroup, groupTemplateInfo, createdArtifacts, labelCounter, shouldLock, inTransaction);
2973                         log.debug("createDeploymentArtifactsFromCsar end");
2974                         if (resStatus.isRight())
2975                                 return resStatus;
2976
2977                         Map<String, String> members = new HashMap<String, String>();
2978                         associateMembersToArtifacts(createdArtifacts, null, heatGroups, artifactsGroup, members);
2979
2980                         List<String> artifactsList = new ArrayList<String>(artifactsGroup);
2981                         List<String> artifactsUUIDList = new ArrayList<String>(artifactsUUIDGroup);
2982
2983                         GroupDefinition groupDefinition = new GroupDefinition();
2984                         groupDefinition.setName(groupName);
2985                         groupDefinition.setType(Constants.DEFAULT_GROUP_VF_MODULE);
2986                         groupDefinition.setArtifacts(artifactsList);
2987                         groupDefinition.setArtifactsUuid(artifactsUUIDList);
2988
2989                         if (!members.isEmpty())
2990                                 groupDefinition.setMembers(members);
2991                         List<GroupProperty> properties = new ArrayList<GroupProperty>();
2992                         GroupProperty prop = new GroupProperty();
2993                         prop.setName(Constants.IS_BASE);
2994                         prop.setValue(Boolean.toString(groupTemplateInfo.isBase()));
2995                         properties.add(prop);
2996                         Either<GroupTypeDefinition, StorageOperationStatus> getLatestGroupTypeRes = groupTypeOperation.getLatestGroupTypeByType(Constants.DEFAULT_GROUP_VF_MODULE, true);
2997                         if (getLatestGroupTypeRes.isRight()) {
2998                                 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getLatestGroupTypeRes.right().value())));
2999                         }
3000                         properties = createVfModuleAdditionalProperties(groupTemplateInfo.isBase(), groupName, properties, createdArtifacts, artifactsList, getLatestGroupTypeRes.left().value());
3001                         groupDefinition.convertFromGroupProperties(properties);
3002                         log.debug("createGroup start");
3003
3004                         // Since in these groups we handle only artifacts, then no need to
3005                         // fetch component instances
3006
3007                         // Either<GroupDefinition, ResponseFormat> createGroup = groupBusinessLogic.createGroup(comp, user, ComponentTypeEnum.RESOURCE, groupDefinition, inTransaction);
3008                         // log.debug("createGroup end");
3009                         // if (createGroup.isRight())
3010                         // return Either.right(createGroup.right().value());
3011                         needToCreate.add(groupDefinition);
3012                 }
3013
3014                 ComponentParametersView componentParametersView = new ComponentParametersView();
3015                 componentParametersView.disableAll();
3016                 componentParametersView.setIgnoreUsers(false);
3017                 componentParametersView.setIgnoreArtifacts(false);
3018                 componentParametersView.setIgnoreGroups(false);
3019
3020                 componentParametersView.setIgnoreComponentInstances(false);
3021
3022                 Either<Resource, StorageOperationStatus> component = toscaOperationFacade.getToscaElement(resource.getUniqueId(), componentParametersView);
3023                 if (component.isRight()) {
3024                         return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
3025                 }
3026
3027                 Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.addGroups(component.left().value(), importCsarInfo.getModifier(), ComponentTypeEnum.RESOURCE, needToCreate);
3028                 if (createGroups.isRight()) {
3029                         return Either.right(createGroups.right().value());
3030                 }
3031
3032                 return resStatus;
3033         }
3034
3035         public List<GroupProperty> createVfModuleAdditionalProperties(boolean isBase, String moduleName, List<GroupProperty> properties, List<ArtifactDefinition> deploymentArtifacts, List<String> artifactsInGroup, GroupTypeDefinition groupType) {
3036                 Map<String, VfModuleProperty> vfModuleProperties = ConfigurationManager.getConfigurationManager().getConfiguration().getVfModuleProperties();
3037                 vfModuleProperties.entrySet().forEach(p -> {
3038                         GroupProperty prop = new GroupProperty();
3039                         prop.setName(p.getKey());
3040                         if (isBase) {
3041                                 prop.setValue(p.getValue().getForBaseModule());
3042                                 prop.setDefaultValue(p.getValue().getForBaseModule());
3043                         } else {
3044                                 prop.setValue(p.getValue().getForNonBaseModule());
3045                                 prop.setDefaultValue(p.getValue().getForNonBaseModule());
3046                         }
3047                         properties.add(prop);
3048
3049                 });
3050                 GroupProperty proplabel = new GroupProperty();
3051                 proplabel.setName("vf_module_label");
3052
3053                 Matcher matcher = pattern.matcher(moduleName);
3054
3055                 if (matcher.find()) {
3056                         proplabel.setValue(matcher.group(1));
3057                         proplabel.setDefaultValue(matcher.group(1));
3058                 } else {
3059                         proplabel.setValue(moduleName);
3060                         proplabel.setDefaultValue(moduleName);
3061                 }
3062                 properties.add(proplabel);
3063
3064                 GroupProperty propvolume = new GroupProperty();
3065                 propvolume.setName("volume_group");
3066                 boolean isVolume = false;
3067                 for (String artifactId : artifactsInGroup) {
3068                         ArtifactDefinition artifactDef = null;
3069                         artifactDef = findArtifactInList(deploymentArtifacts, artifactId);
3070                         if (artifactDef != null && artifactDef.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType())) {
3071                                 isVolume = true;
3072                                 break;
3073                         }
3074                 }
3075                 propvolume.setValue(String.valueOf(isVolume));
3076                 propvolume.setDefaultValue(String.valueOf(isVolume));
3077                 properties.add(propvolume);
3078                 mergeWithGroupTypeProperties(properties, groupType.getProperties());
3079                 return properties;
3080         }
3081
3082         private void mergeWithGroupTypeProperties(List<GroupProperty> properties, List<PropertyDefinition> groupTypeProperties) {
3083
3084                 Map<String, GroupProperty> propertiesMap = properties.stream().collect(Collectors.toMap(p -> p.getName(), p -> p));
3085                 for (PropertyDefinition groupTypeProperty : groupTypeProperties) {
3086                         if (!propertiesMap.containsKey(groupTypeProperty.getName())) {
3087                                 properties.add(new GroupProperty(groupTypeProperty));
3088                         }
3089                 }
3090         }
3091
3092         private ArtifactDefinition findArtifactInList(List<ArtifactDefinition> createdArtifacts, String artifactId) {
3093                 for (ArtifactDefinition artifact : createdArtifacts) {
3094                         if (artifact.getUniqueId().equals(artifactId)) {
3095                                 return artifact;
3096                         }
3097                 }
3098                 return null;
3099         }
3100
3101         private void associateMembersToArtifacts(List<ArtifactDefinition> createdArtifacts, List<ArtifactDefinition> artifactsFromResource, List<GroupDefinition> heatGroups, Set<String> artifactsGroup, Map<String, String> members) {
3102                 if (heatGroups != null && !heatGroups.isEmpty()) {
3103                         for (GroupDefinition heatGroup : heatGroups) {
3104                                 List<GroupProperty> grpoupProps = heatGroup.convertToGroupProperties();
3105                                 if (grpoupProps != null) {
3106                                         Optional<GroupProperty> op = grpoupProps.stream().filter(p -> p.getName().equals(Constants.HEAT_FILE_PROPS)).findAny();
3107                                         if (op.isPresent()) {
3108                                                 GroupProperty prop = op.get();
3109                                                 String heatFileNAme = prop.getValue();
3110                                                 if (null == heatFileNAme || heatFileNAme.isEmpty())
3111                                                         continue;
3112                                                 List<ArtifactDefinition> artifacts = new ArrayList();
3113                                                 for (String artifactId : artifactsGroup) {
3114                                                         Optional<ArtifactDefinition> opArt = createdArtifacts.stream().filter(p -> p.getUniqueId().equals(artifactId)).findAny();
3115                                                         if (opArt.isPresent()) {
3116                                                                 artifacts.add(opArt.get());
3117                                                         }
3118                                                         if (artifactsFromResource != null) {
3119                                                                 opArt = artifactsFromResource.stream().filter(p -> p.getUniqueId().equals(artifactId)).findAny();
3120                                                                 if (opArt.isPresent()) {
3121                                                                         artifacts.add(opArt.get());
3122                                                                 }
3123                                                         }
3124                                                 }
3125                                                 Optional<ArtifactDefinition> resOp = artifacts.stream().filter(p -> heatFileNAme.contains(p.getArtifactName())).findAny();
3126                                                 if (resOp.isPresent()) {
3127                                                         members.putAll(heatGroup.getMembers());
3128                                                 }
3129                                         }
3130                                 }
3131                         }
3132
3133                 }
3134         }
3135
3136         private Either<Resource, ResponseFormat> createDeploymentArtifactFromCsar(ImportCsarInfo importCsarInfo, String artifactPath, Resource resource, Set<String> artifactsGroup, Set<String> artifactsUUIDGroup,
3137                         ArtifactTemplateInfo artifactTemplateInfo, List<ArtifactDefinition> createdArtifacts, int labelCounter, boolean shoudLock, boolean inTransaction) {
3138                 Either<Resource, ResponseFormat> resStatus = Either.left(resource);
3139                 String artifactFileName = artifactTemplateInfo.getFileName();
3140                 String artifactUid = "";
3141                 String artifactEnvUid = "";
3142                 String artifactUUID = "";
3143                 boolean alreadyExist = false;
3144
3145                 // check if artifacts already exist
3146                 for (ArtifactDefinition createdArtifact : createdArtifacts) {
3147                         if (createdArtifact.getArtifactName().equals(artifactFileName)) {
3148                                 artifactUid = createdArtifact.getUniqueId();
3149                                 artifactUUID = createdArtifact.getArtifactUUID();
3150                                 if (!createdArtifact.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) {
3151                                         log.debug("Artifact with name {} and type {} already exist with type  {}", artifactFileName, artifactTemplateInfo.getType(), createdArtifact.getArtifactType());
3152                                         BeEcompErrorManager.getInstance().logInternalDataError("Artifact  file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
3153                                         return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName, artifactTemplateInfo.getType(), createdArtifact.getArtifactType()));
3154                                 }
3155                                 alreadyExist = true;
3156                                 artifactEnvUid = checkAndGetHeatEnvId(createdArtifact);
3157                                 break;
3158                         }
3159                 }
3160                 // if not exist need to create
3161                 if (!alreadyExist) {
3162
3163                         Either<ArtifactDefinition, ResponseFormat> newArtifactEither = createDeploymentArtifact(importCsarInfo, resource, artifactPath, artifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction);
3164                         if (newArtifactEither.isRight()) {
3165                                 resStatus = Either.right(newArtifactEither.right().value());
3166                                 return resStatus;
3167                         }
3168                         ArtifactDefinition newArtifact = newArtifactEither.left().value();
3169                         artifactUid = newArtifact.getUniqueId();
3170                         artifactUUID = newArtifact.getArtifactUUID();
3171
3172                         ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(newArtifact.getArtifactType());
3173                         if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_VOL) {
3174                                 Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactsBusinessLogic.createHeatEnvPlaceHolder(newArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME, resource.getUniqueId(), NodeTypeEnum.Resource,
3175                                                 resource.getName(), importCsarInfo.getModifier(), resource, null);
3176                                 if (createHeatEnvPlaceHolder.isRight()) {
3177                                         return Either.right(createHeatEnvPlaceHolder.right().value());
3178                                 }
3179                                 artifactEnvUid = createHeatEnvPlaceHolder.left().value().getUniqueId();
3180                         }
3181                 }
3182
3183                 artifactsGroup.add(artifactUid);
3184                 artifactsUUIDGroup.add(artifactUUID);
3185                 if (!artifactEnvUid.isEmpty()) {
3186                         artifactsGroup.add(artifactEnvUid);
3187                 }
3188
3189                 List<ArtifactTemplateInfo> relatedArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo();
3190                 if (relatedArtifacts != null) {
3191                         for (ArtifactTemplateInfo relatedArtifactTemplateInfo : relatedArtifacts) {
3192                                 resStatus = createDeploymentArtifactFromCsar(importCsarInfo, artifactPath, resource, artifactsGroup, artifactsUUIDGroup, relatedArtifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction);
3193                                 if (resStatus.isRight())
3194                                         return resStatus;
3195                         }
3196                 }
3197                 return resStatus;
3198         }
3199
3200         private String checkAndGetHeatEnvId(ArtifactDefinition createdArtifact) {
3201                 String artifactEnvUid = "";
3202                 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(createdArtifact.getArtifactType());
3203                 if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_VOL) {
3204                         artifactEnvUid = createdArtifact.getUniqueId() + ArtifactsBusinessLogic.HEAT_ENV_SUFFIX;
3205                 }
3206                 return artifactEnvUid;
3207         }
3208
3209         private Either<ArtifactDefinition, ResponseFormat> createDeploymentArtifact(ImportCsarInfo importCsarInfo, Resource resource, String artifactPath, ArtifactTemplateInfo artifactTemplateInfo,
3210                         List<ArtifactDefinition> createdArtifacts, int labelCounter, boolean shoudLock, boolean inTransaction) {
3211                 final String artifactFileName = artifactTemplateInfo.getFileName();
3212                 Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactContententStatus = CsarValidationUtils.getArtifactsContent(importCsarInfo.getCsarUUID(), importCsarInfo.getCsar(), artifactPath + artifactFileName, artifactFileName, componentsUtils);
3213                 if (artifactContententStatus.isRight()) {
3214                         return Either.right(artifactContententStatus.right().value());
3215                 }
3216                 labelCounter += createdArtifacts.size();
3217
3218                 Map<String, Object> json = buildJsonForArtifact(artifactTemplateInfo, artifactContententStatus.left().value().getValue(), labelCounter);
3219
3220                 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = createOrUpdateCsarArtifactFromJson(resource, importCsarInfo.getModifier(), json, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create),
3221                                 shoudLock, inTransaction);
3222
3223                 if (uploadArtifactToService.isRight())
3224                         return Either.right(uploadArtifactToService.right().value());
3225
3226                 ArtifactDefinition currentInfo = uploadArtifactToService.left().value().left().value();
3227                 if (currentInfo.getHeatParameters() != null) {
3228
3229                         Either<ArtifactDefinition, ResponseFormat> updateEnvEither = updateHeatParamsFromCsar(resource, importCsarInfo, artifactTemplateInfo, currentInfo, false);
3230                         if (updateEnvEither.isRight()) {
3231                                 log.debug("failed to update parameters to artifact {}", artifactFileName);
3232                                 return Either.right(updateEnvEither.right().value());
3233
3234                         }
3235                         currentInfo = updateEnvEither.left().value();
3236
3237                 }
3238
3239                 createdArtifacts.add(currentInfo);
3240
3241                 return Either.left(currentInfo);
3242
3243         }
3244
3245         private Either<ArtifactDefinition, ResponseFormat> updateDeploymentArtifactsFromCsar(ImportCsarInfo importCsarInfo, Resource resource, ArtifactDefinition oldArtifact, ArtifactTemplateInfo artifactTemplateInfo,
3246                         List<ArtifactDefinition> updatedArtifacts, List<ArtifactTemplateInfo> updatedRequiredArtifacts, boolean shouldLock, boolean inTransaction) {
3247
3248                 Either<ArtifactDefinition, ResponseFormat> resStatus = null;
3249                 String artifactFileName = artifactTemplateInfo.getFileName();
3250                 String artifactUid = "";
3251
3252                 // check if artifacts already exist
3253                 for (ArtifactDefinition updatedArtifact : updatedArtifacts) {
3254                         if (updatedArtifact.getArtifactName().equals(artifactFileName)) {
3255                                 artifactUid = updatedArtifact.getUniqueId();
3256                                 if (!updatedArtifact.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) {
3257                                         log.debug("Artifact with name {} and type {} already updated with type  {}", artifactFileName, artifactTemplateInfo.getType(), updatedArtifact.getArtifactType());
3258                                         BeEcompErrorManager.getInstance().logInternalDataError("Artifact  file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
3259                                         resStatus = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName, artifactTemplateInfo.getType(), updatedArtifact.getArtifactType()));
3260                                         return resStatus;
3261                                 }
3262                                 resStatus = Either.left(updatedArtifact);
3263                                 return resStatus;
3264                         }
3265
3266                 }
3267
3268                 Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactContententStatus = CsarValidationUtils.getArtifactsContent(importCsarInfo.getCsarUUID(), importCsarInfo.getCsar(), CsarUtils.ARTIFACTS_PATH + artifactFileName, artifactFileName, componentsUtils);
3269                 if (artifactContententStatus.isRight()) {
3270                         resStatus = Either.right(artifactContententStatus.right().value());
3271                         return resStatus;
3272                 }
3273
3274                 Map<String, Object> json = buildJsonForUpdateArtifact(oldArtifact.getUniqueId(), artifactFileName, oldArtifact.getArtifactType(), ArtifactGroupTypeEnum.DEPLOYMENT, oldArtifact.getArtifactLabel(), oldArtifact.getArtifactDisplayName(),
3275                                 oldArtifact.getDescription(), artifactContententStatus.left().value().getRight(), updatedRequiredArtifacts);
3276
3277                 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = createOrUpdateCsarArtifactFromJson(resource, importCsarInfo.getModifier(), json, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Update),
3278                                 shouldLock, inTransaction);
3279
3280                 if (uploadArtifactToService.isRight()) {
3281                         resStatus = Either.right(uploadArtifactToService.right().value());
3282                         return resStatus;
3283                 }
3284                 ArtifactDefinition currentInfo = uploadArtifactToService.left().value().left().value();
3285
3286                 Either<ArtifactDefinition, ResponseFormat> updateEnvEither = updateHeatParamsFromCsar(resource, importCsarInfo, artifactTemplateInfo, currentInfo, true);
3287                 if (updateEnvEither.isRight()) {
3288                         log.debug("failed to update parameters to artifact {}", artifactFileName);
3289                         resStatus = Either.right(updateEnvEither.right().value());
3290                         return resStatus;
3291                 }
3292                 // TODO evg update env time ( must be separate US for this!!!!)
3293
3294                 artifactUid = updateEnvEither.left().value().getUniqueId();
3295                 updatedArtifacts.add(updateEnvEither.left().value());
3296                 resStatus = Either.left(updateEnvEither.left().value());
3297
3298                 return resStatus;
3299
3300         }
3301
3302         private Either<ArtifactDefinition, ResponseFormat> updateHeatParamsFromCsar(Resource resource, ImportCsarInfo importCsarInfo, ArtifactTemplateInfo artifactTemplateInfo, ArtifactDefinition currentInfo, boolean isUpdateEnv) {
3303                 Either<ArtifactDefinition, ResponseFormat> resStatus = Either.left(currentInfo);
3304                 if (artifactTemplateInfo.getEnv() != null && !artifactTemplateInfo.getEnv().isEmpty()) {
3305
3306                         Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactparamsStatus = CsarValidationUtils.getArtifactsContent(importCsarInfo.getCsarUUID(), importCsarInfo.getCsar(), CsarUtils.ARTIFACTS_PATH + artifactTemplateInfo.getEnv(), artifactTemplateInfo.getEnv(),
3307                                         componentsUtils);
3308                         if (artifactparamsStatus.isRight()) {
3309                                 resStatus = Either.right(artifactparamsStatus.right().value());
3310                                 return resStatus;
3311                         }
3312                         Either<List<HeatParameterDefinition>, ResponseFormat> propsStatus = extractHeatParameters(ArtifactTypeEnum.HEAT_ENV.getType(), artifactTemplateInfo.getEnv(), artifactparamsStatus.left().value().getValue(), false);
3313                         /*
3314                          * if (propsStatus.isRight()) {
3315                          *
3316                          * resStatus = Either.right(propsStatus.right().value()); return resStatus; }
3317                          */
3318                         if (propsStatus.isLeft()) {
3319                                 List<HeatParameterDefinition> updatedHeatEnvParams = propsStatus.left().value();
3320                                 List<HeatParameterDefinition> currentHeatEnvParams = currentInfo.getListHeatParameters();
3321                                 // List<HeatParameterDefinition> newHeatEnvParams = new ArrayList<HeatParameterDefinition>();
3322
3323                                 if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty() && currentHeatEnvParams != null && !currentHeatEnvParams.isEmpty()) {
3324
3325                                         String paramName;
3326                                         for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
3327
3328                                                 paramName = heatEnvParam.getName();
3329                                                 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
3330                                                         if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
3331
3332                                                                 String updatedParamValue = heatEnvParam.getCurrentValue();
3333                                                                 if (updatedParamValue == null)
3334                                                                         updatedParamValue = heatEnvParam.getDefaultValue();
3335                                                                 HeatParameterType paramType = HeatParameterType.isValidType(currHeatParam.getType());
3336                                                                 if (!paramType.getValidator().isValid(updatedParamValue, null)) {
3337                                                                         ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
3338                                                                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, ArtifactTypeEnum.HEAT_ENV.getType(), paramType.getType(), paramName);
3339                                                                         resStatus = Either.right(responseFormat);
3340                                                                         return resStatus;
3341                                                                 }
3342                                                                 currHeatParam.setCurrentValue(HeatParameterType.isValidType(currHeatParam.getType()).getConverter().convert(updatedParamValue, null, null));
3343                                                                 // newHeatEnvParams.add(currHeatParam);
3344                                                                 break;
3345                                                         }
3346                                                 }
3347                                         }
3348                                         currentInfo.setListHeatParameters(currentHeatEnvParams);
3349                                         Either<ArtifactDefinition, StorageOperationStatus> updateArifactOnResource = artifactToscaOperation.updateArifactOnResource(currentInfo, resource.getUniqueId(), currentInfo.getUniqueId(), null, null);
3350                                         if (updateArifactOnResource.isRight()) {
3351                                                 log.debug("Failed to update heat paratemers of heat on CSAR flow for component {} artifact {} label {}", resource.getUniqueId(), currentInfo.getUniqueId(), currentInfo.getArtifactLabel());
3352                                                 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactOnResource.right().value())));
3353                                         }
3354                                         resStatus = Either.left(updateArifactOnResource.left().value());
3355                                 }
3356                         }
3357                 }
3358                 if (isUpdateEnv) {
3359                         Map<String, ArtifactDefinition> artifacts = resource.getDeploymentArtifacts();
3360                         Optional<ArtifactDefinition> op = artifacts.values().stream().filter(p -> p.getGeneratedFromId() != null && p.getGeneratedFromId().equals(currentInfo.getUniqueId())).findAny();
3361                         if (op.isPresent()) {
3362                                 ArtifactDefinition artifactInfoHeatEnv = op.get();
3363                                 Either<ArtifactDefinition, StorageOperationStatus> updateArifactOnResource = artifactToscaOperation.updateArifactOnResource(artifactInfoHeatEnv, resource.getUniqueId(), artifactInfoHeatEnv.getUniqueId(), null, null);
3364                                 if (updateArifactOnResource.isRight()) {
3365                                         log.debug("Failed to update heat env on CSAR flow for component {} artifact {} label {}", resource.getUniqueId(), artifactInfoHeatEnv.getUniqueId(), artifactInfoHeatEnv.getArtifactLabel());
3366                                         return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactOnResource.right().value())));
3367                                 }
3368                         }
3369                 }
3370                 return resStatus;
3371         }
3372
3373         private Either<List<HeatParameterDefinition>, ResponseFormat> extractHeatParameters(String artifactType, String fileName, byte[] content, boolean is64Encoded) {
3374                 // extract heat parameters
3375                 String heatDecodedPayload = is64Encoded ? new String(Base64.decodeBase64(content)) : new String(content);
3376                 Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParamsWithoutImplicitTypes(heatDecodedPayload, artifactType);
3377                 if (heatParameters.isRight()) {
3378                         log.debug("File {} is not in expected key-value form in csar ", fileName);
3379                         BeEcompErrorManager.getInstance().logInternalDataError("File " + fileName + " is not in expected key-value form in csar ", "CSAR internals are invalid", ErrorSeverity.ERROR);
3380                         return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, fileName));
3381
3382                 }
3383                 return Either.left(heatParameters.left().value());
3384
3385         }
3386
3387         private Map<String, Object> buildJsonForArtifact(ArtifactTemplateInfo artifactTemplateInfo, byte[] artifactContentent, int atrifactLabelCounter) {
3388
3389                 Map<String, Object> json = new HashMap<String, Object>();
3390                 String artifactName = artifactTemplateInfo.getFileName();
3391
3392                 json.put(Constants.ARTIFACT_NAME, artifactTemplateInfo.getFileName());
3393                 json.put(Constants.ARTIFACT_TYPE, artifactTemplateInfo.getType());
3394                 json.put(Constants.ARTIFACT_DESCRIPTION, "created from csar");
3395
3396                 // DE250204: There is no need to check if base64 encoding.
3397
3398                 // String encodedPayload = new String(artifactContentent);
3399                 // boolean isEncoded = GeneralUtility.isBase64Encoded(artifactContentent);
3400                 // if (!isEncoded) {
3401                 String encodedPayload = Base64.encodeBase64String(artifactContentent);
3402                 // }
3403                 json.put(Constants.ARTIFACT_PAYLOAD_DATA, encodedPayload);
3404                 String displayName = artifactName;
3405                 if (artifactName.lastIndexOf(".") > 0)
3406                         displayName = artifactName.substring(0, artifactName.lastIndexOf("."));
3407                 json.put(Constants.ARTIFACT_DISPLAY_NAME, displayName);
3408                 String label = ValidationUtils.normalizeArtifactLabel(artifactTemplateInfo.getType() + atrifactLabelCounter);
3409                 json.put(Constants.ARTIFACT_LABEL, label);
3410                 json.put(Constants.ARTIFACT_GROUP_TYPE, ArtifactGroupTypeEnum.DEPLOYMENT.getType());
3411                 List<ArtifactTemplateInfo> requiredArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo();
3412                 json.put(Constants.REQUIRED_ARTIFACTS, (requiredArtifacts == null || requiredArtifacts.isEmpty()) ? new ArrayList<>()
3413                                 : requiredArtifacts.stream().filter(e -> e.getType().equals(ArtifactTypeEnum.HEAT_ARTIFACT.getType()) || e.getType().equals(ArtifactTypeEnum.HEAT_NESTED.getType())).map(e -> e.getFileName()).collect(Collectors.toList()));
3414                 return json;
3415         }
3416
3417         private Map<String, Object> buildJsonForUpdateArtifact(String artifactId, String artifactName, String artifactType, ArtifactGroupTypeEnum artifactGroupType, String label, String displayName, String description, byte[] artifactContentent,
3418                         List<ArtifactTemplateInfo> updatedRequiredArtifacts) {
3419
3420                 Map<String, Object> json = new HashMap<String, Object>();
3421                 if (artifactId != null && !artifactId.isEmpty())
3422                         json.put(Constants.ARTIFACT_ID, artifactId);
3423
3424                 json.put(Constants.ARTIFACT_NAME, artifactName);
3425                 json.put(Constants.ARTIFACT_TYPE, artifactType);
3426                 json.put(Constants.ARTIFACT_DESCRIPTION, description);
3427
3428                 String encodedPayload = new String(artifactContentent);
3429
3430                 // boolean isEncoded = GeneralUtility.isBase64Encoded(artifactContentent);
3431                 // if (!isEncoded) {
3432                 log.debug("payload is encoded. perform decode");
3433                 encodedPayload = Base64.encodeBase64String(artifactContentent);
3434                 // }
3435
3436                 json.put(Constants.ARTIFACT_PAYLOAD_DATA, encodedPayload);
3437                 json.put(Constants.ARTIFACT_DISPLAY_NAME, displayName);
3438                 json.put(Constants.ARTIFACT_LABEL, label);
3439                 json.put(Constants.ARTIFACT_GROUP_TYPE, artifactGroupType.getType());
3440                 json.put(Constants.REQUIRED_ARTIFACTS, (updatedRequiredArtifacts == null || updatedRequiredArtifacts.isEmpty()) ? new ArrayList<>()
3441                                 : updatedRequiredArtifacts.stream().filter(e -> e.getType().equals(ArtifactTypeEnum.HEAT_ARTIFACT.getType()) || e.getType().equals(ArtifactTypeEnum.HEAT_NESTED.getType())).map(e -> e.getFileName()).collect(Collectors.toList()));
3442                 return json;
3443         }
3444
3445         private Either<Map<String, List<ArtifactTemplateInfo>>, ResponseFormat> parseResourceArtifactsInfoFromFile(Resource resource, String artifactsMetaFile, String artifactFileName, User user) {
3446
3447                 try {
3448                         JsonObject jsonElement = new JsonObject();
3449                         jsonElement = gson.fromJson(artifactsMetaFile, jsonElement.getClass());
3450
3451                         JsonElement importStructureElement = jsonElement.get(Constants.IMPORT_STRUCTURE);
3452                         if (importStructureElement == null || importStructureElement.isJsonNull()) {
3453                                 log.debug("Artifact  file is not in expected formatr, fileName  {}", artifactFileName);
3454                                 BeEcompErrorManager.getInstance().logInternalDataError("Artifact  file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
3455                                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName));
3456                         }
3457
3458                         Map<String, List<Map<String, Object>>> artifactTemplateMap = new HashMap<String, List<Map<String, Object>>>();
3459                         artifactTemplateMap = componentsUtils.parseJsonToObject(importStructureElement.toString(), HashMap.class);
3460                         if (artifactTemplateMap.isEmpty()) {
3461                                 log.debug("Artifact  file is not in expected formatr, fileName  {}", artifactFileName);
3462                                 BeEcompErrorManager.getInstance().logInternalDataError("Artifact  file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
3463                                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName));
3464                         }
3465
3466                         Set<String> artifactsTypeKeys = artifactTemplateMap.keySet();
3467                         Map<String, List<ArtifactTemplateInfo>> artifactsMap = new HashMap<String, List<ArtifactTemplateInfo>>();
3468                         List<ArtifactTemplateInfo> allGroups = new ArrayList<>();
3469                         for (String artifactsTypeKey : artifactsTypeKeys) {
3470
3471                                 List<Map<String, Object>> o = artifactTemplateMap.get(artifactsTypeKey);
3472                                 Either<List<ArtifactTemplateInfo>, ResponseFormat> artifactTemplateInfoListPairStatus = createArtifactTemplateInfoModule(artifactsTypeKey, o);
3473                                 if (artifactTemplateInfoListPairStatus.isRight()) {
3474                                         log.debug("Artifact  file is not in expected formatr, fileName  {}", artifactFileName);
3475                                         BeEcompErrorManager.getInstance().logInternalDataError("Artifact  file is not in expected format, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
3476                                         return Either.right(artifactTemplateInfoListPairStatus.right().value());
3477                                 }
3478                                 List<ArtifactTemplateInfo> artifactTemplateInfoList = artifactTemplateInfoListPairStatus.left().value();
3479                                 if (artifactTemplateInfoList == null) {
3480                                         log.debug("Artifact  file is not in expected formatr, fileName  {}", artifactFileName);
3481                                         BeEcompErrorManager.getInstance().logInternalDataError("Artifact  file is not in expected format, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
3482                                         return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName));
3483
3484                                 }
3485                                 allGroups.addAll(artifactTemplateInfoList);
3486                                 artifactsMap.put(artifactsTypeKey, artifactTemplateInfoList);
3487                         }
3488                         int counter = groupBusinessLogic.getNextVfModuleNameCounter(resource.getGroups());
3489                         Either<Boolean, ResponseFormat> validateGroupNamesRes = groupBusinessLogic.validateGenerateVfModuleGroupNames(allGroups, resource.getSystemName(), counter);
3490                         if (validateGroupNamesRes.isRight()) {
3491                                 return Either.right(validateGroupNamesRes.right().value());
3492                         }
3493                         return Either.left(artifactsMap);
3494                 } catch (Exception e) {
3495                         log.debug("Artifact  file is not in expected format, fileName  {}", artifactFileName);
3496                         log.debug("failed with exception.", e);
3497                         BeEcompErrorManager.getInstance().logInternalDataError("Artifact  file is not in expected format, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
3498                         return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName));
3499                 }
3500
3501         }
3502
3503         private Either<List<ArtifactTemplateInfo>, ResponseFormat> createArtifactTemplateInfoModule(String artifactsTypeKey, List<Map<String, Object>> jsonObject) {
3504                 List<ArtifactTemplateInfo> artifactTemplateInfoList = new ArrayList<ArtifactTemplateInfo>();
3505                 for (Map<String, Object> o : jsonObject) {
3506                         Either<ArtifactTemplateInfo, ResponseFormat> artifacttemplateInfoStatus = ArtifactTemplateInfo.createArtifactTemplateInfoFromJson(componentsUtils, artifactsTypeKey, o, artifactTemplateInfoList, null);
3507                         if (artifacttemplateInfoStatus.isRight()) {
3508                                 return Either.right(artifacttemplateInfoStatus.right().value());
3509                         }
3510
3511                         ArtifactTemplateInfo artifacttemplateInfo = artifacttemplateInfoStatus.left().value();
3512                         if (artifacttemplateInfo != null) {
3513                                 artifactTemplateInfoList.add(artifacttemplateInfo);
3514                         }
3515
3516                 }
3517                 return Either.left(artifactTemplateInfoList);
3518         }
3519
3520         private Either<Resource, ResponseFormat> createResourceInstancesRelations(User user, String yamlName, Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, boolean inTransaction, boolean needLock) {
3521                 log.debug("createResourceInstancesRelations try to create relations ");
3522                 List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
3523                 if (uploadResInstancesMap == null) {
3524                         log.debug("UploadComponentInstanceInfo is empty, fileName  {}", yamlName);
3525                         BeEcompErrorManager.getInstance().logInternalDataError("UploadComponentInstanceInfo is emty, fileName  {}", yamlName, ErrorSeverity.ERROR);
3526
3527                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3528                         return Either.right(responseFormat);
3529                 }
3530
3531                 if (componentInstancesList == null || componentInstancesList.isEmpty()) {
3532                         log.debug("componentInstancesList is empty in resource {} ", resource.getUniqueId());
3533                         BeEcompErrorManager.getInstance().logInternalDataError("componentInstancesList is empty in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR);
3534
3535                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3536                         return Either.right(responseFormat);
3537                 }
3538
3539                 log.debug("Before validateAndUpdatePropertyValue");
3540                 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
3541                 if (allDataTypes.isRight()) {
3542                         TitanOperationStatus status = allDataTypes.right().value();
3543                         BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
3544                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status)), yamlName);
3545
3546                 }
3547
3548                 Map<String, List<ComponentInstanceProperty>> instProperties = new HashMap<>();
3549                 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties = new HashMap<>();
3550                 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements = new HashMap<>();
3551                 Map<String, Map<String, ArtifactDefinition>> instArtifacts = new HashMap<>();
3552                 Map<String, List<PropertyDefinition>> instAttributes = new HashMap<>();
3553                 Map<String, Resource> originCompMap = new HashMap<>();
3554                 List<RequirementCapabilityRelDef> relations = new ArrayList<>();
3555
3556                 Map<String, List<ComponentInstanceInput>> instInputs = new HashMap<>();
3557
3558                 for (Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) {
3559                         UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
3560                         ComponentInstance currentCompInstance = null;
3561                         for (ComponentInstance compInstance : componentInstancesList) {
3562
3563                                 if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
3564                                         currentCompInstance = compInstance;
3565                                         break;
3566                                 }
3567
3568                         }
3569                         if (currentCompInstance == null) {
3570                                 log.debug("component instance with name {}  in resource {} ", uploadComponentInstanceInfo.getName(), resource.getUniqueId());
3571                                 BeEcompErrorManager.getInstance().logInternalDataError("component instance with name " + uploadComponentInstanceInfo.getName() + "  in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR);
3572                                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3573                                 return Either.right(responseFormat);
3574                         }
3575                         String resourceInstanceId = currentCompInstance.getUniqueId();
3576                         Resource originResource = null;
3577                         if (!originCompMap.containsKey(currentCompInstance.getComponentUid())) {
3578                                 Either<Resource, StorageOperationStatus> getPropertyRes = toscaOperationFacade.getToscaFullElement(currentCompInstance.getComponentUid());
3579                                 if (getPropertyRes.isRight()) {
3580                                         log.debug("failed to find properties of resource {} status is {}", currentCompInstance.getComponentUid(), getPropertyRes);
3581                                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getPropertyRes.right().value()), yamlName);
3582                                         return Either.right(responseFormat);
3583                                 }
3584                                 originResource = getPropertyRes.left().value();
3585                                 originCompMap.put(originResource.getUniqueId(), originResource);
3586                         } else {
3587                                 originResource = originCompMap.get(currentCompInstance.getComponentUid());
3588                         }
3589                         if (originResource.getCapabilities() != null && !originResource.getCapabilities().isEmpty()) {
3590                                 Map<String, List<CapabilityDefinition>> originCapabilities ;
3591                                 if (MapUtils.isNotEmpty(uploadComponentInstanceInfo.getCapabilitiesNamesToUpdate()) && resource.getResourceType() == ResourceTypeEnum.CVFC) {
3592                                         originCapabilities = new HashMap<>(); 
3593                                         originResource.getCapabilities().entrySet().stream().forEach(e ->{
3594                                                 List<CapabilityDefinition> list =  e.getValue().stream().map(l -> new CapabilityDefinition(l)).collect(Collectors.toList()); 
3595                                                 originCapabilities.put(e.getKey(), list);
3596                                         });
3597                                         for (List<CapabilityDefinition> capabilities : originCapabilities.values()) {
3598                                                 capabilities.stream().filter(c -> uploadComponentInstanceInfo.getCapabilitiesNamesToUpdate().containsKey(c.getName())).forEach(c -> c.setName(uploadComponentInstanceInfo.getCapabilitiesNamesToUpdate().get(c.getName())));
3599                                         }
3600                                 }else{
3601                                         originCapabilities = originResource.getCapabilities();
3602                                 }
3603                                 instCapabilties.put(currentCompInstance, originCapabilities);
3604                         }
3605                         if (originResource.getRequirements() != null && !originResource.getRequirements().isEmpty()) {
3606                                 Map<String, List<RequirementDefinition>> originRequirements; 
3607                                 if (MapUtils.isNotEmpty(uploadComponentInstanceInfo.getRequirementsNamesToUpdate()) && resource.getResourceType() == ResourceTypeEnum.CVFC) {
3608                                         originRequirements = new HashMap<>();
3609                                         originResource.getRequirements().entrySet().stream().forEach(e ->{
3610                                                 List<RequirementDefinition> list =  e.getValue().stream().map(l -> new RequirementDefinition(l)).collect(Collectors.toList()); 
3611                                                 originRequirements.put(e.getKey(), list);
3612                                         });
3613                                         for (List<RequirementDefinition> requirements : originRequirements.values()) {
3614                                                 requirements.stream().filter(r -> uploadComponentInstanceInfo.getRequirementsNamesToUpdate().containsKey(r.getName())).forEach(r -> r.setName(uploadComponentInstanceInfo.getRequirementsNamesToUpdate().get(r.getName())));
3615                                         }
3616                                 }else{
3617                                         originRequirements = originResource.getRequirements();
3618                                 }
3619                                 instRequirements.put(currentCompInstance, originRequirements);
3620                         }
3621                         if (originResource.getDeploymentArtifacts() != null && !originResource.getDeploymentArtifacts().isEmpty())
3622                                 instArtifacts.put(resourceInstanceId, originResource.getDeploymentArtifacts());
3623                         if (originResource.getAttributes() != null && !originResource.getAttributes().isEmpty())
3624                                 instAttributes.put(resourceInstanceId, originResource.getAttributes());
3625                         if (originResource.getResourceType() != ResourceTypeEnum.CVFC) {
3626                                 ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, resource, originResource, currentCompInstance, yamlName, instProperties, allDataTypes.left().value());
3627                                 if (addPropertiesValueToRiRes.getStatus() != 200) {
3628                                         return Either.right(addPropertiesValueToRiRes);
3629                                 }
3630                         } else {
3631                                 // TO DO
3632                                 ResponseFormat addInputValueToRiRes = addInputsValuesToRi(uploadComponentInstanceInfo, resource, originResource, currentCompInstance, yamlName, instInputs, allDataTypes.left().value());
3633                                 if (addInputValueToRiRes.getStatus() != 200) {
3634                                         return Either.right(addInputValueToRiRes);
3635                                 }
3636                         }
3637                 }
3638
3639                 Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade.associateComponentInstancePropertiesToComponent(instProperties, resource.getUniqueId());
3640                 if (addPropToInst.isRight()) {
3641                         log.debug("failed to associate properties of resource {} status is {}", resource.getUniqueId(), addPropToInst.right().value());
3642                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName);
3643                         return Either.right(responseFormat);
3644                 }
3645                 if (instInputs != null && !instInputs.isEmpty()) {
3646                         Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addInputToInst = toscaOperationFacade.associateComponentInstanceInputsToComponent(instInputs, resource.getUniqueId());
3647                         if (addInputToInst.isRight()) {
3648                                 log.debug("failed to associate inputs value of resource {} status is {}", resource.getUniqueId(), addInputToInst.right().value());
3649                                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addInputToInst.right().value()), yamlName);
3650                                 return Either.right(responseFormat);
3651                         }
3652                 }
3653                 StorageOperationStatus addArtToInst = toscaOperationFacade.associateArtifactToInstances(instArtifacts, resource.getUniqueId(), user);
3654                 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
3655                         log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
3656                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
3657                         return Either.right(responseFormat);
3658                 }
3659
3660                 addArtToInst = toscaOperationFacade.associateCalculatedCapReq(instCapabilties, instRequirements, resource.getUniqueId());
3661                 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
3662                         log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(), addArtToInst);
3663                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
3664                         return Either.right(responseFormat);
3665                 }
3666
3667                 addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes, resource.getUniqueId());
3668                 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
3669                         log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(), addArtToInst);
3670                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
3671                         return Either.right(responseFormat);
3672                 }
3673
3674                 ComponentParametersView parametersView = new ComponentParametersView();
3675                 parametersView.disableAll();
3676                 parametersView.setIgnoreComponentInstances(false);
3677                 parametersView.setIgnoreComponentInstancesProperties(false);
3678                 parametersView.setIgnoreCapabilities(false);
3679                 parametersView.setIgnoreRequirements(false);
3680
3681                 Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId(), parametersView);
3682
3683                 if (eitherGerResource.isRight()) {
3684                         ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
3685
3686                         return Either.right(responseFormat);
3687
3688                 }
3689
3690                 resource = eitherGerResource.left().value();
3691
3692                 for (Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) {
3693                         UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
3694                         ComponentInstance currentCompInstance = null;
3695                         for (ComponentInstance compInstance : componentInstancesList) {
3696
3697                                 if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
3698                                         currentCompInstance = compInstance;
3699                                         break;
3700                                 }
3701
3702                         }
3703                         if (currentCompInstance == null) {
3704                                 log.debug("component instance with name {}  in resource {} ", uploadComponentInstanceInfo.getName(), resource.getUniqueId());
3705                                 BeEcompErrorManager.getInstance().logInternalDataError("component instance with name " + uploadComponentInstanceInfo.getName() + "  in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR);
3706                                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3707                                 return Either.right(responseFormat);
3708                         }
3709
3710                         ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, resource, entry.getValue(), relations);
3711                         if (addRelationToRiRes.getStatus() != 200) {
3712                                 return Either.right(addRelationToRiRes);
3713                         }
3714                 }
3715
3716                 addArtToInst = toscaOperationFacade.associateResourceInstances(resource.getUniqueId(), relations);
3717                 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
3718                         log.debug("failed to associate instances of resource {} status is {}", resource.getUniqueId(), addArtToInst);
3719                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
3720                         return Either.right(responseFormat);
3721                 }
3722
3723                 log.debug("************* in create relations, getResource start");
3724
3725                 eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
3726                 log.debug("************* in create relations, getResource end");
3727                 if (eitherGerResource.isRight()) {
3728                         ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
3729
3730                         return Either.right(responseFormat);
3731
3732                 }
3733                 return Either.left(eitherGerResource.left().value());
3734         }
3735
3736         private ResponseFormat addRelationToRI(String yamlName, Resource resource, UploadComponentInstanceInfo nodesInfoValue, List<RequirementCapabilityRelDef> relations) {
3737                 List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
3738                 long totalCreateRel = 0;
3739                 long totalCreatePropVal = 0;
3740
3741                 UploadComponentInstanceInfo uploadComponentInstanceInfo = nodesInfoValue;
3742
3743                 ComponentInstance currentCompInstance = null;
3744
3745                 for (ComponentInstance compInstance : componentInstancesList) {
3746
3747                         if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
3748                                 currentCompInstance = compInstance;
3749                                 break;
3750                         }
3751
3752                 }
3753
3754                 if (currentCompInstance == null) {
3755                         log.debug("component instance with name {}  in resource {} ", uploadComponentInstanceInfo.getName(), resource.getUniqueId());
3756                         BeEcompErrorManager.getInstance().logInternalDataError("component instance with name " + uploadComponentInstanceInfo.getName() + "  in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR);
3757                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3758                         return responseFormat;
3759                 }
3760                 String resourceInstanceId = currentCompInstance.getUniqueId();
3761
3762                 Map<String, List<UploadReqInfo>> regMap = uploadComponentInstanceInfo.getRequirements();
3763
3764                 if (regMap != null) {
3765                         Iterator<Entry<String, List<UploadReqInfo>>> nodesRegValue = regMap.entrySet().iterator();
3766
3767                         long startAddRelation = System.currentTimeMillis();
3768
3769                         while (nodesRegValue.hasNext()) {
3770                                 Entry<String, List<UploadReqInfo>> nodesRegInfoEntry = nodesRegValue.next();
3771
3772                                 List<UploadReqInfo> uploadRegInfoList = nodesRegInfoEntry.getValue();
3773                                 for (UploadReqInfo uploadRegInfo : uploadRegInfoList) {
3774                                         log.debug("Going to create  relation {}", uploadRegInfo.getName());
3775                                         String regName = uploadRegInfo.getName();
3776                                         RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef();
3777                                         regCapRelDef.setFromNode(resourceInstanceId);
3778                                         log.debug("try to find available requirement {} ", regName);
3779                                         Either<RequirementDefinition, ResponseFormat> eitherReqStatus = findAviableRequiremen(regName, yamlName, uploadComponentInstanceInfo, currentCompInstance, uploadRegInfo.getCapabilityName());
3780                                         if (eitherReqStatus.isRight()) {
3781                                                 log.debug("failed to find available requirement {} status is {}", regName, eitherReqStatus.right().value());
3782                                                 return eitherReqStatus.right().value();
3783                                         }
3784
3785                                         RequirementDefinition validReq = eitherReqStatus.left().value();
3786                                         List<RequirementAndRelationshipPair> reqAndRelationshipPairList = regCapRelDef.getRelationships();
3787                                         if (reqAndRelationshipPairList == null)
3788                                                 reqAndRelationshipPairList = new ArrayList<RequirementAndRelationshipPair>();
3789                                         RequirementAndRelationshipPair reqAndRelationshipPair = new RequirementAndRelationshipPair();
3790                                         reqAndRelationshipPair.setRequirement(regName);
3791                                         reqAndRelationshipPair.setRequirementOwnerId(validReq.getOwnerId());
3792                                         reqAndRelationshipPair.setRequirementUid(validReq.getUniqueId());
3793                                         RelationshipImpl relationship = new RelationshipImpl();
3794                                         relationship.setType(validReq.getCapability());
3795                                         reqAndRelationshipPair.setRelationships(relationship);
3796
3797                                         ComponentInstance currentCapCompInstance = null;
3798                                         for (ComponentInstance compInstance : componentInstancesList) {
3799                                                 if (compInstance.getName().equals(uploadRegInfo.getNode())) {
3800                                                         currentCapCompInstance = compInstance;
3801                                                         break;
3802                                                 }
3803                                         }
3804
3805                                         if (currentCapCompInstance == null) {
3806                                                 log.debug("The component instance  with name {} not found on resource {} ", uploadRegInfo.getNode(), resource.getUniqueId());
3807                                                 BeEcompErrorManager.getInstance().logInternalDataError("component instance with name " + uploadRegInfo.getNode() + "  in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR);
3808                                                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3809                                                 return responseFormat;
3810                                         }
3811                                         regCapRelDef.setToNode(currentCapCompInstance.getUniqueId());
3812                                         log.debug("try to find aviable Capability  req name is {} ", validReq.getName());
3813                                         CapabilityDefinition aviableCapForRel = findAvailableCapabilityByTypeOrName(validReq, currentCapCompInstance, uploadRegInfo);
3814                                         if (aviableCapForRel == null) {
3815                                                 log.debug("aviable capability was not found. req name is {} component instance is {}", validReq.getName(), currentCapCompInstance.getUniqueId());
3816                                                 BeEcompErrorManager.getInstance().logInternalDataError("aviable capability was not found. req name is " + validReq.getName() + " component instance is " + currentCapCompInstance.getUniqueId(), resource.getUniqueId(),
3817                                                                 ErrorSeverity.ERROR);
3818                                                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3819                                                 return responseFormat;
3820                                         }
3821                                         reqAndRelationshipPair.setCapability(aviableCapForRel.getName());
3822                                         reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId());
3823                                         reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId());
3824                                         reqAndRelationshipPairList.add(reqAndRelationshipPair);
3825                                         regCapRelDef.setRelationships(reqAndRelationshipPairList);
3826                                         relations.add(regCapRelDef);
3827                                 }
3828                         }
3829                         totalCreateRel += (System.currentTimeMillis() - startAddRelation);
3830                 } else if (resource.getResourceType() != ResourceTypeEnum.CVFC) {
3831                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK, yamlName);
3832                         return responseFormat;
3833                 }
3834                 return componentsUtils.getResponseFormat(ActionStatus.OK);
3835         }
3836
3837         private ResponseFormat addInputsValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Resource resource, Resource originResource, ComponentInstance currentCompInstance, String yamlName,
3838                         Map<String, List<ComponentInstanceInput>> instInputs, Map<String, DataTypeDefinition> allDataTypes) {
3839                 Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
3840                 if (propMap != null && propMap.size() > 0) {
3841                         Map<String, InputDefinition> currPropertiesMap = new HashMap<String, InputDefinition>();
3842
3843                         int index = 0;
3844                         List<InputDefinition> listFromMap = originResource.getInputs();
3845                         if (listFromMap == null || listFromMap.isEmpty()) {
3846                                 log.debug("failed to find properties ");
3847                                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND);
3848                                 return responseFormat;
3849                         }
3850                         for (InputDefinition prop : listFromMap) {
3851                                 String propName = prop.getName();
3852                                 if (!currPropertiesMap.containsKey(propName)) {
3853                                         currPropertiesMap.put(propName, prop);
3854                                 }
3855                         }
3856                         List<ComponentInstanceInput> instPropList = new ArrayList<>();
3857                         for (List<UploadPropInfo> propertyList : propMap.values()) {
3858
3859                                 UploadPropInfo propertyInfo = propertyList.get(0);
3860                                 String propName = propertyInfo.getName();
3861                                 if (!currPropertiesMap.containsKey(propName)) {
3862                                         log.debug("failed to find property {} ", propName);
3863                                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName);
3864                                         return responseFormat;
3865                                 }
3866                                 InputDefinition curPropertyDef = currPropertiesMap.get(propName);
3867                                 ComponentInstanceInput property = null;
3868
3869                                 String value = null;
3870                                 List<GetInputValueDataDefinition> getInputs = null;
3871                                 boolean isValidate = true;
3872                                 if (propertyInfo.getValue() != null) {
3873                                         getInputs = propertyInfo.getGet_input();
3874                                         isValidate = getInputs == null || getInputs.isEmpty();
3875                                         if (isValidate) {
3876                                                 value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType());
3877                                         } else
3878                                                 value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), ToscaTagNamesEnum.GET_INPUT.getElementName());
3879                                 }
3880                                 String innerType = null;
3881                                 property = new ComponentInstanceInput(curPropertyDef, value, null);
3882
3883                                 Either<String, StorageOperationStatus> validatevalueEiter = validatePropValueBeforeCreate(property, value, isValidate, innerType, allDataTypes);
3884                                 if (validatevalueEiter.isRight()) {
3885                                         return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validatevalueEiter.right().value()));
3886                                 }
3887
3888                                 // String uniqueId = UniqueIdBuilder.buildResourceInstancePropertyValueUid(currentCompInstance.getComponentUid(), index++);
3889                                 // property.setUniqueId(uniqueId);
3890                                 property.setValue(validatevalueEiter.left().value());
3891
3892                                 if (getInputs != null && !getInputs.isEmpty()) {
3893                                         List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
3894                                         for (GetInputValueDataDefinition getInput : getInputs) {
3895                                                 List<InputDefinition> inputs = resource.getInputs();
3896                                                 if (inputs == null || inputs.isEmpty()) {
3897                                                         log.debug("Failed to add property {} to resource instance {}. Inputs list is empty ", property, currentCompInstance.getUniqueId());
3898                                                         return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
3899                                                 }
3900
3901                                                 Optional<InputDefinition> optional = inputs.stream().filter(p -> p.getName().equals(getInput.getInputName())).findAny();
3902                                                 if (!optional.isPresent()) {
3903                                                         log.debug("Failed to find input {} ", getInput.getInputName());
3904                                                         // @@TODO error message
3905                                                         return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
3906                                                 }
3907                                                 InputDefinition input = optional.get();
3908                                                 getInput.setInputId(input.getUniqueId());
3909                                                 getInputValues.add(getInput);
3910
3911                                                 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
3912                                                 if (getInputIndex != null) {
3913                                                         optional = inputs.stream().filter(p -> p.getName().equals(getInputIndex.getInputName())).findAny();
3914                                                         if (!optional.isPresent()) {
3915                                                                 log.debug("Failed to find input {} ", getInputIndex.getInputName());
3916                                                                 // @@TODO error message
3917                                                                 return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
3918                                                         }
3919                                                         InputDefinition inputIndex = optional.get();
3920                                                         getInputIndex.setInputId(inputIndex.getUniqueId());
3921                                                         getInputValues.add(getInputIndex);
3922                                                 }
3923                                         }
3924                                         property.setGetInputValues(getInputValues);
3925                                 }
3926                                 instPropList.add(property);
3927                                 // delete overriden property
3928                                 currPropertiesMap.remove(property.getName());
3929                         }
3930                         // add rest of properties
3931                         if (!currPropertiesMap.isEmpty()) {
3932                                 for (InputDefinition value : currPropertiesMap.values()) {
3933                                         instPropList.add(new ComponentInstanceInput(value));
3934                                 }
3935                         }
3936                         instInputs.put(currentCompInstance.getUniqueId(), instPropList);
3937                 }
3938                 return componentsUtils.getResponseFormat(ActionStatus.OK);
3939         }
3940
3941         private ResponseFormat addPropertyValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Resource resource, Resource originResource, ComponentInstance currentCompInstance, String yamlName,
3942                         Map<String, List<ComponentInstanceProperty>> instProperties, Map<String, DataTypeDefinition> allDataTypes) {
3943
3944                 Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
3945                 if (propMap != null && propMap.size() > 0) {
3946                         Map<String, PropertyDefinition> currPropertiesMap = new HashMap<String, PropertyDefinition>();
3947
3948                         int index = 0;
3949                         List<PropertyDefinition> listFromMap = originResource.getProperties();
3950                         if (listFromMap == null || listFromMap.isEmpty()) {
3951                                 log.debug("failed to find properties ");
3952                                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND);
3953                                 return responseFormat;
3954                         }
3955                         for (PropertyDefinition prop : listFromMap) {
3956                                 String propName = prop.getName();
3957                                 if (!currPropertiesMap.containsKey(propName)) {
3958                                         currPropertiesMap.put(propName, prop);
3959                                 }
3960                         }
3961                         List<ComponentInstanceProperty> instPropList = new ArrayList<>();
3962                         for (List<UploadPropInfo> propertyList : propMap.values()) {
3963
3964                                 UploadPropInfo propertyInfo = propertyList.get(0);
3965                                 String propName = propertyInfo.getName();
3966                                 if (!currPropertiesMap.containsKey(propName)) {
3967                                         log.debug("failed to find property {} ", propName);
3968                                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName);
3969                                         return responseFormat;
3970                                 }
3971                                 PropertyDefinition curPropertyDef = currPropertiesMap.get(propName);
3972                                 ComponentInstanceProperty property = null;
3973
3974                                 String value = null;
3975                                 List<GetInputValueDataDefinition> getInputs = null;
3976                                 boolean isValidate = true;
3977                                 if (propertyInfo.getValue() != null) {
3978                                         getInputs = propertyInfo.getGet_input();
3979                                         isValidate = getInputs == null || getInputs.isEmpty();
3980                                         if (isValidate) {
3981                                                 value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType());
3982                                         } else
3983                                                 value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), ToscaTagNamesEnum.GET_INPUT.getElementName());
3984                                 }
3985                                 String innerType = null;
3986                                 property = new ComponentInstanceProperty(curPropertyDef, value, null);
3987
3988                                 Either<String, StorageOperationStatus> validatevalueEiter = validatePropValueBeforeCreate(property, value, isValidate, innerType, allDataTypes);
3989                                 if (validatevalueEiter.isRight()) {
3990                                         return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validatevalueEiter.right().value()));
3991                                 }
3992
3993                                 // String uniqueId = UniqueIdBuilder.buildResourceInstancePropertyValueUid(currentCompInstance.getComponentUid(), index++);
3994                                 // property.setUniqueId(uniqueId);
3995                                 property.setValue(validatevalueEiter.left().value());
3996
3997                                 if (getInputs != null && !getInputs.isEmpty()) {
3998                                         List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
3999                                         for (GetInputValueDataDefinition getInput : getInputs) {
4000                                                 List<InputDefinition> inputs = resource.getInputs();
4001                                                 if (inputs == null || inputs.isEmpty()) {
4002                                                         log.debug("Failed to add property {} to resource instance {}. Inputs list is empty ", property, currentCompInstance.getUniqueId());
4003                                                         return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
4004                                                 }
4005
4006                                                 Optional<InputDefinition> optional = inputs.stream().filter(p -> p.getName().equals(getInput.getInputName())).findAny();
4007                                                 if (!optional.isPresent()) {
4008                                                         log.debug("Failed to find input {} ", getInput.getInputName());
4009                                                         // @@TODO error message
4010                                                         return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
4011                                                 }
4012                                                 InputDefinition input = optional.get();
4013                                                 getInput.setInputId(input.getUniqueId());
4014                                                 getInputValues.add(getInput);
4015
4016                                                 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
4017                                                 if (getInputIndex != null) {
4018                                                         optional = inputs.stream().filter(p -> p.getName().equals(getInputIndex.getInputName())).findAny();
4019                                                         if (!optional.isPresent()) {
4020                                                                 log.debug("Failed to find input {} ", getInputIndex.getInputName());
4021                                                                 // @@TODO error message
4022                                                                 return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
4023                                                         }
4024                                                         InputDefinition inputIndex = optional.get();
4025                                                         getInputIndex.setInputId(inputIndex.getUniqueId());
4026                                                         getInputValues.add(getInputIndex);
4027
4028                                                 }
4029
4030                                         }
4031                                         property.setGetInputValues(getInputValues);
4032                                 }
4033                                 instPropList.add(property);
4034                                 // delete overriden property
4035                                 currPropertiesMap.remove(property.getName());
4036                         }
4037                         // add rest of properties
4038                         if (!currPropertiesMap.isEmpty()) {
4039                                 for (PropertyDefinition value : currPropertiesMap.values()) {
4040                                         instPropList.add(new ComponentInstanceProperty(value));
4041                                 }
4042                         }
4043                         instProperties.put(currentCompInstance.getUniqueId(), instPropList);
4044                 }
4045                 return componentsUtils.getResponseFormat(ActionStatus.OK);
4046         }
4047
4048         // US740820 Relate RIs according to capability name
4049         private CapabilityDefinition findAvailableCapabilityByTypeOrName(RequirementDefinition validReq, ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
4050                 if (null == uploadReqInfo.getCapabilityName() || validReq.getCapability().equals(uploadReqInfo.getCapabilityName())) {// get
4051                         // by
4052                         // capability
4053                         // type
4054                         return findAviableCapability(validReq, currentCapCompInstance);
4055                 }
4056                 return findAvailableCapability(validReq, currentCapCompInstance, uploadReqInfo);
4057         }
4058
4059         private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq, ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
4060                 CapabilityDefinition cap = null;
4061                 Map<String, List<CapabilityDefinition>> capMap = currentCapCompInstance.getCapabilities();
4062                 if (!capMap.containsKey(validReq.getCapability())) {
4063                         return null;
4064                 }
4065                 Optional<CapabilityDefinition> capByName = capMap.get(validReq.getCapability()).stream().filter(p -> p.getName().equals(uploadReqInfo.getCapabilityName())).findAny();
4066                 if (!capByName.isPresent()) {
4067                         return null;
4068                 }
4069                 cap = capByName.get();
4070
4071                 if (cap.getMaxOccurrences() != null && !cap.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES)) {
4072                         String leftOccurrences = cap.getLeftOccurrences();
4073                         int left = Integer.parseInt(leftOccurrences);
4074                         if (left > 0) {
4075                                 --left;
4076                                 cap.setLeftOccurrences(String.valueOf(left));
4077
4078                         }
4079
4080                 }
4081
4082                 // TODO temporary fix - remove specific capability node validation -
4083                 // String reqNode = validReq.getNode();
4084                 // if (reqNode != null && !reqNode.isEmpty() &&
4085                 // !cap.getCapabilitySources().contains(reqNode)) {
4086                 // return null;
4087                 // }
4088                 // RequirementAndRelationshipPair relationPair = getReqRelPair(cap);
4089                 // Either<Boolean, StorageOperationStatus> eitherStatus = componentInstanceOperation.isAvailableCapabilty(currentCapCompInstance, relationPair);
4090                 // if (eitherStatus.isRight() || eitherStatus.left().value() == false) {
4091                 // return null;
4092                 // }
4093                 return cap;
4094         }
4095
4096         private CapabilityDefinition findAviableCapability(RequirementDefinition validReq, ComponentInstance currentCapCompInstance) {
4097                 CapabilityDefinition aviableCapForRel = null;
4098                 Map<String, List<CapabilityDefinition>> capMap = currentCapCompInstance.getCapabilities();
4099                 if (capMap.containsKey(validReq.getCapability())) {
4100                         List<CapabilityDefinition> capList = capMap.get(validReq.getCapability());
4101
4102                         for (CapabilityDefinition cap : capList) {
4103                                 // TODO temporary fix - remove specific capability node
4104                                 // String reqNode = validReq.getNode();
4105                                 // if (reqNode != null && !reqNode.isEmpty()) {
4106                                 // if (!cap.getCapabilitySources().contains(reqNode)) {
4107                                 // continue;
4108                                 // }
4109                                 // }
4110                                 if (cap.getMaxOccurrences() != null && !cap.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES)) {
4111                                         String leftOccurrences = cap.getLeftOccurrences();
4112                                         if (leftOccurrences == null) {
4113                                                 leftOccurrences = cap.getMaxOccurrences();
4114                                         }
4115                                         int left = Integer.parseInt(leftOccurrences);
4116                                         if (left > 0) {
4117                                                 --left;
4118                                                 cap.setLeftOccurrences(String.valueOf(left));
4119                                                 aviableCapForRel = cap;
4120                                                 break;
4121                                         } else {
4122                                                 continue;
4123                                         }
4124                                 } else {
4125                                         aviableCapForRel = cap;
4126                                         break;
4127                                 }
4128                         }
4129                 }
4130                 return aviableCapForRel;
4131         }
4132
4133         private Either<RequirementDefinition, ResponseFormat> findAviableRequiremen(String regName, String yamlName, UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance, String capName) {
4134                 Map<String, List<RequirementDefinition>> comInstRegDefMap = currentCompInstance.getRequirements();
4135                 List<RequirementDefinition> list = comInstRegDefMap.get(capName);
4136                 RequirementDefinition validRegDef = null;
4137                 if (list == null) {
4138                         for (Entry<String, List<RequirementDefinition>> entry : comInstRegDefMap.entrySet()) {
4139                                 for (RequirementDefinition reqDef : entry.getValue()) {
4140                                         if (reqDef.getName().equals(regName)) {
4141                                                 if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
4142                                                         String leftOccurrences = reqDef.getLeftOccurrences();
4143                                                         if (leftOccurrences == null) {
4144                                                                 leftOccurrences = reqDef.getMaxOccurrences();
4145                                                         }
4146                                                         int left = Integer.parseInt(leftOccurrences);
4147                                                         if (left > 0) {
4148                                                                 --left;
4149                                                                 reqDef.setLeftOccurrences(String.valueOf(left));
4150                                                                 validRegDef = reqDef;
4151                                                                 break;
4152                                                         } else {
4153                                                                 continue;
4154                                                         }
4155                                                 } else {
4156                                                         validRegDef = reqDef;
4157                                                         break;
4158                                                 }
4159
4160                                         }
4161                                 }
4162                                 if (validRegDef != null) {
4163                                         break;
4164                                 }
4165                         }
4166                 } else {
4167                         for (RequirementDefinition reqDef : list) {
4168                                 if (reqDef.getName().equals(regName)) {
4169                                         if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
4170                                                 String leftOccurrences = reqDef.getLeftOccurrences();
4171                                                 if (leftOccurrences == null) {
4172                                                         leftOccurrences = reqDef.getMaxOccurrences();
4173                                                 }
4174                                                 int left = Integer.parseInt(leftOccurrences);
4175                                                 if (left > 0) {
4176                                                         --left;
4177                                                         reqDef.setLeftOccurrences(String.valueOf(left));
4178                                                         validRegDef = reqDef;
4179                                                         break;
4180                                                 } else {
4181                                                         continue;
4182                                                 }
4183                                         } else {
4184                                                 validRegDef = reqDef;
4185                                                 break;
4186                                         }
4187                                 }
4188                         }
4189                 }
4190                 if (validRegDef == null) {
4191                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
4192                         return Either.right(responseFormat);
4193                 }
4194                 return Either.left(validRegDef);
4195         }
4196
4197         @SuppressWarnings("unchecked")
4198         public Either<ParsedToscaYamlInfo, ResponseFormat> parseResourceInfoFromYaml(String yamlFileName, Resource resource, String resourceYml, User user, Map<String, String> createdNodesToscaResourceNames, Map<String, NodeTypeInfo> nodeTypesInfo, String nodeTypeName) {
4199
4200                 Map<String, Object> mappedToscaTemplate;
4201                 if(nodeTypesInfo != null && nodeTypeName != null && nodeTypesInfo.containsKey(nodeTypeName)){
4202                         mappedToscaTemplate = nodeTypesInfo.get(nodeTypeName).getMappedToscaTemplate();
4203                 }
4204                 else {
4205                         mappedToscaTemplate = (Map<String, Object>) new Yaml().load(resourceYml);
4206                 }
4207                 Either<Object, ResultStatusEnum> toscaElementEither = ImportUtils.findToscaElement(mappedToscaTemplate, ToscaTagNamesEnum.TOPOLOGY_TEMPLATE, ToscaElementTypeEnum.ALL);
4208                 if (toscaElementEither.isRight()) {
4209                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
4210                         return Either.right(responseFormat);
4211                 }
4212
4213                 Either<Map<String, InputDefinition>, ResponseFormat> createInputsEither = createInputsFromYaml(yamlFileName, mappedToscaTemplate, resource);
4214                 if (createInputsEither.isRight()) {
4215                         ResponseFormat responseFormat = createInputsEither.right().value();
4216                         return Either.right(responseFormat);
4217                 }
4218
4219                 Either<Map<String, UploadComponentInstanceInfo>, ResponseFormat> uploadResInstancesEither = createResourcesInstanceInfoFromYaml(yamlFileName, mappedToscaTemplate, resource, createdNodesToscaResourceNames);
4220                 if (uploadResInstancesEither.isRight()) {
4221                         ResponseFormat responseFormat = uploadResInstancesEither.right().value();
4222                         return Either.right(responseFormat);
4223                 }
4224
4225                 Either<Map<String, GroupDefinition>, ResponseFormat> createGroupsFromYaml = createGroupsFromYaml(yamlFileName, mappedToscaTemplate, resource);
4226                 if (createGroupsFromYaml.isRight()) {
4227                         ResponseFormat responseFormat = createGroupsFromYaml.right().value();
4228                         return Either.right(responseFormat);
4229                 }
4230
4231                 ParsedToscaYamlInfo parsedToscaYamlInfo = new ParsedToscaYamlInfo();
4232                 parsedToscaYamlInfo.setInputs(createInputsEither.left().value());
4233                 parsedToscaYamlInfo.setInstances(uploadResInstancesEither.left().value());
4234                 parsedToscaYamlInfo.setGroups(createGroupsFromYaml.left().value());
4235
4236                 return Either.left(parsedToscaYamlInfo);
4237         }
4238
4239         private Either<Resource, ResponseFormat> createResourceInstances(User user, String yamlName, Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, boolean inTransaction, boolean needLock,
4240                         Map<String, Resource> nodeTypeNamespaceMap) {
4241
4242                 Either<Resource, ResponseFormat> eitherResource = null;
4243                 log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName);
4244                 if (uploadResInstancesMap == null || uploadResInstancesMap.isEmpty()) {
4245                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
4246
4247                         return Either.right(responseFormat);
4248
4249                 }
4250                 Map<String, Resource> existingnodeTypeMap = new HashMap<>();
4251                 if (nodeTypeNamespaceMap != null && !nodeTypeNamespaceMap.isEmpty()) {
4252                         nodeTypeNamespaceMap.entrySet().stream().forEach(x -> existingnodeTypeMap.put(x.getValue().getToscaResourceName(), x.getValue()));
4253                 }
4254
4255                 Iterator<Entry<String, UploadComponentInstanceInfo>> nodesInfoValue = uploadResInstancesMap.entrySet().iterator();
4256                 Map<ComponentInstance, Resource> resourcesInstancesMap = new HashMap<>();
4257                 while (nodesInfoValue.hasNext()) {
4258                         log.debug("*************Going to create  resource instances {}", yamlName);
4259                         Entry<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoEntry = nodesInfoValue.next();
4260                         UploadComponentInstanceInfo uploadComponentInstanceInfo = uploadComponentInstanceInfoEntry.getValue();
4261
4262                         // updating type if the type is node type name - we need to take the
4263                         // updated name
4264                         log.debug("*************Going to create  resource instances {}", uploadComponentInstanceInfo.getName());
4265                         if (nodeTypeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
4266                                 uploadComponentInstanceInfo.setType(nodeTypeNamespaceMap.get(uploadComponentInstanceInfo.getType()).getToscaResourceName());
4267                         }
4268
4269                         eitherResource = validateResourceInstanceBeforeCreate(yamlName, uploadComponentInstanceInfo, existingnodeTypeMap);
4270                         if (eitherResource.isRight()) {
4271                                 return eitherResource;
4272                         }
4273                         Resource refResource = eitherResource.left().value();
4274
4275                         ComponentInstance componentInstance = new ComponentInstance();
4276
4277                         componentInstance.setComponentUid(refResource.getUniqueId());
4278
4279                         ComponentTypeEnum containerComponentType = resource.getComponentType();
4280                         NodeTypeEnum containerNodeType = containerComponentType.getNodeType();
4281
4282                         if (containerNodeType.equals(NodeTypeEnum.Resource) && uploadComponentInstanceInfo.getCapabilities() != null) {
4283                                 Either<Map<String, List<CapabilityDefinition>>, ResponseFormat> getValidComponentInstanceCapabilitiesRes = getValidComponentInstanceCapabilities(refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities());
4284                                 if (getValidComponentInstanceCapabilitiesRes.isRight()) {
4285                                         return Either.right(getValidComponentInstanceCapabilitiesRes.right().value());
4286                                 } else {
4287                                         componentInstance.setCapabilities(getValidComponentInstanceCapabilitiesRes.left().value());
4288                                 }
4289                         }
4290                         if (!existingnodeTypeMap.containsKey(uploadComponentInstanceInfo.getType())) {
4291                                 log.debug("createResourceInstances - not found lates version for resource instance with name {} and type ", uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
4292                                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
4293                                 return Either.right(responseFormat);
4294                         }
4295                         Resource origResource = existingnodeTypeMap.get(uploadComponentInstanceInfo.getType());
4296                         componentInstance.setName(uploadComponentInstanceInfo.getName());
4297                         componentInstance.setIcon(origResource.getIcon());
4298
4299                         resourcesInstancesMap.put(componentInstance, origResource);
4300
4301                 }
4302                 if (MapUtils.isNotEmpty(resourcesInstancesMap)) {
4303
4304                         StorageOperationStatus status = toscaOperationFacade.associateComponentInstancesToComponent(resource, resourcesInstancesMap, false);
4305                         if (status != null && status != StorageOperationStatus.OK) {
4306                                 log.debug("Failed to add component instances to container component {}", resource.getName());
4307                                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status));
4308                                 eitherResource = Either.right(responseFormat);
4309                                 return eitherResource;
4310                         }
4311
4312                 }
4313
4314                 log.debug("*************Going to get resource {}", resource.getUniqueId());
4315                 ComponentParametersView parametersView = new ComponentParametersView();
4316                 parametersView.disableAll();
4317                 parametersView.setIgnoreComponentInstances(false);
4318                 parametersView.setIgnoreUsers(false);
4319                 parametersView.setIgnoreInputs(false); // inputs are read when creating
4320                 // property values on instances
4321                 Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId(), parametersView);
4322                 log.debug("*************finished to get resource {}", resource.getUniqueId());
4323                 if (eitherGerResource.isRight()) {
4324                         ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
4325
4326                         return Either.right(responseFormat);
4327
4328                 }
4329
4330                 if (eitherGerResource.left().value().getComponentInstances() == null || eitherGerResource.left().value().getComponentInstances().isEmpty()) {
4331
4332                         log.debug("Error when create resource inctanse from csar. ComponentInstances list empty");
4333                         BeEcompErrorManager.getInstance().logBeDaoSystemError("Error when create resource inctanse from csar. ComponentInstances list empty");
4334                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
4335                         return Either.right(responseFormat);
4336
4337                 }
4338
4339                 return Either.left(eitherGerResource.left().value());
4340         }
4341
4342         private Either<Resource, ResponseFormat> validateResourceInstanceBeforeCreate(String yamlName, UploadComponentInstanceInfo uploadComponentInstanceInfo, Map<String, Resource> nodeTypeNamespaceMap) {
4343                 log.debug("validateResourceInstanceBeforeCreate - going to validate resource instance with name {} and type before create", uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
4344                 Resource refResource = null;
4345                 if (nodeTypeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
4346                         refResource = nodeTypeNamespaceMap.get(uploadComponentInstanceInfo.getType());
4347                 } else {
4348                         Either<Resource, StorageOperationStatus> findResourceEither = toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(uploadComponentInstanceInfo.getType());
4349                         if (findResourceEither.isRight()) {
4350                                 log.debug("validateResourceInstanceBeforeCreate - not found lates version for resource instance with name {} and type ", uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
4351                                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(findResourceEither.right().value()));
4352                                 return Either.right(responseFormat);
4353                         }
4354                         refResource = findResourceEither.left().value();
4355                         nodeTypeNamespaceMap.put(refResource.getToscaResourceName(), refResource);
4356                 }
4357                 String componentState = refResource.getComponentMetadataDefinition().getMetadataDataDefinition().getState();
4358                 if (componentState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4359                         log.debug("validateResourceInstanceBeforeCreate - component instance of component {} can not be created because the component is in an illegal state {}.", refResource.getName(), componentState);
4360                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ILLEGAL_COMPONENT_STATE, refResource.getComponentType().getValue(), refResource.getName(), componentState);
4361                         return Either.right(responseFormat);
4362                 }
4363
4364                 if (!ToscaUtils.isAtomicType(refResource) && refResource.getResourceType() != ResourceTypeEnum.CVFC) {
4365                         log.debug("validateResourceInstanceBeforeCreate -  ref resource type is  ", refResource.getResourceType());
4366                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
4367                         return Either.right(responseFormat);
4368                 }
4369                 return Either.left(refResource);
4370         }
4371
4372         private Either<Map<String, UploadComponentInstanceInfo>, ResponseFormat> createResourcesInstanceInfoFromYaml(String yamlFileName, Map<String, Object> toscaJson, Resource resource, Map<String, String> createdNodesToscaResourceNames) {
4373                 Map<String, UploadComponentInstanceInfo> moduleComponentInstances = new HashMap<String, UploadComponentInstanceInfo>();
4374                 Map<String, Object> substitutionMappings = null;
4375                 Either<Map<String, UploadComponentInstanceInfo>, ResponseFormat> result = Either.left(moduleComponentInstances);
4376                 Either<Map<String, Object>, ResultStatusEnum> eitherNodesTemlates = ImportUtils.findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.NODE_TEMPLATES);
4377                 Either<Map<String, Object>, ResultStatusEnum> eitherSubstitutionMappings = ImportUtils.findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.SUBSTITUTION_MAPPINGS);
4378                 if (eitherSubstitutionMappings.isLeft()) {
4379                         substitutionMappings = eitherSubstitutionMappings.left().value();
4380                 }
4381                 if (eitherNodesTemlates.isLeft()) {
4382                         Map<String, Object> jsonNodeTemplates = eitherNodesTemlates.left().value();
4383
4384                         Iterator<Entry<String, Object>> nodesNameValue = jsonNodeTemplates.entrySet().iterator();
4385                         while (nodesNameValue.hasNext()) {
4386                                 Entry<String, Object> nodeNameValue = nodesNameValue.next();
4387                                 Either<UploadComponentInstanceInfo, ResponseFormat> eitherNode = createModuleComponentInstanceInfo(nodeNameValue, substitutionMappings, createdNodesToscaResourceNames);
4388                                 if (eitherNode.isRight()) {
4389                                         log.info("error when creating node template:{}, for resource:{}", nodeNameValue.getKey(), resource.getName());
4390                                         return Either.right(eitherNode.right().value());
4391                                 } else {
4392                                         UploadComponentInstanceInfo uploadComponentInstanceInfo = eitherNode.left().value();
4393                                         moduleComponentInstances.put(nodeNameValue.getKey(), uploadComponentInstanceInfo);
4394                                 }
4395
4396                         }
4397
4398                 }
4399                 if (moduleComponentInstances.isEmpty()) {
4400                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlFileName);
4401                         return Either.right(responseFormat);
4402                 }
4403
4404                 return result;
4405         }
4406
4407         @SuppressWarnings("unchecked")
4408         private Either<UploadComponentInstanceInfo, ResponseFormat> createModuleComponentInstanceInfo(Entry<String, Object> nodeTemplateJsonEntry, Map<String, Object> substitutionMappings, Map<String, String> createdNodesToscaResourceNames) {
4409
4410                 UploadComponentInstanceInfo nodeTemplateInfo = new UploadComponentInstanceInfo();
4411                 Either<UploadComponentInstanceInfo, ResponseFormat> result = Either.left(nodeTemplateInfo);
4412                 nodeTemplateInfo.setName(nodeTemplateJsonEntry.getKey());
4413                 try {
4414                         if (nodeTemplateJsonEntry.getValue() instanceof String) {
4415                                 String nodeTemplateJsonString = (String) nodeTemplateJsonEntry.getValue();
4416                                 nodeTemplateInfo.setType(nodeTemplateJsonString);
4417                         } else if (nodeTemplateJsonEntry.getValue() instanceof Map) {
4418                                 Map<String, Object> nodeTemplateJsonMap = (Map<String, Object>) nodeTemplateJsonEntry.getValue();
4419                                 // Type
4420                                 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) {
4421                                         String toscaResourceType = (String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName());
4422                                         if (createdNodesToscaResourceNames.containsKey(toscaResourceType)) {
4423                                                 toscaResourceType = createdNodesToscaResourceNames.get(toscaResourceType);
4424                                         }
4425                                         nodeTemplateInfo.setType(toscaResourceType);
4426                                 }
4427
4428                                 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.REQUIREMENTS.getElementName())) {
4429                                         Either<Map<String, List<UploadReqInfo>>, ResponseFormat> regResponse = createReqModuleFromYaml(nodeTemplateInfo, nodeTemplateJsonMap);
4430                                         if (regResponse.isRight())
4431                                                 return Either.right(regResponse.right().value());
4432                                         if (regResponse.left().value().size() > 0) {
4433                                                 nodeTemplateInfo.setRequirements(regResponse.left().value());
4434                                         }
4435                                 }
4436
4437                                 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.CAPABILITIES.getElementName())) {
4438                                         Either<Map<String, List<UploadCapInfo>>, ResponseFormat> eitherCapRes = createCapModuleFromYaml(nodeTemplateInfo, nodeTemplateJsonMap);
4439                                         if (eitherCapRes.isRight())
4440                                                 return Either.right(eitherCapRes.right().value());
4441                                         if (eitherCapRes.left().value().size() > 0) {
4442                                                 nodeTemplateInfo.setCapabilities(eitherCapRes.left().value());
4443                                         }
4444                                 }
4445                                 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.PROPERTIES.getElementName())) {
4446                                         Either<Map<String, List<UploadPropInfo>>, ResponseFormat> regResponse = createPropModuleFromYaml(nodeTemplateJsonMap);
4447                                         if (regResponse.isRight())
4448                                                 return Either.right(regResponse.right().value());
4449                                         if (regResponse.left().value().size() > 0) {
4450                                                 nodeTemplateInfo.setProperties(regResponse.left().value());
4451                                         }
4452                                 }
4453                                 if (substitutionMappings != null) {
4454                                         if (substitutionMappings.containsKey(ToscaTagNamesEnum.CAPABILITIES.getElementName())) {
4455                                                 Either<Map<String, String>, ResponseFormat> getCapNamesToUpdateRes = getNamesToUpdate(nodeTemplateInfo, (Map<String, List<String>>) substitutionMappings.get(ToscaTagNamesEnum.CAPABILITIES.getElementName()));
4456                                                 if (getCapNamesToUpdateRes.isRight())
4457                                                         return Either.right(getCapNamesToUpdateRes.right().value());
4458                                                 if (getCapNamesToUpdateRes.left().value().size() > 0) {
4459                                                         nodeTemplateInfo.setCapabilitiesNamesToUpdate(getCapNamesToUpdateRes.left().value());
4460                                                 }
4461                                         }
4462                                         if (substitutionMappings.containsKey(ToscaTagNamesEnum.REQUIREMENTS.getElementName())) {
4463                                                 Either<Map<String, String>, ResponseFormat> getReqNamesToUpdateRes = getNamesToUpdate(nodeTemplateInfo, (Map<String, List<String>>) substitutionMappings.get(ToscaTagNamesEnum.REQUIREMENTS.getElementName()));
4464                                                 if (getReqNamesToUpdateRes.isRight())
4465                                                         return Either.right(getReqNamesToUpdateRes.right().value());
4466                                                 if (getReqNamesToUpdateRes.left().value().size() > 0) {
4467                                                         nodeTemplateInfo.setRequirementsNamesToUpdate(getReqNamesToUpdateRes.left().value());
4468                                                 }
4469                                         }
4470                                 }
4471                         } else {
4472
4473                                 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
4474
4475                         }
4476                 } catch (Exception e) {
4477                         BeEcompErrorManager.getInstance().logBeSystemError("Import Resource - create capability");
4478                         log.debug("error when creating capability, message:{}", e.getMessage(), e);
4479                         result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML));
4480                 }
4481
4482                 return result;
4483         }
4484
4485         private Either<Map<String, String>, ResponseFormat> getNamesToUpdate(UploadComponentInstanceInfo nodeTemplateInfo, Map<String, List<String>> elements) {
4486                 Either<Map<String, String>, ResponseFormat> response;
4487                 try {
4488                         Map<String, String> namesToUpdate = elements.entrySet().stream().filter(e -> e.getValue().get(0).equalsIgnoreCase(nodeTemplateInfo.getName())).collect(Collectors.toMap(e -> e.getValue().get(1), e -> e.getKey()));
4489                         response = Either.left(namesToUpdate);
4490                 } catch (Exception e) {
4491                         log.debug("The exception {} occured upon adding names to update for instance {} . ", e.getMessage(), nodeTemplateInfo.getName());
4492                         response = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
4493                 }
4494                 return response;
4495         }
4496
4497         private Either<Map<String, List<UploadPropInfo>>, ResponseFormat> createPropModuleFromYaml(Map<String, Object> nodeTemplateJsonMap) {
4498                 Map<String, List<UploadPropInfo>> moduleProp = new HashMap<String, List<UploadPropInfo>>();
4499                 Either<Map<String, List<UploadPropInfo>>, ResponseFormat> response = Either.left(moduleProp);
4500                 Either<Map<String, Object>, ResultStatusEnum> toscaProperties = ImportUtils.findFirstToscaMapElement(nodeTemplateJsonMap, ToscaTagNamesEnum.PROPERTIES);
4501                 if (toscaProperties.isLeft()) {
4502                         Map<String, Object> jsonProperties = toscaProperties.left().value();
4503                         for (Entry<String, Object> jsonPropObj : jsonProperties.entrySet()) {
4504                                 // Property
4505                                 String propName = jsonPropObj.getKey();
4506                                 Object propValue = jsonPropObj.getValue();
4507
4508                                 if (valueContainsPattern(STR_REPLACE_PATTERN, propValue)) {
4509                                         log.trace("Ignore property value {}.", propName);
4510                                         continue;
4511                                 }
4512
4513                                 if (valueContainsPattern(TOKEN_PATTERN, propValue)) {
4514                                         log.trace("Ignore property value {}.", propName);
4515                                         continue;
4516                                 }
4517                                 if (valueContainsPattern(GET_PROPERTY_PATTERN, propValue)) {
4518                                         log.trace("Ignore property value {}.", propName);
4519                                         continue;
4520                                 }
4521
4522                                 if (valueContainsPattern(CONCAT_PATTERN, propValue)) {
4523                                         log.trace("Ignore property value {}.", propName);
4524                                         continue;
4525                                 }
4526
4527                                 UploadPropInfo propertyDef = new UploadPropInfo();
4528                                 propertyDef.setValue(propValue);
4529                                 propertyDef.setName(propName);
4530                                 if (propValue instanceof Map) {
4531                                         if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.TYPE.getElementName())) {
4532                                                 propertyDef.setType(((Map<String, Object>) propValue).get(ToscaTagNamesEnum.TYPE.getElementName()).toString());
4533                                         }
4534
4535                                         if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName())
4536                                                         || ImportUtils.getPropertyJsonStringValue(propValue, ToscaPropertyType.MAP.getType()).contains(ToscaTagNamesEnum.GET_INPUT.getElementName())) {
4537                                                 createGetInputModuleFromMap(propName, (Map<String, Object>) propValue, propertyDef);
4538                                         }
4539
4540                                         if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.DESCRIPTION.getElementName())) {
4541                                                 propertyDef.setDescription(((Map<String, Object>) propValue).get(ToscaTagNamesEnum.DESCRIPTION.getElementName()).toString());
4542                                         }
4543                                         if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.DEFAULT_VALUE.getElementName())) {
4544                                                 propertyDef.setValue(((Map<String, Object>) propValue).get(ToscaTagNamesEnum.DEFAULT_VALUE.getElementName()));
4545                                         }
4546                                         if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.IS_PASSWORD.getElementName())) {
4547                                                 propertyDef.setPassword(Boolean.getBoolean(((Map<String, Object>) propValue).get(ToscaTagNamesEnum.IS_PASSWORD.getElementName()).toString()));
4548                                         } else {
4549                                                 propertyDef.setValue(propValue);
4550                                         }
4551                                 } else if (propValue instanceof List) {
4552                                         List<Object> propValueList = (List<Object>) propValue;
4553
4554                                         createInputPropList(propertyDef, propValueList);
4555                                         propertyDef.setValue(propValue);
4556                                 }
4557
4558                                 if (moduleProp.containsKey(propName)) {
4559                                         moduleProp.get(propName).add(propertyDef);
4560                                 } else {
4561                                         List<UploadPropInfo> list = new ArrayList<UploadPropInfo>();
4562                                         list.add(propertyDef);
4563                                         moduleProp.put(propName, list);
4564                                 }
4565                         }
4566                 }
4567                 return response;
4568         }
4569
4570         private void createInputPropList(UploadPropInfo propertyDef, List<Object> propValueList) {
4571                 for (Object objValue : propValueList) {
4572
4573                         if (objValue instanceof Map) {
4574                                 Map<String, Object> objMap = (Map<String, Object>) objValue;
4575                                 if (objMap.containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName()))
4576                                         createGetInputModuleFromMap(propertyDef.getName(), objMap, propertyDef);
4577                                 else {
4578                                         Set<String> keys = objMap.keySet();
4579                                         for (String key : keys) {
4580                                                 Object value = objMap.get(key);
4581                                                 if (value instanceof Map) {
4582                                                         createGetInputModuleFromMap(key, (Map<String, Object>) value, propertyDef);
4583
4584                                                 } else if (value instanceof List) {
4585                                                         List<Object> propSubValueList = (List<Object>) value;
4586
4587                                                         createInputPropList(propertyDef, propSubValueList);
4588                                                 }
4589
4590                                         }
4591                                 }
4592
4593                         } else if (objValue instanceof List) {
4594                                 List<Object> propSubValueList = (List<Object>) objValue;
4595
4596                                 createInputPropList(propertyDef, propSubValueList);
4597
4598                         }
4599
4600                 }
4601         }
4602
4603         private void createGetInputModuleFromMap(String propName, Map<String, Object> propValue, UploadPropInfo propertyDef) {
4604
4605                 if (propValue.containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName())) {
4606                         Object getInput = propValue.get(ToscaTagNamesEnum.GET_INPUT.getElementName());
4607                         GetInputValueDataDefinition getInputInfo = new GetInputValueDataDefinition();
4608                         List<GetInputValueDataDefinition> getInputs = propertyDef.getGet_input();
4609                         if (getInputs == null) {
4610                                 getInputs = new ArrayList<GetInputValueDataDefinition>();
4611                         }
4612                         if (getInput instanceof String) {
4613
4614                                 getInputInfo.setInputName((String) getInput);
4615                                 getInputInfo.setPropName(propName);
4616
4617                         } else if (getInput instanceof List) {
4618                                 List<Object> getInputList = (List<Object>) getInput;
4619                                 getInputInfo.setPropName(propName);
4620                                 getInputInfo.setInputName((String) getInputList.get(0));
4621                                 if (getInputList.size() > 1) {
4622                                         Object indexObj = getInputList.get(1);
4623                                         if (indexObj instanceof Integer) {
4624                                                 getInputInfo.setIndexValue((Integer) indexObj);
4625                                         } else if (indexObj instanceof Float) {
4626                                                 int index = ((Float) indexObj).intValue();
4627                                                 getInputInfo.setIndexValue(index);
4628                                         } else if (indexObj instanceof Map && ((Map<String, Object>) indexObj).containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName())) {
4629                                                 Object index = ((Map<String, Object>) indexObj).get(ToscaTagNamesEnum.GET_INPUT.getElementName());
4630                                                 GetInputValueDataDefinition getInputInfoIndex = new GetInputValueDataDefinition();
4631                                                 getInputInfoIndex.setInputName((String) index);
4632                                                 getInputInfoIndex.setPropName(propName);
4633                                                 getInputInfo.setGetInputIndex(getInputInfoIndex);
4634                                         }
4635                                         getInputInfo.setList(true);
4636                                 }
4637
4638                         }
4639                         getInputs.add(getInputInfo);
4640                         propertyDef.setGet_input(getInputs);
4641                         propertyDef.setValue(propValue);
4642                 } else {
4643                         Set<String> keys = propValue.keySet();
4644                         for (String key : keys) {
4645                                 Object value = propValue.get(key);
4646                                 if (value instanceof Map) {
4647                                         createGetInputModuleFromMap(key, (Map<String, Object>) value, propertyDef);
4648
4649                                 } else if (value instanceof List) {
4650                                         List<Object> valueList = (List<Object>) value;
4651                                         for (Object o : valueList) {
4652                                                 if (o instanceof Map) {
4653                                                         createGetInputModuleFromMap(key, (Map<String, Object>) o, propertyDef);
4654
4655                                                 }
4656                                         }
4657
4658                                 }
4659
4660                         }
4661
4662                 }
4663         }
4664
4665         /*
4666          * private boolean valueContainsStrReplace(Object propValue) {
4667          *
4668          * log.debug("valueContainsStrReplace value is {}", propValue); boolean result = false; if (propValue != null) { log.debug("valueContainsStrReplace value is {}", propValue.getClass()); Matcher matcher =
4669          * STR_REPLACE_PATTERN.matcher(propValue.toString()); result = matcher.find(); }
4670          *
4671          * return result; }
4672          *
4673          * private boolean valueContainsToken(Object propValue) {
4674          *
4675          * log.debug("valueContainsToken value is {}", propValue); boolean result = false; if (propValue != null) { log.debug("valueContainsToken value is {}", propValue.getClass()); Matcher matcher = TOKEN_PATTERN.matcher(propValue.toString()); result =
4676          * matcher.find(); }
4677          *
4678          * return result; }
4679          */
4680
4681         private boolean valueContainsPattern(Pattern pattern, Object propValue) {
4682
4683                 log.debug("valueContainsToken value is {}", propValue);
4684                 boolean result = false;
4685                 if (propValue != null) {
4686                         log.trace("valueContainspattern value is {}", propValue.getClass());
4687                         Matcher matcher = pattern.matcher(propValue.toString());
4688                         result = matcher.find();
4689                 }
4690
4691                 return result;
4692
4693         }
4694
4695         private Either<Map<String, List<UploadCapInfo>>, ResponseFormat> createCapModuleFromYaml(UploadComponentInstanceInfo nodeTemplateInfo, Map<String, Object> nodeTemplateJsonMap) {
4696                 Map<String, List<UploadCapInfo>> moduleCap = new HashMap<String, List<UploadCapInfo>>();
4697                 Either<Map<String, List<UploadCapInfo>>, ResponseFormat> response = Either.left(moduleCap);
4698                 Either<List<Object>, ResultStatusEnum> toscaRequirements = ImportUtils.findFirstToscaListElement(nodeTemplateJsonMap, ToscaTagNamesEnum.CAPABILITIES);
4699                 if (toscaRequirements.isLeft()) {
4700                         List<Object> jsonCapabilities = toscaRequirements.left().value();
4701
4702                         for (Object jsonCapObj : jsonCapabilities) {
4703                                 // Requirement
4704                                 Map<String, Object> capJsonWrapper = (Map<String, Object>) jsonCapObj;
4705                                 String capName = capJsonWrapper.keySet().iterator().next();
4706                                 Either<UploadCapInfo, ResponseFormat> eitherCap = createModuleNodeTemplateCap(capJsonWrapper.get(capName));
4707                                 if (eitherCap.isRight()) {
4708                                         log.info("error when creating Requirement:{}, for node:{}", capName, nodeTemplateInfo);
4709                                         return Either.right(eitherCap.right().value());
4710                                 } else {
4711                                         UploadCapInfo requirementDef = eitherCap.left().value();
4712                                         requirementDef.setName(capName);
4713                                         if (moduleCap.containsKey(capName)) {
4714                                                 moduleCap.get(capName).add(requirementDef);
4715                                         } else {
4716                                                 List<UploadCapInfo> list = new ArrayList<UploadCapInfo>();
4717                                                 list.add(requirementDef);
4718                                                 moduleCap.put(capName, list);
4719                                         }
4720
4721                                 }
4722                         }
4723
4724                 }
4725
4726                 return response;
4727         }
4728
4729         private Either<Map<String, List<UploadReqInfo>>, ResponseFormat> createReqModuleFromYaml(UploadComponentInstanceInfo nodeTemplateInfo, Map<String, Object> nodeTemplateJsonMap) {
4730                 Map<String, List<UploadReqInfo>> moduleRequirements = new HashMap<String, List<UploadReqInfo>>();
4731                 Either<Map<String, List<UploadReqInfo>>, ResponseFormat> response = Either.left(moduleRequirements);
4732                 Either<List<Object>, ResultStatusEnum> toscaRequirements = ImportUtils.findFirstToscaListElement(nodeTemplateJsonMap, ToscaTagNamesEnum.REQUIREMENTS);
4733                 if (toscaRequirements.isLeft()) {
4734                         List<Object> jsonRequirements = toscaRequirements.left().value();
4735
4736                         for (Object jsonRequirementObj : jsonRequirements) {
4737                                 // Requirement
4738                                 Map<String, Object> requirementJsonWrapper = (Map<String, Object>) jsonRequirementObj;
4739                                 String requirementName = requirementJsonWrapper.keySet().iterator().next();
4740                                 Either<UploadReqInfo, ResponseFormat> eitherRequirement = createModuleNodeTemplateReg(requirementJsonWrapper.get(requirementName));
4741                                 if (eitherRequirement.isRight()) {
4742                                         log.info("error when creating Requirement:{}, for node:{}", requirementName, nodeTemplateInfo);
4743                                         return Either.right(eitherRequirement.right().value());
4744                                 } else {
4745                                         UploadReqInfo requirementDef = eitherRequirement.left().value();
4746                                         requirementDef.setName(requirementName);
4747                                         if (moduleRequirements.containsKey(requirementName)) {
4748                                                 moduleRequirements.get(requirementName).add(requirementDef);
4749                                         } else {
4750                                                 List<UploadReqInfo> list = new ArrayList<UploadReqInfo>();
4751                                                 list.add(requirementDef);
4752                                                 moduleRequirements.put(requirementName, list);
4753                                         }
4754
4755                                 }
4756                         }
4757
4758                 }
4759                 return response;
4760         }
4761
4762         private Either<UploadCapInfo, ResponseFormat> createModuleNodeTemplateCap(Object capObject) {
4763                 UploadCapInfo capTemplateInfo = new UploadCapInfo();
4764                 Either<UploadCapInfo, ResponseFormat> result = Either.left(capTemplateInfo);
4765
4766                 if (capObject instanceof String) {
4767                         String nodeTemplateJsonString = (String) capObject;
4768                         capTemplateInfo.setNode(nodeTemplateJsonString);
4769                 } else if (capObject instanceof Map) {
4770                         Map<String, Object> nodeTemplateJsonMap = (Map<String, Object>) capObject;
4771                         // Type
4772                         if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.NODE.getElementName())) {
4773                                 capTemplateInfo.setNode((String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.NODE.getElementName()));
4774                         }
4775                         if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) {
4776                                 capTemplateInfo.setType((String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName()));
4777                         }
4778                         if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.VALID_SOURCE_TYPES.getElementName())) {
4779                                 Either<List<Object>, ResultStatusEnum> validSourceTypesRes = ImportUtils.findFirstToscaListElement(nodeTemplateJsonMap, ToscaTagNamesEnum.VALID_SOURCE_TYPES);
4780                                 if (validSourceTypesRes.isLeft()) {
4781                                         capTemplateInfo.setValidSourceTypes(validSourceTypesRes.left().value().stream().map(o -> o.toString()).collect(Collectors.toList()));
4782                                 }
4783                         }
4784                         if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.PROPERTIES.getElementName())) {
4785                                 Either<Map<String, List<UploadPropInfo>>, ResponseFormat> regResponse = createPropModuleFromYaml(nodeTemplateJsonMap);
4786                                 if (regResponse.isRight())
4787                                         return Either.right(regResponse.right().value());
4788                                 if (!regResponse.left().value().isEmpty()) {
4789                                         List<UploadPropInfo> properties = new ArrayList<UploadPropInfo>();
4790                                         regResponse.left().value().values().forEach(list -> properties.addAll(list));
4791                                         if (!properties.isEmpty())
4792                                                 capTemplateInfo.setProperties(properties);
4793                                 }
4794                         }
4795                 }
4796
4797                 return result;
4798         }
4799
4800         private Either<UploadReqInfo, ResponseFormat> createModuleNodeTemplateReg(Object regObject) {
4801
4802                 UploadReqInfo regTemplateInfo = new UploadReqInfo();
4803                 Either<UploadReqInfo, ResponseFormat> result = Either.left(regTemplateInfo);
4804
4805                 if (regObject instanceof String) {
4806                         String nodeTemplateJsonString = (String) regObject;
4807                         regTemplateInfo.setNode(nodeTemplateJsonString);
4808                 } else if (regObject instanceof Map) {
4809                         Map<String, Object> nodeTemplateJsonMap = (Map<String, Object>) regObject;
4810                         // Type
4811                         if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.NODE.getElementName())) {
4812                                 regTemplateInfo.setNode((String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.NODE.getElementName()));
4813                         }
4814                         // US740820 Relate RIs according to capability name
4815                         if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.CAPABILITY.getElementName())) {
4816                                 regTemplateInfo.setCapabilityName((String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.CAPABILITY.getElementName()));
4817                         }
4818                 }
4819
4820                 return result;
4821         }
4822
4823         public Either<Resource, ResponseFormat> propagateStateToCertified(User user, Resource resource, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock, boolean forceCertificationAllowed) {
4824                 
4825                 Either<Resource, ResponseFormat> result = null;
4826                 try {
4827                         if(resource.getLifecycleState() != LifecycleStateEnum.CERTIFIED && forceCertificationAllowed){
4828                                 result = nodeForceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock);
4829                                 if(result.isRight()){
4830                                         return result;
4831                                 }
4832                                 resource = result.left().value();
4833                         }
4834                         if (resource.getLifecycleState() == LifecycleStateEnum.CERTIFIED) {
4835                                 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherPopulated = populateToscaArtifacts(resource, user, false, inTransaction, needLock);
4836                                 result = eitherPopulated.isLeft() ? Either.left(resource) : Either.right(eitherPopulated.right().value());
4837                                 return result;
4838                         }
4839                         return nodeFullCertification(resource.getUniqueId(), user, lifecycleChangeInfo, inTransaction, needLock);
4840                 } catch (Exception e) {
4841                         log.debug("The exception {} has occured upon certification of resource {}. ", e.getMessage(), resource.getName());
4842                         return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
4843                 } finally {
4844                         if (result == null || result.isRight()) {
4845                                 BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
4846                                 if (inTransaction == false) {
4847                                         log.debug("operation failed. do rollback");
4848                                         titanDao.rollback();
4849                                 }
4850                         } else if (inTransaction == false) {
4851                                 log.debug("operation success. do commit");
4852                                 titanDao.commit();
4853                         }
4854                 }
4855         }
4856
4857         private Either<Resource, ResponseFormat> nodeFullCertification(String uniqueId, User user, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
4858                 Either<Resource, ResponseFormat> result = lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFICATION_REQUEST, lifecycleChangeInfo, inTransaction, needLock);
4859                 if (result.isLeft()) {
4860                         result = lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.START_CERTIFICATION, lifecycleChangeInfo, inTransaction, needLock);
4861                 }
4862                 if (result.isLeft()) {
4863                         result = lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFY, lifecycleChangeInfo, inTransaction, needLock);
4864                 }
4865                 return result;
4866         }
4867
4868         private Either<Resource, ResponseFormat> nodeForceCertification(Resource resource, User user, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
4869                 return lifecycleBusinessLogic.forceResourceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock);
4870         }
4871
4872         /*
4873          * /**
4874          *
4875          * @deprecated Use {@link #createOrUpdateResourceByImport(Resource,User,boolean, boolean,boolean)} instead
4876          */
4877         /*
4878          * public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateResourceByImport(Resource resource, User user, AuditingActionEnum auditingEnum, boolean isNormative, boolean needLock) { return
4879          * createOrUpdateResourceByImport(resource, user, isNormative, false, needLock); }
4880          */
4881
4882         public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateResourceByImport(Resource resource, User user, boolean isNormative, boolean isInTransaction, boolean needLock) {
4883
4884                 // check if resource already exist
4885                 Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resource.getName());
4886                 Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> result = null;
4887
4888                 // create
4889                 if (latestByName.isRight() && latestByName.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
4890
4891                         Either<Resource, StorageOperationStatus> latestByToscaName = toscaOperationFacade.getLatestByToscaResourceName(resource.getToscaResourceName());
4892                         if (latestByToscaName.isRight() && latestByToscaName.right().value().equals(StorageOperationStatus.NOT_FOUND))
4893                                 result = createResourceByImport(resource, user, isNormative, isInTransaction);
4894
4895                         else {
4896                                 StorageOperationStatus status = latestByName.right().value();
4897                                 BeEcompErrorManager.getInstance().logBeComponentMissingError("Create / Update resource by import", ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
4898                                 log.debug("resource already exist {}. status={}", resource.getName(), status);
4899                                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_ALREADY_EXISTS);
4900                                 componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
4901                                 result = Either.right(responseFormat);
4902                         }
4903
4904                 }
4905
4906                 // update
4907                 else if (latestByName.isLeft()) {
4908                         result = updateExistingResourceByImport(resource, latestByName.left().value(), user, isNormative, needLock);
4909                 }
4910
4911                 // error
4912                 else {
4913                         StorageOperationStatus status = latestByName.right().value();
4914                         log.debug("failed to get latest version of resource {}. status={}", resource.getName(), status);
4915                         ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(latestByName.right().value()), resource);
4916                         componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
4917                         result = Either.right(responseFormat);
4918                 }
4919                 return result;
4920
4921         }
4922
4923         private Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createResourceByImport(Resource resource, User user, boolean isNormative, boolean isInTransaction) {
4924                 log.debug("resource with name {} does not exist. create new resource", resource.getName());
4925                 Either<Resource, ResponseFormat> response = validateResourceBeforeCreate(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isInTransaction);
4926                 if (response.isRight()) {
4927                         return Either.right(response.right().value());
4928                 }
4929                 Either<Resource, ResponseFormat> createResponse = createResourceByDao(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isNormative, isInTransaction, null);
4930                 if (createResponse.isRight()) {
4931                         return Either.right(createResponse.right().value());
4932                 } else {
4933                         ImmutablePair<Resource, ActionStatus> resourcePair = new ImmutablePair<>(createResponse.left().value(), ActionStatus.CREATED);
4934                         ASDCKpiApi.countImportResourcesKPI();
4935                         return Either.left(resourcePair);
4936
4937                 }
4938         }
4939
4940         public boolean isResourceExist(String resourceName) {
4941                 Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resourceName);
4942                 return latestByName.isLeft();
4943         }
4944
4945         private Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> updateExistingResourceByImport(Resource newResource, Resource oldResource, User user, boolean inTransaction, boolean needLock) {
4946                 String lockedResourceId = oldResource.getUniqueId();
4947                 log.debug("found resource: name={}, id={}, version={}, state={}", oldResource.getName(), lockedResourceId, oldResource.getVersion(), oldResource.getLifecycleState());
4948                 Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> result = null;
4949                 try {
4950                         if (needLock) {
4951                                 Either<Boolean, ResponseFormat> lockResult = lockComponent(lockedResourceId, oldResource, "Update Resource by Import");
4952                                 if (lockResult.isRight()) {
4953                                         return Either.right(lockResult.right().value());
4954                                 }
4955                         }
4956
4957                         Either<Resource, ResponseFormat> prepareResourceForUpdate = prepareResourceForUpdate(oldResource, user, inTransaction, false);
4958                         if (prepareResourceForUpdate.isRight()) {
4959                                 ResponseFormat responseFormat = prepareResourceForUpdate.right().value();
4960                                 log.info("resource {} cannot be updated. reason={}", lockedResourceId, responseFormat.getFormattedMessage());
4961                                 componentsUtils.auditResource(responseFormat, user, newResource, oldResource.getLifecycleState().name(), oldResource.getVersion(), AuditingActionEnum.IMPORT_RESOURCE, null);
4962                                 result = Either.right(prepareResourceForUpdate.right().value());
4963                                 return result;
4964                         }
4965                         oldResource = prepareResourceForUpdate.left().value();
4966
4967                         mergeOldResourceMetadataWithNew(oldResource, newResource);
4968
4969                         Either<Boolean, ResponseFormat> validateFieldsResponse = validateResourceFieldsBeforeUpdate(oldResource, newResource, inTransaction);
4970                         if (validateFieldsResponse.isRight()) {
4971                                 result = Either.right(validateFieldsResponse.right().value());
4972                                 return result;
4973                         }
4974
4975                         // contact info normalization
4976                         newResource.setContactId(newResource.getContactId().toLowerCase());
4977                         // non-updatable fields
4978                         newResource.setCreatorUserId(user.getUserId());
4979                         newResource.setCreatorFullName(user.getFullName());
4980                         newResource.setLastUpdaterUserId(user.getUserId());
4981                         newResource.setLastUpdaterFullName(user.getFullName());
4982                         newResource.setUniqueId(oldResource.getUniqueId());
4983                         newResource.setVersion(oldResource.getVersion());
4984                         newResource.setInvariantUUID(oldResource.getInvariantUUID());
4985                         newResource.setLifecycleState(oldResource.getLifecycleState());
4986                         newResource.setUUID(oldResource.getUUID());
4987                         newResource.setNormalizedName(oldResource.getNormalizedName());
4988                         newResource.setSystemName(oldResource.getSystemName());
4989                         if (oldResource.getCsarUUID() != null) {
4990                                 newResource.setCsarUUID(oldResource.getCsarUUID());
4991                         }
4992                         if (oldResource.getImportedToscaChecksum() != null) {
4993                                 newResource.setImportedToscaChecksum(oldResource.getImportedToscaChecksum());
4994                         }
4995                         newResource.setAbstract(oldResource.isAbstract());
4996
4997                         if (newResource.getDerivedFrom() == null || newResource.getDerivedFrom().isEmpty()) {
4998                                 newResource.setDerivedFrom(oldResource.getDerivedFrom());
4999                         }
5000                         // TODO rhalili: handle artifacts here (delete from old resource and
5001                         // add for new)
5002                         // TODO rbetzer: remove after migration - in case of resources
5003                         // created without tosca artifacts - add the placeholders
5004                         if (newResource.getToscaArtifacts() == null || newResource.getToscaArtifacts().isEmpty()) {
5005                                 setToscaArtifactsPlaceHolders(newResource, user);
5006                         }
5007                         Either<Resource, StorageOperationStatus> overrideResource = toscaOperationFacade.overrideComponent(newResource, oldResource);
5008
5009                         if (overrideResource.isRight()) {
5010                                 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(overrideResource.right().value()), newResource);
5011                                 componentsUtils.auditResource(responseFormat, user, newResource, newResource.getLifecycleState().name(), newResource.getVersion(), AuditingActionEnum.IMPORT_RESOURCE, null);
5012                                 result = Either.right(responseFormat);
5013                                 return result;
5014                         }
5015
5016                         log.debug("Resource updated successfully!!!");
5017                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
5018                         componentsUtils.auditResource(responseFormat, user, newResource, oldResource.getLifecycleState().name(), oldResource.getVersion(), AuditingActionEnum.IMPORT_RESOURCE, null);
5019
5020                         ImmutablePair<Resource, ActionStatus> resourcePair = new ImmutablePair<>(overrideResource.left().value(), ActionStatus.OK);
5021                         result = Either.left(resourcePair);
5022                         return result;
5023                 } finally {
5024                         if (result == null || result.isRight()) {
5025                                 BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
5026                                 log.debug("operation failed. do rollback");
5027                                 titanDao.rollback();
5028                         } else if (inTransaction == false) {
5029                                 log.debug("operation success. do commit");
5030                                 titanDao.commit();
5031                         }
5032                         if (needLock == true) {
5033                                 log.debug("unlock resource {}", lockedResourceId);
5034                                 graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
5035                         }
5036                 }
5037
5038         }
5039
5040         /**
5041          * Merge old resource with new. Keep old category and vendor name without change
5042          *
5043          * @param oldResource
5044          * @param newResource
5045          */
5046         private void mergeOldResourceMetadataWithNew(Resource oldResource, Resource newResource) {
5047
5048                 // keep old category and vendor name without change
5049                 // merge the rest of the resource metadata
5050                 if (newResource.getTags() == null || newResource.getTags().isEmpty()) {
5051                         newResource.setTags(oldResource.getTags());
5052                 }
5053
5054                 if (newResource.getDescription() == null) {
5055                         newResource.setDescription(oldResource.getDescription());
5056                 }
5057
5058                 if (newResource.getVendorRelease() == null) {
5059                         newResource.setVendorRelease(oldResource.getVendorRelease());
5060                 }
5061
5062                 if (newResource.getResourceVendorModelNumber() == null) {
5063                         newResource.setResourceVendorModelNumber(oldResource.getResourceVendorModelNumber());
5064                 }
5065
5066                 if (newResource.getContactId() == null) {
5067                         newResource.setContactId(oldResource.getContactId());
5068                 }
5069
5070                 newResource.setCategories(oldResource.getCategories());
5071                 newResource.setVendorName(oldResource.getVendorName());
5072         }
5073
5074         private Either<Resource, ResponseFormat> prepareResourceForUpdate(Resource latestResource, User user, boolean inTransaction, boolean needLock) {
5075
5076                 Either<Resource, ResponseFormat> result = Either.left(latestResource);
5077                 // check if user can edit resource
5078                 if (!ComponentValidationUtils.canWorkOnResource(latestResource, user.getUserId())) {
5079                         // checkout
5080                         Either<Resource, ResponseFormat> changeState = lifecycleBusinessLogic.changeState(latestResource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT, new LifecycleChangeInfoWithAction("update by import"), inTransaction, needLock);
5081                         result = changeState;
5082                 }
5083
5084                 return result;
5085         }
5086
5087         public Either<Resource, ResponseFormat> validateResourceBeforeCreate(Resource resource, User user, AuditingActionEnum actionEnum, boolean inTransaction) {
5088
5089                 Either<Boolean, ResponseFormat> eitherValidation = validateResourceFieldsBeforeCreate(user, resource, actionEnum, inTransaction);
5090                 if (eitherValidation.isRight()) {
5091                         return Either.right(eitherValidation.right().value());
5092                 }
5093
5094                 eitherValidation = validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), resource, actionEnum, inTransaction);
5095                 if (eitherValidation.isRight()) {
5096                         return Either.right(eitherValidation.right().value());
5097                 }
5098                 eitherValidation = validateLifecycleTypesCreate(user, resource, actionEnum);
5099                 if (eitherValidation.isRight()) {
5100                         return Either.right(eitherValidation.right().value());
5101                 }
5102                 eitherValidation = validateResourceType(user, resource, actionEnum);
5103                 if (eitherValidation.isRight()) {
5104                         return Either.right(eitherValidation.right().value());
5105                 }
5106
5107                 resource.setCreatorUserId(user.getUserId());
5108                 resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
5109                 resource.setContactId(resource.getContactId().toLowerCase());
5110                 if (!ToscaUtils.isAtomicType(resource) && resource.getResourceType() != ResourceTypeEnum.CVFC) {
5111                         resource.setToscaResourceName(CommonBeUtils.generateToscaResourceName(resource.getResourceType().name(), resource.getSystemName()));
5112                 }
5113
5114                 // Generate invariant UUID - must be here and not in operation since it
5115                 // should stay constant during clone
5116                 // TODO
5117                 String invariantUUID = UniqueIdBuilder.buildInvariantUUID();
5118                 resource.setInvariantUUID(invariantUUID);
5119
5120                 return Either.left(resource);
5121         }
5122
5123         private Either<Boolean, ResponseFormat> validateResourceType(User user, Resource resource, AuditingActionEnum actionEnum) {
5124                 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
5125                 if (resource.getResourceType() == null) {
5126                         log.debug("Invalid resource type for resource");
5127                         ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
5128                         eitherResult = Either.right(errorResponse);
5129                         componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null);
5130                 }
5131                 return eitherResult;
5132         }
5133
5134         private Either<Boolean, ResponseFormat> validateLifecycleTypesCreate(User user, Resource resource, AuditingActionEnum actionEnum) {
5135                 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
5136                 if (resource.getInterfaces() != null && resource.getInterfaces().size() > 0) {
5137                         log.debug("validate interface lifecycle Types Exist");
5138                         Iterator<InterfaceDefinition> intItr = resource.getInterfaces().values().iterator();
5139                         while (intItr.hasNext() && eitherResult.isLeft()) {
5140                                 InterfaceDefinition interfaceDefinition = intItr.next();
5141                                 String intType = interfaceDefinition.getUniqueId();
5142                                 Either<InterfaceDefinition, StorageOperationStatus> eitherCapTypeFound = interfaceTypeOperation.getInterface(intType);
5143                                 if (eitherCapTypeFound.isRight()) {
5144                                         if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
5145                                                 BeEcompErrorManager.getInstance().logBeGraphObjectMissingError("Create Resource - validateLifecycleTypesCreate", "Interface", intType);
5146                                                 log.debug("Lifecycle Type: {} is required by resource: {} but does not exist in the DB", intType, resource.getName());
5147                                                 BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateLifecycleTypesCreate");
5148                                                 log.debug("request to data model failed with error: {}", eitherCapTypeFound.right().value().name());
5149                                         }
5150
5151                                         ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_LIFECYCLE_TYPE, intType);
5152                                         eitherResult = Either.right(errorResponse);
5153                                         componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null);
5154                                 }
5155
5156                         }
5157                 }
5158                 return eitherResult;
5159         }
5160
5161         private Either<Boolean, ResponseFormat> validateCapabilityTypesCreate(User user, ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
5162
5163                 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
5164                 if (resource.getCapabilities() != null && resource.getCapabilities().size() > 0) {
5165                         log.debug("validate capability Types Exist - capabilities section");
5166
5167                         for (Entry<String, List<CapabilityDefinition>> typeEntry : resource.getCapabilities().entrySet()) {
5168
5169                                 eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, actionEnum, eitherResult, typeEntry, inTransaction);
5170                                 if (eitherResult.isRight()) {
5171                                         return Either.right(eitherResult.right().value());
5172                                 }
5173                         }
5174                 }
5175
5176                 if (resource.getRequirements() != null && resource.getRequirements().size() > 0) {
5177                         log.debug("validate capability Types Exist - requirements section");
5178                         for (String type : resource.getRequirements().keySet()) {
5179                                 eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, resource.getRequirements().get(type), actionEnum, eitherResult, type, inTransaction);
5180                                 if (eitherResult.isRight()) {
5181                                         return Either.right(eitherResult.right().value());
5182                                 }
5183                         }
5184                 }
5185
5186                 return eitherResult;
5187         }
5188
5189         // @param typeObject- the object to which the validation is done
5190         private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user, ICapabilityTypeOperation capabilityTypeOperation, Resource resource, List validationObjects, AuditingActionEnum actionEnum, Either<Boolean, ResponseFormat> eitherResult, String type,
5191                                                                                                                                                  boolean inTransaction) {
5192                 Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation.getCapabilityType(type, inTransaction);
5193                 if (eitherCapTypeFound.isRight()) {
5194                         if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
5195                                 BeEcompErrorManager.getInstance().logBeGraphObjectMissingError("Create Resource - validateCapabilityTypesCreate", "Capability Type", type);
5196                                 log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", type, resource.getName());
5197                                 BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateCapabilityTypesCreate");
5198                         }
5199                         log.debug("Trying to get capability type {} failed with error: {}", type, eitherCapTypeFound.right().value().name());
5200                         ResponseFormat errorResponse = null;
5201                         if (type != null)
5202                                 errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, type);
5203                         else
5204                                 errorResponse = componentsUtils.getResponseFormatByElement(ActionStatus.MISSING_CAPABILITY_TYPE, validationObjects);
5205                         eitherResult = Either.right(errorResponse);
5206                         componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null);
5207                 }
5208                 return eitherResult;
5209         }
5210
5211         private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user, ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum, Either<Boolean, ResponseFormat> eitherResult,
5212                         Entry<String, List<CapabilityDefinition>> typeEntry, boolean inTransaction) {
5213                 Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation.getCapabilityType(typeEntry.getKey(), inTransaction);
5214                 if (eitherCapTypeFound.isRight()) {
5215                         if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
5216                                 BeEcompErrorManager.getInstance().logBeGraphObjectMissingError("Create Resource - validateCapabilityTypesCreate", "Capability Type", typeEntry.getKey());
5217                                 log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", typeEntry.getKey(), resource.getName());
5218                                 BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateCapabilityTypesCreate");
5219                         }
5220                         log.debug("Trying to get capability type {} failed with error: {}", typeEntry.getKey(), eitherCapTypeFound.right().value().name());
5221                         ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, typeEntry.getKey());
5222                         eitherResult = Either.right(errorResponse);
5223                         componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null);
5224                 }
5225                 CapabilityTypeDefinition capabilityTypeDefinition = eitherCapTypeFound.left().value();
5226                 if (capabilityTypeDefinition.getProperties() != null) {
5227                         for (CapabilityDefinition capDef : typeEntry.getValue()) {
5228                                 List<ComponentInstanceProperty> properties = capDef.getProperties();
5229                                 if (properties == null || properties.isEmpty()) {
5230                                         properties = new ArrayList<ComponentInstanceProperty>();
5231                                         for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
5232                                                 ComponentInstanceProperty newProp = new ComponentInstanceProperty(prop.getValue());
5233                                                 properties.add(newProp);
5234                                         }
5235                                 } else {
5236                                         for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
5237                                                 PropertyDefinition porpFromDef = prop.getValue();
5238                                                 List<ComponentInstanceProperty> propsToAdd = new ArrayList<>();
5239                                                 for (ComponentInstanceProperty cip : properties) {
5240                                                         if (!cip.getName().equals(porpFromDef.getName())) {
5241                                                                 ComponentInstanceProperty newProp = new ComponentInstanceProperty(porpFromDef);
5242                                                                 propsToAdd.add(newProp);
5243                                                         }
5244                                                 }
5245                                                 if (!propsToAdd.isEmpty()) {
5246                                                         properties.addAll(propsToAdd);
5247                                                 }
5248                                         }
5249                                 }
5250                                 capDef.setProperties(properties);
5251                         }
5252                 }
5253                 return eitherResult;
5254         }
5255
5256         public Either<Resource, ResponseFormat> createResourceByDao(Resource resource, User user, AuditingActionEnum actionEnum, boolean isNormative, boolean inTransaction, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) {
5257                 // create resource
5258
5259                 // lock new resource name in order to avoid creation resource with same
5260                 // name
5261                 if (inTransaction == false) {
5262                         Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource, "Create Resource");
5263                         if (lockResult.isRight()) {
5264                                 ResponseFormat responseFormat = lockResult.right().value();
5265                                 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, additionalParams);
5266                                 return Either.right(responseFormat);
5267                         }
5268
5269                         log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
5270                 }
5271                 try {
5272                         if (resource.deriveFromGeneric()) {
5273                                 Either<Resource, ResponseFormat> genericResourceEither = fetchAndSetDerivedFromGenericType(resource);
5274                                 if (genericResourceEither.isRight())
5275                                         return genericResourceEither;
5276                                 if (resource.shouldGenerateInputs())
5277                                         generateInputsFromGenericTypeProperties(resource, genericResourceEither.left().value());
5278                         }
5279
5280                         Either<Resource, ResponseFormat> respStatus = createResourceTransaction(resource, user, isNormative, inTransaction);
5281                         if (respStatus.isLeft()) {
5282                                 auditCreateResource(user, respStatus.left().value(), actionEnum, additionalParams);
5283                                 ASDCKpiApi.countCreatedResourcesKPI();
5284                         } else
5285                                 componentsUtils.auditResource(respStatus.right().value(), user, resource, "", "", actionEnum, additionalParams);
5286                         return respStatus;
5287
5288                 } finally {
5289                         if (inTransaction == false) {
5290                                 graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(), NodeTypeEnum.Resource);
5291                         }
5292                 }
5293         }
5294
5295         private void auditCreateResource(User user, Resource persistedResource, AuditingActionEnum actionEnum, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) {
5296                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
5297                 componentsUtils.auditResource(responseFormat, user, persistedResource, "", "", actionEnum, additionalParams);
5298         }
5299
5300         private Either<Resource, ResponseFormat> createResourceTransaction(Resource resource, User user, boolean isNormative, boolean inTransaction) {
5301                 // validate resource name uniqueness
5302                 log.debug("validate resource name");
5303                 Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade.validateComponentNameExists(resource.getName(), resource.getResourceType(), resource.getComponentType());
5304                 if (eitherValidation.isRight()) {
5305                         log.debug("Failed to validate component name {}. Status is {}. ", resource.getName(), eitherValidation.right().value());
5306                         ResponseFormat errorResponse = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(eitherValidation.right().value()));
5307                         return Either.right(errorResponse);
5308                 }
5309                 if (eitherValidation.left().value()) {
5310                         log.debug("resource with name: {}, already exists", resource.getName());
5311                         ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
5312                         return Either.right(errorResponse);
5313                 }
5314
5315                 log.debug("send resource {} to dao for create", resource.getName());
5316
5317                 createArtifactsPlaceHolderData(resource, user);
5318
5319                 //
5320
5321                 // enrich object
5322                 if (!isNormative) {
5323                         log.debug("enrich resource with creator, version and state");
5324                         resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
5325                         resource.setVersion(INITIAL_VERSION);
5326                         resource.setHighestVersion(true);
5327                         if (resource.getResourceType() != null && resource.getResourceType() != ResourceTypeEnum.CVFC)
5328                                 resource.setAbstract(false);
5329                 }
5330
5331                 Either<Resource, StorageOperationStatus> createToscaElement = toscaOperationFacade.createToscaComponent(resource);
5332                 if (createToscaElement.isLeft()) {
5333                         return Either.left(createToscaElement.left().value());
5334                 }
5335
5336                 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(createToscaElement.right().value()), resource);
5337
5338                 return Either.right(responseFormat);
5339         }
5340
5341         private void createArtifactsPlaceHolderData(Resource resource, User user) {
5342                 // create mandatory artifacts
5343
5344                 // TODO it must be removed after that artifact uniqueId creation will be
5345                 // moved to ArtifactOperation
5346                 // String resourceUniqueId =
5347                 // UniqueIdBuilder.buildResourceUniqueId(resource.getResourceName(),
5348                 // resource.getResourceVersion());
5349
5350                 setInformationalArtifactsPlaceHolder(resource, user);
5351                 setDeploymentArtifactsPlaceHolder(resource, user);
5352                 setToscaArtifactsPlaceHolders(resource, user);
5353         }
5354
5355         @SuppressWarnings("unchecked")
5356         @Override
5357         public void setDeploymentArtifactsPlaceHolder(Component component, User user) {
5358                 Resource resource = (Resource) component;
5359                 Map<String, ArtifactDefinition> artifactMap = resource.getDeploymentArtifacts();
5360                 if (artifactMap == null) {
5361                         artifactMap = new HashMap<String, ArtifactDefinition>();
5362                 }
5363                 Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getDeploymentResourceArtifacts();
5364                 if (deploymentResourceArtifacts != null) {
5365                         Iterator<Entry<String, Object>> iterator = deploymentResourceArtifacts.entrySet().iterator();
5366                         while (iterator.hasNext()) {
5367                                 Entry<String, Object> currEntry = iterator.next();
5368                                 boolean shouldCreateArtifact = true;
5369                                 Map<String, Object> artifactDetails = (Map<String, Object>) currEntry.getValue();
5370                                 Object object = artifactDetails.get(PLACE_HOLDER_RESOURCE_TYPES);
5371                                 if (object != null) {
5372                                         List<String> artifactTypes = (List<String>) object;
5373                                         if (!artifactTypes.contains(resource.getResourceType().name())) {
5374                                                 shouldCreateArtifact = false;
5375                                                 continue;
5376                                         }
5377                                 } else {
5378                                         log.info("resource types for artifact placeholder {} were not defined. default is all resources", currEntry.getKey());
5379                                 }
5380                                 if (shouldCreateArtifact) {
5381                                         if (artifactsBusinessLogic != null) {
5382                                                 ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(resource.getUniqueId(), currEntry.getKey(), (Map<String, Object>) currEntry.getValue(), user, ArtifactGroupTypeEnum.DEPLOYMENT);
5383                                                 if (artifactDefinition != null && !artifactMap.containsKey(artifactDefinition.getArtifactLabel()))
5384                                                         artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
5385                                         }
5386                                 }
5387                         }
5388                 }
5389                 resource.setDeploymentArtifacts(artifactMap);
5390         }
5391
5392         @SuppressWarnings("unchecked")
5393         private void setInformationalArtifactsPlaceHolder(Resource resource, User user) {
5394                 Map<String, ArtifactDefinition> artifactMap = resource.getArtifacts();
5395                 if (artifactMap == null) {
5396                         artifactMap = new HashMap<String, ArtifactDefinition>();
5397                 }
5398                 String resourceUniqueId = resource.getUniqueId();
5399                 List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceCategory();
5400                 List<String> exludeResourceType = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceType();
5401                 Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getInformationalResourceArtifacts();
5402                 List<CategoryDefinition> categories = resource.getCategories();
5403                 boolean isCreateArtifact = true;
5404                 if (exludeResourceCategory != null) {
5405                         String category = categories.get(0).getName();
5406                         for (String exlude : exludeResourceCategory) {
5407                                 if (exlude.equalsIgnoreCase(category)) {
5408                                         isCreateArtifact = false;
5409                                         break;
5410                                 }
5411                         }
5412
5413                 }
5414                 if (isCreateArtifact && exludeResourceType != null) {
5415                         String resourceType = resource.getResourceType().name();
5416                         for (String type : exludeResourceType) {
5417                                 if (type.equalsIgnoreCase(resourceType)) {
5418                                         isCreateArtifact = false;
5419                                         break;
5420                                 }
5421                         }
5422
5423                 }
5424
5425                 if (informationalResourceArtifacts != null && isCreateArtifact) {
5426                         Set<String> keys = informationalResourceArtifacts.keySet();
5427                         for (String informationalResourceArtifactName : keys) {
5428                                 Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts.get(informationalResourceArtifactName);
5429                                 ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user, ArtifactGroupTypeEnum.INFORMATIONAL);
5430                                 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
5431
5432                         }
5433                 }
5434                 resource.setArtifacts(artifactMap);
5435         }
5436
5437         /**
5438          * deleteResource
5439          *
5440          * @param resourceId
5441          * @param user
5442          * @return
5443          */
5444         public ResponseFormat deleteResource(String resourceId, User user) {
5445                 ResponseFormat responseFormat;
5446                 Either<User, ResponseFormat> eitherCreator = validateUserExists(user, "Delete Resource", false);
5447                 if (eitherCreator.isRight()) {
5448                         return eitherCreator.right().value();
5449                 }
5450
5451                 Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade.getToscaElement(resourceId);
5452                 if (resourceStatus.isRight()) {
5453                         log.debug("failed to get resource {}", resourceId);
5454                         return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceStatus.right().value()), "");
5455                 }
5456
5457                 Resource resource = resourceStatus.left().value();
5458
5459                 StorageOperationStatus result = StorageOperationStatus.OK;
5460                 Either<Boolean, ResponseFormat> lockResult = lockComponent(resourceId, resource, "Mark resource to delete");
5461                 if (lockResult.isRight()) {
5462                         result = StorageOperationStatus.GENERAL_ERROR;
5463                         return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
5464                 }
5465
5466                 try {
5467
5468                         result = markComponentToDelete(resource);
5469                         if (result.equals(StorageOperationStatus.OK)) {
5470                                 responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
5471                         } else {
5472                                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
5473                                 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName());
5474                         }
5475                         return responseFormat;
5476
5477                 } finally {
5478                         if (result == null || !result.equals(StorageOperationStatus.OK)) {
5479                                 log.warn("operation failed. do rollback");
5480                                 titanDao.rollback();
5481                         } else {
5482                                 log.debug("operation success. do commit");
5483                                 titanDao.commit();
5484                         }
5485                         graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource);
5486                 }
5487
5488         }
5489
5490         public ResponseFormat deleteResourceByNameAndVersion(String resourceName, String version, User user) {
5491                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
5492                 Either<User, ResponseFormat> eitherCreator = validateUserExists(user, "Delete Resource", false);
5493                 if (eitherCreator.isRight()) {
5494                         return eitherCreator.right().value();
5495                 }
5496
5497                 // Resource resource = null;
5498                 Resource resource = null;
5499                 StorageOperationStatus result = StorageOperationStatus.OK;
5500                 try {
5501
5502                         Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, version);
5503                         if (resourceStatus.isRight()) {
5504                                 log.debug("failed to get resource {} version {}", resourceName, version);
5505                                 return componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(resourceStatus.right().value()), resourceName);
5506                         }
5507
5508                         resource = resourceStatus.left().value();
5509
5510                 } finally {
5511                         if (result == null || !result.equals(StorageOperationStatus.OK)) {
5512                                 log.warn("operation failed. do rollback");
5513                                 titanDao.rollback();
5514                                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
5515                                 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resourceName);
5516                         } else {
5517                                 log.debug("operation success. do commit");
5518                                 titanDao.commit();
5519                         }
5520                 }
5521                 if (resource != null) {
5522                         Either<Boolean, ResponseFormat> lockResult = lockComponent(resource.getUniqueId(), resource, "Delete Resource");
5523                         if (lockResult.isRight()) {
5524                                 result = StorageOperationStatus.GENERAL_ERROR;
5525                                 return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
5526                         }
5527                         try {
5528                                 result = markComponentToDelete(resource);
5529                                 if (!result.equals(StorageOperationStatus.OK)) {
5530                                         ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
5531                                         responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName());
5532                                         return responseFormat;
5533                                 }
5534
5535                         } finally {
5536                                 if (result == null || !result.equals(StorageOperationStatus.OK)) {
5537                                         log.warn("operation failed. do rollback");
5538                                         titanDao.rollback();
5539                                 } else {
5540                                         log.debug("operation success. do commit");
5541                                         titanDao.commit();
5542                                 }
5543                                 graphLockOperation.unlockComponent(resource.getUniqueId(), NodeTypeEnum.Resource);
5544                         }
5545                 }
5546                 return responseFormat;
5547         }
5548
5549         public Either<Resource, ResponseFormat> getResource(String resourceId, User user) {
5550
5551                 if (user != null) {
5552                         Either<User, ResponseFormat> eitherCreator = validateUserExists(user, "Create Resource", false);
5553                         if (eitherCreator.isRight()) {
5554                                 return Either.right(eitherCreator.right().value());
5555                         }
5556                 }
5557
5558                 // IResourceOperation dataModel = getResourceOperation();
5559                 Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(resourceId);
5560
5561                 if (storageStatus.isRight()) {
5562                         log.debug("failed to get resource by id {}", resourceId);
5563                         return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), ""));
5564                 }
5565                 return Either.left(storageStatus.left().value());
5566
5567         }
5568
5569         public Either<Resource, ResponseFormat> getResourceByNameAndVersion(String resourceName, String resourceVersion, String userId) {
5570
5571                 Either<User, ResponseFormat> resp = validateUserExists(userId, "get Resource By Name And Version", false);
5572                 if (resp.isRight()) {
5573                         return Either.right(resp.right().value());
5574                 }
5575
5576                 Either<Resource, StorageOperationStatus> getResource = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion);
5577                 if (getResource.isRight()) {
5578                         log.debug("failed to get resource by name {} and version {}", resourceName, resourceVersion);
5579                         return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(getResource.right().value()), resourceName));
5580                 }
5581                 return Either.left(getResource.left().value());
5582         }
5583
5584         /**
5585          * updateResourceMetadata
5586          *
5587          * @param user               - modifier data (userId)
5588          * @param inTransaction      TODO
5589          * @param resourceIdToUpdate - the resource identifier
5590          * @param newResource
5591          * @return Either<Resource, responseFormat>
5592          */
5593         public Either<Resource, ResponseFormat> updateResourceMetadata(String resourceIdToUpdate, Resource newResource, Resource currentResource, User user, boolean inTransaction) {
5594
5595                 Either<User, ResponseFormat> resp = validateUserExists(user.getUserId(), "update Resource Metadata", false);
5596                 if (resp.isRight()) {
5597                         return Either.right(resp.right().value());
5598                 }
5599
5600                 // IResourceOperation dataModel = getResourceOperation();
5601                 log.debug("Get resource with id {}", resourceIdToUpdate);
5602                 boolean needToUnlock = false;
5603                 boolean rollbackNeeded = true;
5604
5605                 try {
5606                         // Either<Resource, StorageOperationStatus> storageStatus =
5607                         // dataModel.getResource_tx(resourceIdToUpdate, false);
5608                         if (currentResource == null) {
5609                                 Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(resourceIdToUpdate);
5610                                 if (storageStatus.isRight()) {
5611                                         return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), ""));
5612                                 }
5613
5614                                 currentResource = storageStatus.left().value();
5615                         }
5616                         // verify that resource is checked-out and the user is the last
5617                         // updater
5618                         if (!ComponentValidationUtils.canWorkOnResource(currentResource, user.getUserId())) {
5619                                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
5620                         }
5621
5622                         // lock resource
5623                         StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceIdToUpdate, NodeTypeEnum.Resource);
5624                         if (!lockResult.equals(StorageOperationStatus.OK)) {
5625                                 BeEcompErrorManager.getInstance().logBeFailedLockObjectError("Upload Artifact - lock ", NodeTypeEnum.Resource.getName(), resourceIdToUpdate);
5626                                 log.debug("Failed to lock resource: {}, error - {}", resourceIdToUpdate, lockResult);
5627                                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockResult));
5628                                 return Either.right(responseFormat);
5629                         }
5630
5631                         needToUnlock = true;
5632
5633                         // critical section starts here
5634                         // convert json to object
5635
5636                         // Update and updated resource must have a non-empty "derivedFrom"
5637                         // list
5638                         // This code is not called from import resources, because of root
5639                         // VF "derivedFrom" should be null (or ignored)
5640                         if (ToscaUtils.isAtomicType(currentResource)) {
5641                                 Either<Boolean, ResponseFormat> derivedFromNotEmptyEither = validateDerivedFromNotEmpty(null, newResource, null);
5642                                 if (derivedFromNotEmptyEither.isRight()) {
5643                                         log.debug("for updated resource {}, derived from field is empty", newResource.getName());
5644                                         return Either.right(derivedFromNotEmptyEither.right().value());
5645                                 }
5646
5647                                 derivedFromNotEmptyEither = validateDerivedFromNotEmpty(null, currentResource, null);
5648                                 if (derivedFromNotEmptyEither.isRight()) {
5649                                         log.debug("for current resource {}, derived from field is empty", currentResource.getName());
5650                                         return Either.right(derivedFromNotEmptyEither.right().value());
5651                                 }
5652                         } else {
5653                                 newResource.setDerivedFrom(null);
5654                         }
5655
5656                         Either<Resource, ResponseFormat> dataModelResponse = updateResourceMetadata(resourceIdToUpdate, newResource, user, currentResource, false, true);
5657                         if (dataModelResponse.isRight()) {
5658                                 log.debug("failed to update resource metadata!!!");
5659                                 rollbackNeeded = true;
5660                                 return Either.right(dataModelResponse.right().value());
5661                         }
5662
5663                         log.debug("Resource metadata updated successfully!!!");
5664                         rollbackNeeded = false;
5665                         return Either.left(dataModelResponse.left().value());
5666
5667                 } finally {
5668                         if (!inTransaction) {
5669                                 if (rollbackNeeded) {
5670                                         titanDao.rollback();
5671                                 } else {
5672                                         titanDao.commit();
5673                                 }
5674                         }
5675
5676                         if (needToUnlock) {
5677                                 graphLockOperation.unlockComponent(resourceIdToUpdate, NodeTypeEnum.Resource);
5678                         }
5679                 }
5680         }
5681
5682         private Either<List<GroupDefinition>,Boolean> updateComponentGroupName(String replacePattern , String with ,List<GroupDefinition> oldGroup){
5683                 if ( oldGroup==null || with==null || replacePattern==null || with.isEmpty() || replacePattern.isEmpty()){
5684                         if (log.isInfoEnabled())
5685                                 log.info("cannot update group name , invalid args -> replacePattern:{} , with:{} , oldGroup:{}" , replacePattern, with, oldGroup == null ? null : " < size : "+oldGroup.size()+" >" );
5686                         return Either.right(false);
5687                 }
5688                 List<GroupDefinition> list = oldGroup.stream().map( group -> new GroupDefinition(group)).collect(Collectors.toList());
5689                 for ( GroupDefinition group : list) {
5690                         if ( group!=null && group.isSamePrefix( replacePattern ) ){
5691                                 String prefix = group.getName().substring( 0, replacePattern.length() );
5692                                 String newGroupName = group.getName().replaceFirst(prefix , with);
5693                                 group.setName(newGroupName);
5694                                 //String newUid = group.getUniqueId().replaceFirst(prefix , with); //removing this will also change the unique id
5695                                 //group.setUniqueId(newUid);
5696                         }
5697                 }
5698                 return Either.left(list);
5699         }
5700
5701         private boolean isComponentNameChanged(Resource newResource,Resource oldResource){
5702                 if (newResource!=null &&  oldResource!=null){   //TODO - must protect all chain against null , use optional
5703                         String futureName = newResource.getComponentMetadataDefinition().getMetadataDataDefinition().getName();
5704                         String oldName = oldResource.getComponentMetadataDefinition().getMetadataDataDefinition().getName();
5705                         return !oldName.equals(futureName);
5706                 }
5707                 return false;
5708         }
5709
5710         private Either<Resource, ResponseFormat> updateResourceMetadata(String resourceIdToUpdate, Resource newResource, User user, Resource currentResource, boolean shouldLock, boolean inTransaction) {
5711                 //region -> Update groups name for newResource
5712                 if ( isComponentNameChanged( currentResource , newResource) ){
5713                         String replacePattern = Optional.ofNullable(    //get currentResource name from metadata
5714                                         Optional.ofNullable( Optional.ofNullable( currentResource )
5715                                                         .orElse(null).getComponentMetadataDefinition() )
5716                                                         .orElse(null).getMetadataDataDefinition() )
5717                                         .orElse(null).getName();
5718                         String with = Optional.ofNullable(                              //get newResource name from metadata
5719                                         Optional.ofNullable( Optional.ofNullable( newResource )
5720                                                         .orElse(null).getComponentMetadataDefinition() )
5721                                                         .orElse(null).getMetadataDataDefinition() )
5722                                         .orElse(null).getName();
5723                         if ( with != null  && replacePattern != null ){
5724                                 Either result = updateComponentGroupName( replacePattern , with  ,currentResource.getGroups());
5725                                 if (result.isLeft())
5726                                         newResource.setGroups( (List<GroupDefinition>)result.left().value() );
5727                         }
5728                 }
5729                 //endregion
5730
5731                 Either<Boolean, ResponseFormat> validateResourceFields = validateResourceFieldsBeforeUpdate(currentResource, newResource, inTransaction);
5732                 if (validateResourceFields.isRight()) {
5733                         return Either.right(validateResourceFields.right().value());
5734                 }
5735                 // Setting last updater and uniqueId
5736                 newResource.setContactId(newResource.getContactId().toLowerCase());
5737                 newResource.setLastUpdaterUserId(user.getUserId());
5738                 newResource.setUniqueId(resourceIdToUpdate);
5739                 // Cannot set highest version through UI
5740                 newResource.setHighestVersion(currentResource.isHighestVersion());
5741                 newResource.setCreationDate(currentResource.getCreationDate());
5742
5743                 Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom = processUpdateOfDerivedFrom(currentResource, newResource, user.getUserId(), shouldLock, inTransaction);
5744
5745                 if (processUpdateOfDerivedFrom.isRight()) {
5746                         log.debug("Couldn't update derived from for resource {}", resourceIdToUpdate);
5747                         return Either.right(processUpdateOfDerivedFrom.right().value());
5748                 }
5749
5750                 log.debug("send resource {} to dao for update", newResource.getUniqueId());
5751                 if (newResource!=null && newResource.getGroups()!=null){
5752                         for ( GroupDefinition group : newResource.getGroups() ){
5753                                 if (newResource.getComponentMetadataDefinition()!=null && newResource.getComponentMetadataDefinition().getMetadataDataDefinition()!=null)
5754                                 groupBusinessLogic.validateAndUpdateGroupMetadata(
5755                                                 newResource.getComponentMetadataDefinition().getMetadataDataDefinition().getUniqueId() ,
5756                                                 user,
5757                                                 ComponentTypeEnum.RESOURCE_INSTANCE,
5758                                                 group,
5759                                                 true ,
5760                                                 false) ;
5761                         }
5762                 }
5763                 Either<Resource, StorageOperationStatus> dataModelResponse = toscaOperationFacade.updateToscaElement(newResource);
5764
5765                 if (dataModelResponse.isRight()) {
5766                         ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()), newResource);
5767                         return Either.right(responseFormat);
5768                 } else if (dataModelResponse.left().value() == null) {
5769                         log.debug("No response from updateResource");
5770                         return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
5771                 }
5772                 return Either.left(dataModelResponse.left().value());
5773         }
5774
5775         /**
5776          * validateResourceFieldsBeforeCreate
5777          *
5778          * @param user      - modifier data (userId)
5779          * @param dataModel - IResourceOperation for resource crud
5780          * @param resource  - Resource object to validate
5781          * @return Either<Boolean, ErrorResponse>
5782          */
5783         private Either<Boolean, ResponseFormat> validateResourceFieldsBeforeCreate(User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
5784                 Either<Boolean, ResponseFormat> componentsFieldsValidation = validateComponentFieldsBeforeCreate(user, resource, actionEnum);
5785                 if (componentsFieldsValidation.isRight()) {
5786                         return componentsFieldsValidation;
5787                 }
5788
5789                 // validate name
5790
5791                 /*
5792                  * log.debug("validate resource name"); Either<Boolean, ResponseFormat> eitherValidation = validateComponentName(user, resource, actionEnum); if (eitherValidation.isRight()) { return eitherValidation; }
5793                  *
5794                  * // validate description log.debug("validate description"); eitherValidation = validateDescriptionAndCleanup(user, resource, actionEnum); if (eitherValidation.isRight()) { return eitherValidation; }
5795                  */
5796
5797                 // validate icon
5798                 /*
5799                  * log.debug("validate icon"); eitherValidation = validateIcon(user, resource, actionEnum); if (eitherValidation.isRight()) { return eitherValidation; }
5800                  */
5801
5802                 // validate tags
5803                 /*
5804                  * log.debug("validate tags"); eitherValidation = validateTagsListAndRemoveDuplicates(user, resource, actionEnum); if (eitherValidation.isRight()) { return eitherValidation; }
5805                  */
5806
5807                 // validate category
5808                 log.debug("validate category");
5809                 Either<Boolean, ResponseFormat> eitherValidation = validateCategory(user, resource, actionEnum, inTransaction);
5810                 if (eitherValidation.isRight()) {
5811                         return eitherValidation;
5812                 }
5813
5814                 // validate vendor name & release & model number
5815                 log.debug("validate vendor name");
5816                 eitherValidation = validateVendorName(user, resource, actionEnum);
5817                 if (eitherValidation.isRight()) {
5818                         return eitherValidation;
5819                 }
5820
5821                 log.debug("validate vendor release");
5822                 eitherValidation = validateVendorReleaseName(user, resource, actionEnum);
5823                 if (eitherValidation.isRight()) {
5824                         return eitherValidation;
5825                 }
5826
5827                 log.debug("validate resource vendor model number");
5828                 eitherValidation = validateResourceVendorModelNumber(user, resource, actionEnum);
5829                 if (eitherValidation.isRight()) {
5830                         return eitherValidation;
5831                 }
5832
5833                 // validate contact info
5834                 /*
5835                  * log.debug("validate contact info"); eitherValidation = validateContactIdContactId(user, resource, actionEnum); if (eitherValidation.isRight()) { return eitherValidation; }
5836                  */
5837
5838                 // validate cost
5839                 log.debug("validate cost");
5840                 eitherValidation = validateCost(user, resource, actionEnum);
5841                 if (eitherValidation.isRight()) {
5842                         return eitherValidation;
5843                 }
5844
5845                 // validate licenseType
5846                 log.debug("validate licenseType");
5847                 eitherValidation = validateLicenseType(user, resource, actionEnum);
5848                 if (eitherValidation.isRight()) {
5849                         return eitherValidation;
5850                 }
5851
5852                 // validate template (derived from)
5853                 log.debug("validate derived from");
5854                 if (!ToscaUtils.isAtomicType(resource) && resource.getResourceType() != ResourceTypeEnum.CVFC) {
5855                         resource.setDerivedFrom(null);
5856                 }
5857                 eitherValidation = validateDerivedFromExist(user, resource, actionEnum);
5858                 if (eitherValidation.isRight()) {
5859                         return Either.right(eitherValidation.right().value());
5860                 }
5861
5862                 // warn about non-updatable fields
5863                 checkComponentFieldsForOverrideAttempt(resource);
5864                 String currentCreatorFullName = resource.getCreatorFullName();
5865                 if (currentCreatorFullName != null) {
5866                         log.warn("Resource Creator fullname is automatically set and cannot be updated");
5867                 }
5868
5869                 String currentLastUpdaterFullName = resource.getLastUpdaterFullName();
5870                 if (currentLastUpdaterFullName != null) {
5871                         log.warn("Resource LastUpdater fullname is automatically set and cannot be updated");
5872                 }
5873
5874                 Long currentLastUpdateDate = resource.getLastUpdateDate();
5875                 if (currentLastUpdateDate != null) {
5876                         log.warn("Resource last update date is automatically set and cannot be updated");
5877                 }
5878
5879                 Boolean currentAbstract = resource.isAbstract();
5880                 if (currentAbstract != null) {
5881                         log.warn("Resource abstract is automatically set and cannot be updated");
5882                 }
5883
5884                 return Either.left(true);
5885         }
5886
5887         /**
5888          * validateResourceFieldsBeforeUpdate
5889          *
5890          * @param currentResource - Resource object to validate
5891          * @return Either<Boolean, ErrorResponse>
5892          */
5893         private Either<Boolean, ResponseFormat> validateResourceFieldsBeforeUpdate(Resource currentResource, Resource updateInfoResource, boolean inTransaction) {
5894
5895                 boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentResource.getVersion());
5896
5897                 // validate resource name
5898                 log.debug("validate resource name before update");
5899                 Either<Boolean, ResponseFormat> eitherValidation = validateResourceName(currentResource, updateInfoResource, hasBeenCertified);
5900                 if (eitherValidation.isRight()) {
5901                         return eitherValidation;
5902                 }
5903
5904                 // validate description
5905                 log.debug("validate description before update");
5906                 eitherValidation = validateDescriptionAndCleanup(null, updateInfoResource, null);
5907                 if (eitherValidation.isRight()) {
5908                         return eitherValidation;
5909                 }
5910
5911                 log.debug("validate icon before update");
5912                 eitherValidation = validateIcon(currentResource, updateInfoResource, hasBeenCertified);
5913                 if (eitherValidation.isRight()) {
5914                         return eitherValidation;
5915                 }
5916
5917                 log.debug("validate tags before update");
5918                 eitherValidation = validateTagsListAndRemoveDuplicates(null, updateInfoResource, null);
5919                 if (eitherValidation.isRight()) {
5920                         return eitherValidation;
5921                 }
5922
5923                 log.debug("validate vendor name before update");
5924                 eitherValidation = validateVendorName(currentResource, updateInfoResource, hasBeenCertified);
5925                 if (eitherValidation.isRight()) {
5926                         return eitherValidation;
5927                 }
5928
5929                 log.debug("validate resource vendor model number before update");
5930                 eitherValidation = validateResourceVendorModelNumber(currentResource, updateInfoResource);
5931                 if (eitherValidation.isRight()) {
5932                         return eitherValidation;
5933                 }
5934
5935
5936                 log.debug("validate vendor release before update");
5937                 eitherValidation = validateVendorReleaseName(null, updateInfoResource, null);
5938                 if (eitherValidation.isRight()) {
5939                         return eitherValidation;
5940                 }
5941
5942                 log.debug("validate contact info before update");
5943                 eitherValidation = validateContactId(null, updateInfoResource, null);
5944                 if (eitherValidation.isRight()) {
5945                         return eitherValidation;
5946                 }
5947
5948                 log.debug("validate derived before update");
5949                 eitherValidation = validateDerivedFromDuringUpdate(currentResource, updateInfoResource, hasBeenCertified);
5950                 if (eitherValidation.isRight()) {
5951                         return eitherValidation;
5952                 }
5953
5954                 log.debug("validate category before update");
5955                 eitherValidation = validateCategory(currentResource, updateInfoResource, hasBeenCertified, inTransaction);
5956                 if (eitherValidation.isRight()) {
5957                         return eitherValidation;
5958                 }
5959
5960                 // warn about non-updatable fields
5961                 String currentResourceVersion = currentResource.getVersion();
5962                 String updatedResourceVersion = updateInfoResource.getVersion();
5963
5964                 if ((updatedResourceVersion != null) && (!updatedResourceVersion.equals(currentResourceVersion))) {
5965                         log.warn("Resource version is automatically set and cannot be updated");
5966                 }
5967
5968                 String currentCreatorUserId = currentResource.getCreatorUserId();
5969                 String updatedCreatorUserId = updateInfoResource.getCreatorUserId();
5970
5971                 if ((updatedCreatorUserId != null) && (!updatedCreatorUserId.equals(currentCreatorUserId))) {
5972                         log.warn("Resource Creator UserId is automatically set and cannot be updated");
5973                 }
5974
5975                 String currentCreatorFullName = currentResource.getCreatorFullName();
5976                 String updatedCreatorFullName = updateInfoResource.getCreatorFullName();
5977
5978                 if ((updatedCreatorFullName != null) && (!updatedCreatorFullName.equals(currentCreatorFullName))) {
5979                         log.warn("Resource Creator fullname is automatically set and cannot be updated");
5980                 }
5981
5982                 String currentLastUpdaterUserId = currentResource.getLastUpdaterUserId();
5983                 String updatedLastUpdaterUserId = updateInfoResource.getLastUpdaterUserId();
5984
5985                 if ((updatedLastUpdaterUserId != null) && (!updatedLastUpdaterUserId.equals(currentLastUpdaterUserId))) {
5986                         log.warn("Resource LastUpdater userId is automatically set and cannot be updated");
5987                 }
5988
5989                 String currentLastUpdaterFullName = currentResource.getLastUpdaterFullName();
5990                 String updatedLastUpdaterFullName = updateInfoResource.getLastUpdaterFullName();
5991
5992                 if ((updatedLastUpdaterFullName != null) && (!updatedLastUpdaterFullName.equals(currentLastUpdaterFullName))) {
5993                         log.warn("Resource LastUpdater fullname is automatically set and cannot be updated");
5994                 }
5995
5996                 Long currentCreationDate = currentResource.getCreationDate();
5997                 Long updatedCreationDate = updateInfoResource.getCreationDate();
5998
5999                 if ((updatedCreationDate != null) && (!updatedCreationDate.equals(currentCreationDate))) {
6000                         log.warn("Resource Creation date is automatically set and cannot be updated");
6001                 }
6002
6003                 Long currentLastUpdateDate = currentResource.getLastUpdateDate();
6004                 Long updatedLastUpdateDate = updateInfoResource.getLastUpdateDate();
6005
6006                 if ((updatedLastUpdateDate != null) && (!updatedLastUpdateDate.equals(currentLastUpdateDate))) {
6007                         log.warn("Resource last update date is automatically set and cannot be updated");
6008                 }
6009
6010                 LifecycleStateEnum currentLifecycleState = currentResource.getLifecycleState();
6011                 LifecycleStateEnum updatedLifecycleState = updateInfoResource.getLifecycleState();
6012
6013                 if ((updatedLifecycleState != null) && (!updatedLifecycleState.equals(currentLifecycleState))) {
6014                         log.warn("Resource lifecycle state date is automatically set and cannot be updated");
6015                 }
6016
6017                 Boolean currentAbstract = currentResource.isAbstract();
6018                 Boolean updatedAbstract = updateInfoResource.isAbstract();
6019
6020                 if ((updatedAbstract != null) && (!updatedAbstract.equals(currentAbstract))) {
6021                         log.warn("Resource abstract is automatically set and cannot be updated");
6022                 }
6023
6024                 Boolean currentHighestVersion = currentResource.isHighestVersion();
6025                 Boolean updatedHighestVersion = updateInfoResource.isHighestVersion();
6026
6027                 if ((updatedHighestVersion != null) && (!updatedHighestVersion.equals(currentHighestVersion))) {
6028                         log.warn("Resource highest version is automatically set and cannot be updated");
6029                 }
6030
6031                 String currentUuid = currentResource.getUUID();
6032                 String updatedUuid = updateInfoResource.getUUID();
6033
6034                 if ((updatedUuid != null) && (!updatedUuid.equals(currentUuid))) {
6035                         log.warn("Resource UUID is automatically set and cannot be updated");
6036                 }
6037
6038                 ResourceTypeEnum currentResourceType = currentResource.getResourceType();
6039                 ResourceTypeEnum updatedResourceType = updateInfoResource.getResourceType();
6040
6041                 if ((updatedResourceType != null) && (!updatedResourceType.equals(currentResourceType))) {
6042                         log.warn("Resource Type  cannot be updated");
6043
6044                 }
6045                 updateInfoResource.setResourceType(currentResource.getResourceType());
6046
6047                 String currentInvariantUuid = currentResource.getInvariantUUID();
6048                 String updatedInvariantUuid = updateInfoResource.getInvariantUUID();
6049
6050                 if ((updatedInvariantUuid != null) && (!updatedInvariantUuid.equals(currentInvariantUuid))) {
6051                         log.warn("Resource invariant UUID is automatically set and cannot be updated");
6052                         updateInfoResource.setInvariantUUID(currentInvariantUuid);
6053                 }
6054                 return Either.left(true);
6055         }
6056
6057         /*
6058          * private Either<Boolean, ResponseFormat> validateResourceName(User user, Resource resource, AuditingActionEnum actionEnum) { log.debug("validate resource name is not empty"); String resourceName = resource.getResourceName();
6059          *
6060          * if (!ValidationUtils.validateStringNotEmpty(resourceName)) { log.debug("Resource name is empty"); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue());
6061          * componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); return Either.right(responseFormat); }
6062          *
6063          * if (!ValidationUtils.validateResourceNameLength(resourceName)) { log.debug("Resource name is exceeds max length {} ", ValidationUtils.RESOURCE_NAME_MAX_LENGTH); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.
6064          * COMPONENT_NAME_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.RESOURCE_NAME_MAX_LENGTH); componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); return Either.right(responseFormat);
6065          * }
6066          *
6067          * if (!ValidationUtils.validateResourceName(resourceName)) { log.debug("Resource name {} has invalid format", resourceName); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPONENT_NAME,
6068          * ComponentTypeEnum.RESOURCE.getValue()); componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); return Either.right(responseFormat); } resource.setNormalizedName(ValidationUtils.normaliseComponentName(
6069          * resourceName)); resource.setSystemName(ValidationUtils.convertToSystemName(resourceName)) ;
6070          *
6071          * return Either.left(true); }
6072          */
6073
6074         private Either<Boolean, ResponseFormat> validateResourceName(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) {
6075                 String resourceNameUpdated = updateInfoResource.getName();
6076                 String resourceNameCurrent = currentResource.getName();
6077                 if (!resourceNameCurrent.equals(resourceNameUpdated)) {
6078                         if (!hasBeenCertified) {
6079                                 Either<Boolean, ResponseFormat> validateResourceNameResponse = validateComponentName(null, updateInfoResource, null);
6080                                 if (validateResourceNameResponse.isRight()) {
6081                                         ResponseFormat errorResponse = validateResourceNameResponse.right().value();
6082                                         return Either.right(errorResponse);
6083                                 }
6084                                 validateResourceNameResponse = validateResourceNameExists(updateInfoResource);
6085                                 if (validateResourceNameResponse.isRight()) {
6086                                         ResponseFormat errorResponse = validateResourceNameResponse.right().value();
6087                                         return Either.right(errorResponse);
6088                                 }
6089                                 currentResource.setName(resourceNameUpdated);
6090                                 currentResource.setNormalizedName(ValidationUtils.normaliseComponentName(resourceNameUpdated));
6091                                 currentResource.setSystemName(ValidationUtils.convertToSystemName(resourceNameUpdated));
6092
6093                         } else {
6094                                 log.info("Resource name: {}, cannot be updated once the resource has been certified once.", resourceNameUpdated);
6095                                 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED);
6096                                 return Either.right(errorResponse);
6097                         }
6098                 }
6099                 return Either.left(true);
6100         }
6101
6102         private Either<Boolean, ResponseFormat> validateIcon(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) {
6103                 String iconUpdated = updateInfoResource.getIcon();
6104                 String iconCurrent = currentResource.getIcon();
6105                 if (!iconCurrent.equals(iconUpdated)) {
6106                         if (!hasBeenCertified) {
6107                                 Either<Boolean, ResponseFormat> validateIcon = validateIcon(null, updateInfoResource, null);
6108                                 if (validateIcon.isRight()) {
6109                                         ResponseFormat errorResponse = validateIcon.right().value();
6110                                         return Either.right(errorResponse);
6111                                 }
6112                         } else {
6113                                 log.info("Icon {} cannot be updated once the resource has been certified once.", iconUpdated);
6114                                 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED);
6115                                 return Either.right(errorResponse);
6116                         }
6117                 }
6118                 return Either.left(true);
6119         }
6120
6121         private Either<Boolean, ResponseFormat> validateVendorName(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) {
6122                 String vendorNameUpdated = updateInfoResource.getVendorName();
6123                 String vendorNameCurrent = currentResource.getVendorName();
6124                 if (!vendorNameCurrent.equals(vendorNameUpdated)) {
6125                         if (!hasBeenCertified) {
6126                                 Either<Boolean, ResponseFormat> validateVendorName = validateVendorName(null, updateInfoResource, null);
6127                                 if (validateVendorName.isRight()) {
6128                                         ResponseFormat errorResponse = validateVendorName.right().value();
6129                                         return Either.right(errorResponse);
6130                                 }
6131                         } else {
6132                                 log.info("Vendor name {} cannot be updated once the resource has been certified once.", vendorNameUpdated);
6133                                 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_VENDOR_NAME_CANNOT_BE_CHANGED);
6134                                 return Either.right(errorResponse);
6135                         }
6136                 }
6137                 return Either.left(true);
6138         }
6139
6140         private Either<Boolean, ResponseFormat> validateResourceVendorModelNumber(Resource currentResource, Resource updateInfoResource) {
6141                 String updatedResourceVendorModelNumber = updateInfoResource.getResourceVendorModelNumber();
6142                 String currentResourceVendorModelNumber = currentResource.getResourceVendorModelNumber();
6143                 if (!currentResourceVendorModelNumber.equals(updatedResourceVendorModelNumber)) {
6144                         Either<Boolean, ResponseFormat> validateResourceVendorModelNumber = validateResourceVendorModelNumber(null, updateInfoResource, null);
6145                         if (validateResourceVendorModelNumber.isRight()) {
6146                                 ResponseFormat errorResponse = validateResourceVendorModelNumber.right().value();
6147                                 return Either.right(errorResponse);
6148                         }
6149                 }
6150                 return Either.left(true);
6151         }
6152
6153         private Either<Boolean, ResponseFormat> validateCategory(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified, boolean inTransaction) {
6154                 Either<Boolean, ResponseFormat> validateCategoryName = validateCategory(null, updateInfoResource, null, inTransaction);
6155                 if (validateCategoryName.isRight()) {
6156                         ResponseFormat errorResponse = validateCategoryName.right().value();
6157                         return Either.right(errorResponse);
6158                 }
6159                 if (hasBeenCertified) {
6160                         CategoryDefinition currentCategory = currentResource.getCategories().get(0);
6161                         SubCategoryDefinition currentSubCategory = currentCategory.getSubcategories().get(0);
6162                         CategoryDefinition updateCategory = updateInfoResource.getCategories().get(0);
6163                         SubCategoryDefinition updtaeSubCategory = updateCategory.getSubcategories().get(0);
6164                         if (!currentCategory.getName().equals(updateCategory.getName()) || !currentSubCategory.getName().equals(updtaeSubCategory.getName())) {
6165                                 log.info("Category {} cannot be updated once the resource has been certified once.", currentResource.getCategories());
6166                                 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CATEGORY_CANNOT_BE_CHANGED);
6167                                 return Either.right(errorResponse);
6168                         }
6169                 }
6170                 return Either.left(true);
6171         }
6172
6173         private Either<Boolean, ResponseFormat> validateDerivedFromDuringUpdate(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) {
6174
6175                 List<String> currentDerivedFrom = currentResource.getDerivedFrom();
6176                 List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
6177                 if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null || updatedDerivedFrom.isEmpty()) {
6178                         log.trace("Update normative types");
6179                         return Either.left(true);
6180                 }
6181
6182                 String derivedFromCurrent = currentDerivedFrom.get(0);
6183                 String derivedFromUpdated = updatedDerivedFrom.get(0);
6184
6185                 if (!derivedFromCurrent.equals(derivedFromUpdated)) {
6186                         if (!hasBeenCertified) {
6187                                 Either<Boolean, ResponseFormat> validateDerivedFromExistsEither = validateDerivedFromExist(null, updateInfoResource, null);
6188                                 if (validateDerivedFromExistsEither.isRight()) {
6189                                         return validateDerivedFromExistsEither;
6190                                 }
6191                         } else {
6192                                 Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null, currentResource, updateInfoResource, null);
6193
6194                                 if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left().value()) {
6195                                         log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
6196                                         return validateDerivedFromExtending;
6197                                 }
6198                         }
6199                 } else {
6200                         // For derived from, we must know whether it was actually changed,
6201                         // otherwise we must do no action.
6202                         // Due to changes it inflicts on data model (remove artifacts,
6203                         // properties...), it's not like a flat field which can be
6204                         // overwritten if not changed.
6205                         // So we must indicate that derived from is not changed
6206                         updateInfoResource.setDerivedFrom(null);
6207                 }
6208                 return Either.left(true);
6209         }
6210
6211         private Either<Boolean, ResponseFormat> validateDerivedFromExist(User user, Resource resource, AuditingActionEnum actionEnum) {
6212
6213                 if (resource.getDerivedFrom() == null || resource.getDerivedFrom().isEmpty()) {
6214                         return Either.left(true);
6215                 }
6216
6217                 // IResourceOperation resourceOperation = getResourceOperation();
6218
6219                 String templateName = resource.getDerivedFrom().get(0);
6220
6221                 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateToscaResourceNameExists(templateName);
6222                 if (dataModelResponse.isRight()) {
6223                         StorageOperationStatus storageStatus = dataModelResponse.right().value();
6224                         BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "Create Resource - validateDerivedFromExist");
6225                         BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateDerivedFromExist");
6226                         log.debug("request to data model failed with error: {}", storageStatus.name());
6227                         ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), resource);
6228                         log.trace("audit before sending response");
6229                         componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
6230                         return Either.right(responseFormat);
6231                 } else if (!dataModelResponse.left().value()) {
6232                         log.info("resource template with name: {}, does not exists", templateName);
6233                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
6234                         componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
6235
6236                         return Either.right(responseFormat);
6237
6238                 }
6239                 return Either.left(true);
6240         }
6241
6242         // Tal G for extending inheritance US815447
6243         private Either<Boolean, ResponseFormat> validateDerivedFromExtending(User user, Resource currentResource, Resource updateInfoResource, AuditingActionEnum actionEnum) {
6244                 // If updated resource is not deriving, should fail validation
6245                 /*
6246                  * if (currentResource.getDerivedFrom() == null || currentResource.getDerivedFrom().isEmpty()) { return Either.left(false); }
6247                  */
6248                 // If current resource is deriving from certain type and it is updated to not deriving, should fail validation
6249                 /*
6250                  * if (updateInfoResource.getDerivedFrom() == null || updateInfoResource.getDerivedFrom().isEmpty()) { return Either.left(false); }
6251                  */
6252                 String currentTemplateName = currentResource.getDerivedFrom().get(0);
6253                 String updatedTemplateName = updateInfoResource.getDerivedFrom().get(0);
6254
6255                 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateToscaResourceNameExtends(currentTemplateName, updatedTemplateName);
6256                 if (dataModelResponse.isRight()) {
6257                         StorageOperationStatus storageStatus = dataModelResponse.right().value();
6258                         BeEcompErrorManager.getInstance().logBeDaoSystemError("Create/Update Resource - validateDerivingFromExtendingType");
6259                         log.debug("request to data model failed with error: {}", storageStatus.name());
6260                         ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), currentResource);
6261                         log.trace("audit before sending response");
6262                         componentsUtils.auditResource(responseFormat, user, currentResource, "", "", actionEnum, null);
6263                         return Either.right(responseFormat);
6264                 }
6265
6266                 if (!dataModelResponse.left().value()) {
6267                         log.info("resource template with name {} does not inherit as original {}", updatedTemplateName, currentTemplateName);
6268                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND);
6269                         componentsUtils.auditResource(responseFormat, user, currentResource, "", "", actionEnum, null);
6270
6271                         return Either.right(responseFormat);
6272
6273                 }
6274                 return Either.left(true);
6275         }
6276
6277         public Either<Boolean, ResponseFormat> validateDerivedFromNotEmpty(User user, Resource resource, AuditingActionEnum actionEnum) {
6278                 log.debug("validate resource derivedFrom field");
6279                 if ((resource.getDerivedFrom() == null) || (resource.getDerivedFrom().isEmpty()) || (resource.getDerivedFrom().get(0)) == null || (resource.getDerivedFrom().get(0).trim().isEmpty())) {
6280                         log.info("derived from (template) field is missing for the resource");
6281                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
6282                         componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
6283
6284                         return Either.right(responseFormat);
6285                 }
6286                 return Either.left(true);
6287         }
6288
6289         private Either<Boolean, ResponseFormat> validateResourceNameExists(Resource resource) {
6290
6291                 Either<Boolean, StorageOperationStatus> resourceOperationResponse = toscaOperationFacade.validateComponentNameExists(resource.getName(), resource.getResourceType(), resource.getComponentType());
6292                 if (resourceOperationResponse.isLeft()) {
6293                         if (!resourceOperationResponse.left().value()) {
6294                                 return Either.left(false);
6295                         } else {
6296                                 log.debug("resource with name: {}, already exists", resource.getName());
6297                                 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
6298                                 return Either.right(errorResponse);
6299                         }
6300                 }
6301                 log.debug("error while validateResourceNameExists for resource: {}", resource.getName());
6302                 ResponseFormat errorResponse = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceOperationResponse.right().value()));
6303                 return Either.right(errorResponse);
6304         }
6305
6306         /*
6307          * private Either<Boolean, ResponseFormat> validateTagsListAndRemoveDuplicates(User user, Resource resource, AuditingActionEnum actionEnum) { List<String> tagsList = resource.getTags();
6308          * 
6309          * Either<Boolean, ResponseFormat> validateTags = validateResourceTags(tagsList, resource.getResourceName()); if (validateTags.isRight()) { ResponseFormat responseFormat = validateTags.right().value();
6310          * componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); return Either.right(responseFormat); } ValidationUtils.removeDuplicateFromList(tagsList); return Either.left(true);
6311          * 
6312          * }
6313          * 
6314          * private Either<Boolean, ResponseFormat> validateResourceTags(List<String> tags, String resourceName) { log.debug("validate resource tags"); boolean includesResourceName = false; int tagListSize = 0; if (tags != null && !tags.isEmpty()) { for
6315          * (String tag : tags) { if (!ValidationUtils.validateTagLength(tag)) { log.debug("tag length exceeds limit {}", ValidationUtils.TAG_MAX_LENGTH); return Either.right(componentsUtils.getResponseFormat(ActionStatus.
6316          * COMPONENT_SINGLE_TAG_EXCEED_LIMIT, "" + ValidationUtils.TAG_MAX_LENGTH)); } if (ValidationUtils.validateComponentNamePattern(tag)) { if (!includesResourceName) { includesResourceName = resourceName.equals(tag); } } else {
6317          * log.debug("invalid tag {}", tag); return Either.right(componentsUtils.getResponseFormat(ActionStatus. COMPONENT_INVALID_TAG)); } tagListSize += tag.length() + 1; } if (!includesResourceName) { log.debug( "tags must include resource name");
6318          * return Either.right(componentsUtils.getResponseFormat(ActionStatus. COMPONENT_INVALID_TAGS_NO_COMP_NAME)); } if (!ValidationUtils.validateTagListLength(tagListSize)) { log.debug( "overall tags length {}, exceeds limit {}", tagListSize,
6319          * ValidationUtils.TAG_LIST_MAX_LENGTH); return Either.right(componentsUtils.getResponseFormat(ActionStatus. COMPONENT_TAGS_EXCEED_LIMIT, "" + ValidationUtils.TAG_LIST_MAX_LENGTH)); } return Either.left(true); }
6320          * 
6321          * return Either.right(componentsUtils.getResponseFormat(ActionStatus. COMPONENT_MISSING_TAGS)); }
6322          */
6323
6324         private Either<Boolean, ResponseFormat> validateCategory(User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
6325
6326                 List<CategoryDefinition> categories = resource.getCategories();
6327                 if (categories == null || categories.size() == 0) {
6328                         log.debug("Resource category is empty");
6329                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
6330                         componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
6331                         return Either.right(responseFormat);
6332                 }
6333                 if (categories.size() > 1) {
6334                         log.debug("Must be only one category for resource");
6335                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_TOO_MUCH_CATEGORIES, ComponentTypeEnum.RESOURCE.getValue());
6336                         return Either.right(responseFormat);
6337                 }
6338                 CategoryDefinition category = categories.get(0);
6339                 List<SubCategoryDefinition> subcategories = category.getSubcategories();
6340                 if (subcategories == null || subcategories.size() == 0) {
6341                         log.debug("Missinig subcategory for resource");
6342                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY);
6343                         return Either.right(responseFormat);
6344                 }
6345                 if (subcategories.size() > 1) {
6346                         log.debug("Must be only one sub category for resource");
6347                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_TOO_MUCH_SUBCATEGORIES);
6348                         return Either.right(responseFormat);
6349                 }
6350
6351                 SubCategoryDefinition subcategory = subcategories.get(0);
6352
6353                 if (!ValidationUtils.validateStringNotEmpty(category.getName())) {
6354                         log.debug("Resource category is empty");
6355                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
6356                         componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
6357                         return Either.right(responseFormat);
6358                 }
6359                 if (!ValidationUtils.validateStringNotEmpty(subcategory.getName())) {
6360                         log.debug("Resource category is empty");
6361                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
6362                         componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
6363                         return Either.right(responseFormat);
6364                 }
6365
6366                 Either<Boolean, ResponseFormat> validateCategory = validateCategoryListed(category, subcategory, inTransaction);
6367                 if (validateCategory.isRight()) {
6368                         ResponseFormat responseFormat = validateCategory.right().value();
6369                         componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
6370                         return Either.right(responseFormat);
6371                 }
6372
6373                 return Either.left(true);
6374         }
6375
6376         private Either<Boolean, ResponseFormat> validateCategoryListed(CategoryDefinition category, SubCategoryDefinition subcategory, boolean inTransaction) {
6377                 if (category != null && subcategory != null) {
6378                         log.debug("validating resource category {} against valid categories list", category);
6379                         Either<List<CategoryDefinition>, ActionStatus> categories = elementDao.getAllCategories(NodeTypeEnum.ResourceNewCategory, inTransaction);
6380                         if (categories.isRight()) {
6381                                 log.debug("failed to retrive resource categories from Titan");
6382                                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(categories.right().value());
6383                                 return Either.right(responseFormat);
6384                         }
6385                         List<CategoryDefinition> categoryList = categories.left().value();
6386                         for (CategoryDefinition cat : categoryList) {
6387                                 if (cat.getName().equals(category.getName())) {
6388                                         for (SubCategoryDefinition subcat : cat.getSubcategories()) {
6389                                                 if (subcat.getName().equals(subcategory.getName())) {
6390                                                         return Either.left(true);
6391                                                 }
6392                                         }
6393                                         log.debug("SubCategory {} is not part of resource category group. Resource subcategory valid values are {}", subcategory, cat.getSubcategories());
6394                                         return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()));
6395                                 }
6396                         }
6397                         log.debug("Category {} is not part of resource category group. Resource category valid values are {}", category, categoryList);
6398                         return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()));
6399                 }
6400                 return Either.left(false);
6401         }
6402
6403         public Either<Boolean, ResponseFormat> validateVendorReleaseName(User user, Resource resource, AuditingActionEnum actionEnum) {
6404                 String vendorRelease = resource.getVendorRelease();
6405
6406                 log.debug("validate vendor relese name");
6407                 if (!ValidationUtils.validateStringNotEmpty(vendorRelease)) {
6408                         log.info("vendor relese name is missing.");
6409                         ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_RELEASE);
6410                         componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null);
6411                         return Either.right(errorResponse);
6412                 }
6413
6414                 Either<Boolean, ResponseFormat> validateVendorReleaseResponse = validateVendorReleaseName(vendorRelease);
6415                 if (validateVendorReleaseResponse.isRight()) {
6416                         ResponseFormat responseFormat = validateVendorReleaseResponse.right().value();
6417                         componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
6418                 }
6419                 return validateVendorReleaseResponse;
6420         }
6421
6422         public Either<Boolean, ResponseFormat> validateVendorReleaseName(String vendorRelease) {
6423                 if (vendorRelease != null) {
6424                         if (!ValidationUtils.validateVendorReleaseLength(vendorRelease)) {
6425                                 log.info("vendor release exceds limit.");
6426                                 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
6427                                 return Either.right(errorResponse);
6428                         }
6429
6430                         if (!ValidationUtils.validateVendorRelease(vendorRelease)) {
6431                                 log.info("vendor release  is not valid.");
6432                                 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_RELEASE);
6433                                 return Either.right(errorResponse);
6434                         }
6435                         return Either.left(true);
6436                 }
6437                 return Either.left(false);
6438
6439         }
6440
6441         private Either<Boolean, ResponseFormat> validateVendorName(User user, Resource resource, AuditingActionEnum actionEnum) {
6442                 String vendorName = resource.getVendorName();
6443                 if (!ValidationUtils.validateStringNotEmpty(vendorName)) {
6444                         log.info("vendor name is missing.");
6445                         ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_NAME);
6446                         componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null);
6447                         return Either.right(errorResponse);
6448                 }
6449
6450                 Either<Boolean, ResponseFormat> validateVendorNameResponse = validateVendorName(vendorName);
6451                 if (validateVendorNameResponse.isRight()) {
6452                         ResponseFormat responseFormat = validateVendorNameResponse.right().value();
6453                         componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
6454                 }
6455                 return validateVendorNameResponse;
6456
6457         }
6458
6459         private Either<Boolean, ResponseFormat> validateResourceVendorModelNumber(User user, Resource resource, AuditingActionEnum actionEnum) {
6460                 String resourceVendorModelNumber = resource.getResourceVendorModelNumber();
6461                 Either<Boolean, ResponseFormat> validateResourceVendorModelNumber = validateResourceVendorModelNumber(resourceVendorModelNumber);
6462                 if (validateResourceVendorModelNumber.isRight()) {
6463                         ResponseFormat responseFormat = validateResourceVendorModelNumber.right().value();
6464                         componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
6465                 }
6466                 return validateResourceVendorModelNumber;
6467
6468         }
6469
6470
6471         private Either<Boolean, ResponseFormat> validateVendorName(String vendorName) {
6472                 if (vendorName != null) {
6473                         if (!ValidationUtils.validateVendorNameLength(vendorName)) {
6474                                 log.info("vendor name exceds limit.");
6475                                 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
6476                                 return Either.right(errorResponse);
6477                         }
6478
6479                         if (!ValidationUtils.validateVendorName(vendorName)) {
6480                                 log.info("vendor name  is not valid.");
6481                                 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_NAME);
6482                                 return Either.right(errorResponse);
6483                         }
6484                         return Either.left(true);
6485
6486                 }
6487                 return Either.left(false);
6488
6489         }
6490
6491         private Either<Boolean, ResponseFormat> validateResourceVendorModelNumber(String resourceVendorModelNumber) {
6492                 if (resourceVendorModelNumber.equals("")) {
6493                         return Either.left(true);
6494                 } else {
6495                         if (!ValidationUtils.validateResourceVendorModelNumberLength(resourceVendorModelNumber)) {
6496                                 log.info("resource vendor model number exceeds limit.");
6497                                 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT, "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
6498                                 return Either.right(errorResponse);
6499                         }
6500                         // resource vendor model number is currently validated as vendor name
6501                         if (!ValidationUtils.validateVendorName(resourceVendorModelNumber)) {
6502                                 log.info("resource vendor model number  is not valid.");
6503                                 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
6504                                 return Either.right(errorResponse);
6505                         }
6506                         return Either.left(true);
6507                 }
6508         }
6509
6510         
6511         /*
6512          * private Either<Boolean, ResponseFormat> validateDescriptionAndCleanup(User user, Resource resource, AuditingActionEnum actionEnum) { String description = resource.getDescription(); if (!ValidationUtils.validateStringNotEmpty(description)) {
6513          * log.debug("Resource description is empty"); ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus. COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue()); componentsUtils.auditResource(errorResponse,
6514          * user, resource, "", "", actionEnum, null); return Either.right(errorResponse); }
6515          * 
6516          * description = ValidationUtils.removeNoneUtf8Chars(description); description = ValidationUtils.removeHtmlTags(description); description = ValidationUtils.normaliseWhitespace(description); description = ValidationUtils.stripOctets(description);
6517          * 
6518          * Either<Boolean, ResponseFormat> validatDescription = validateResourceDescription(description); if (validatDescription.isRight()) { ResponseFormat responseFormat = validatDescription.right().value();
6519          * componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); return Either.right(responseFormat); } resource.setDescription(description); return Either.left(true); }
6520          * 
6521          * private Either<Boolean, ResponseFormat> validateResourceDescription(String description) { if (description != null) { if (!ValidationUtils.validateDescriptionLength(description)) { return
6522          * Either.right(componentsUtils.getResponseFormat(ActionStatus. COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH)); }
6523          * 
6524          * if (!ValidationUtils.validateIsEnglish(description)) { return Either.right(componentsUtils.getResponseFormat(ActionStatus. COMPONENT_INVALID_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue())); } return Either.left(true); } return
6525          * Either.left(false); }
6526          */
6527
6528         /*
6529          * private Either<Boolean, ResponseFormat> validateContactId(User user, Resource resource, AuditingActionEnum actionEnum) { String contactId = resource.getContactId();
6530          * 
6531          * if (!ValidationUtils.validateStringNotEmpty(contactId)) { log.info("contact info is missing."); ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus. COMPONENT_MISSING_CONTACT, ComponentTypeEnum.RESOURCE.getValue());
6532          * componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null); return Either.right(errorResponse); }
6533          * 
6534          * Either<Boolean, ResponseFormat> validateContactIdResponse = validateContactId(contactId); if (validateContactIdResponse.isRight()) { ResponseFormat responseFormat = validateContactIdResponse.right().value();
6535          * componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); } return validateContactIdResponse; }
6536          * 
6537          * private Either<Boolean, ResponseFormat> validateContactId(String contactId) { if (contactId != null) { if (!ValidationUtils.validateContactId(contactId)) { log.debug("contact {} is invalid.", contactId); ResponseFormat errorResponse =
6538          * componentsUtils.getResponseFormat(ActionStatus. COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); return Either.right(errorResponse); } return Either.left(true); } return Either.left(false);
6539          * 
6540          * }
6541          */
6542
6543         /*
6544          * private Either<Boolean, ResponseFormat> validateIcon(User user, Resource resource, AuditingActionEnum actionEnum) { String icon = resource.getIcon();
6545          * 
6546          * if (!ValidationUtils.validateStringNotEmpty(icon)) { log.debug("icon is missing."); ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.RESOURCE.getValue());
6547          * componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null); return Either.right(errorResponse); }
6548          * 
6549          * Either<Boolean, ResponseFormat> validateIcon = validateIcon(icon); if (validateIcon.isRight()) { ResponseFormat responseFormat = validateIcon.right().value(); componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum,
6550          * null); } return validateIcon;
6551          * 
6552          * }
6553          * 
6554          * public Either<Boolean, ResponseFormat> validateIcon(String icon) { if (icon != null) { if (!ValidationUtils.validateIconLength(icon)) { log.debug("icon exceeds max length"); return Either.right(componentsUtils.getResponseFormat(ActionStatus.
6555          * COMPONENT_ICON_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.ICON_MAX_LENGTH)); } if (!ValidationUtils.validateIcon(icon)) { log.debug("icon is invalid." ); ResponseFormat errorResponse =
6556          * componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.RESOURCE.getValue()); return Either.right(errorResponse); } return Either.left(true); } return Either.left(false);
6557          * 
6558          * }
6559          */
6560
6561         private Either<Boolean, ResponseFormat> validateCost(User user, Resource resource, AuditingActionEnum actionEnum) {
6562                 String cost = resource.getCost();
6563                 if (cost != null) {
6564
6565                         if (!ValidationUtils.validateCost(cost)) {
6566                                 log.debug("resource cost is invalid.");
6567                                 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
6568                                 return Either.right(errorResponse);
6569                         }
6570                 }
6571                 return Either.left(true);
6572         }
6573
6574         private Either<Boolean, ResponseFormat> validateLicenseType(User user, Resource resource, AuditingActionEnum actionEnum) {
6575                 log.debug("validate licenseType");
6576                 String licenseType = resource.getLicenseType();
6577                 if (licenseType != null) {
6578                         List<String> licenseTypes = ConfigurationManager.getConfigurationManager().getConfiguration().getLicenseTypes();
6579                         if (!licenseTypes.contains(licenseType)) {
6580                                 log.debug("License type {} isn't configured");
6581                                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
6582                                 if (actionEnum != null) {
6583                                         // In update case, no audit is required
6584                                         componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
6585                                 }
6586                                 return Either.right(responseFormat);
6587                         }
6588                 }
6589                 return Either.left(true);
6590         }
6591
6592         private Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom(Resource currentResource, Resource updatedResource, String userId, boolean shouldLock, boolean inTransaction) {
6593                 Either<Operation, ResponseFormat> deleteArtifactByInterface = null;
6594                 if (updatedResource.getDerivedFrom() != null) {
6595                         log.debug("Starting derived from update for resource {}", updatedResource.getUniqueId());
6596                         log.debug("1. Removing interface artifacts from graph");
6597                         // Remove all interface artifacts of resource
6598                         String resourceId = updatedResource.getUniqueId();
6599                         Map<String, InterfaceDefinition> interfaces = currentResource.getInterfaces();
6600
6601                         if (interfaces != null) {
6602                                 Collection<InterfaceDefinition> values = interfaces.values();
6603                                 for (InterfaceDefinition interfaceDefinition : values) {
6604                                         String interfaceType = interfaceTypeOperation.getShortInterfaceName(interfaceDefinition);
6605
6606                                         log.trace("Starting interface artifacts removal for interface type {}", interfaceType);
6607                                         Map<String, Operation> operations = interfaceDefinition.getOperationsMap();
6608                                         if (operations != null) {
6609                                                 for (Entry<String, Operation> operationEntry : operations.entrySet()) {
6610                                                         Operation operation = operationEntry.getValue();
6611                                                         ArtifactDefinition implementation = operation.getImplementationArtifact();
6612                                                         if (implementation != null) {
6613                                                                 String uniqueId = implementation.getUniqueId();
6614                                                                 log.debug("Removing interface artifact definition {}, operation {}, interfaceType {}", uniqueId, operationEntry.getKey(), interfaceType);
6615                                                                 // only thing that transacts and locks here
6616                                                                 deleteArtifactByInterface = artifactsBusinessLogic.deleteArtifactByInterface(resourceId, interfaceType, operationEntry.getKey(), userId, uniqueId, null, shouldLock, true);
6617                                                                 if (deleteArtifactByInterface.isRight()) {
6618                                                                         log.debug("Couldn't remove artifact definition with id {}", uniqueId);
6619                                                                         if (!inTransaction) {
6620                                                                                 titanDao.rollback();
6621                                                                         }
6622                                                                         return Either.right(deleteArtifactByInterface.right().value());
6623                                                                 }
6624                                                         } else {
6625                                                                 log.trace("No implementation found for operation {} - nothing to delete", operationEntry.getKey());
6626                                                         }
6627                                                 }
6628                                         } else {
6629                                                 log.trace("No operations found for interface type {}", interfaceType);
6630                                         }
6631                                 }
6632                         }
6633                         log.debug("2. Removing properties");
6634                         Either<Map<String, PropertyDefinition>, StorageOperationStatus> findPropertiesOfNode = propertyOperation.deleteAllPropertiesAssociatedToNode(NodeTypeEnum.Resource, resourceId);
6635
6636                         if (findPropertiesOfNode.isRight() && !findPropertiesOfNode.right().value().equals(StorageOperationStatus.OK)) {
6637                                 log.debug("Failed to remove all properties of resource");
6638                                 if (!inTransaction)
6639                                         titanDao.rollback();
6640                                 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(findPropertiesOfNode.right().value())));
6641                         }
6642
6643                 } else {
6644                         log.debug("Derived from wasn't changed during update");
6645                 }
6646
6647                 if (!inTransaction)
6648                         titanDao.commit();
6649                 return Either.left(true);
6650
6651         }
6652
6653         /**** Auditing *******************/
6654
6655         protected static IElementOperation getElementDao(Class<IElementOperation> class1, ServletContext context) {
6656                 WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
6657
6658                 WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
6659
6660                 return webApplicationContext.getBean(class1);
6661         }
6662
6663         public ICapabilityTypeOperation getCapabilityTypeOperation() {
6664                 return capabilityTypeOperation;
6665         }
6666
6667         public void setCapabilityTypeOperation(ICapabilityTypeOperation capabilityTypeOperation) {
6668                 this.capabilityTypeOperation = capabilityTypeOperation;
6669         }
6670
6671         public Either<Boolean, ResponseFormat> validatePropertiesDefaultValues(Resource resource) {
6672                 log.debug("validate resource properties default values");
6673                 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
6674                 List<PropertyDefinition> properties = resource.getProperties();
6675                 String type = null;
6676                 String innerType = null;
6677                 if (properties != null) {
6678                         for (PropertyDefinition property : properties) {
6679                                 if (!propertyOperation.isPropertyTypeValid(property)) {
6680                                         log.info("Invalid type for property");
6681                                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_TYPE, property.getType(), property.getName());
6682                                         eitherResult = Either.right(responseFormat);
6683                                         break;
6684                                 }
6685
6686                                 Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache);
6687                                 if (allDataTypes.isRight()) {
6688                                         return Either.right(allDataTypes.right().value());
6689                                 }
6690
6691                                 type = property.getType();
6692                                 if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
6693                                         ImmutablePair<String, Boolean> propertyInnerTypeValid = propertyOperation.isPropertyInnerTypeValid(property, allDataTypes.left().value());
6694                                         innerType = propertyInnerTypeValid.getLeft();
6695                                         if (!propertyInnerTypeValid.getRight().booleanValue()) {
6696                                                 log.info("Invalid inner type for property");
6697                                                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType, property.getName());
6698                                                 eitherResult = Either.right(responseFormat);
6699                                                 break;
6700                                         }
6701                                 }
6702
6703                                 if (!propertyOperation.isPropertyDefaultValueValid(property, allDataTypes.left().value())) {
6704                                         log.info("Invalid default value for property");
6705                                         ResponseFormat responseFormat;
6706                                         if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
6707                                                 responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE, property.getName(), type, innerType, property.getDefaultValue());
6708                                         } else {
6709                                                 responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEFAULT_VALUE, property.getName(), type, property.getDefaultValue());
6710                                         }
6711                                         eitherResult = Either.right(responseFormat);
6712                                         break;
6713
6714                                 }
6715                         }
6716                 }
6717                 return eitherResult;
6718         }
6719
6720         @Override
6721         public Either<List<String>, ResponseFormat> deleteMarkedComponents() {
6722                 return deleteMarkedComponents(ComponentTypeEnum.RESOURCE);
6723         }
6724
6725         @Override
6726         public ComponentInstanceBusinessLogic getComponentInstanceBL() {
6727                 return vfComponentInstanceBusinessLogic;
6728         }
6729
6730         private String getComponentTypeForResponse(Component component) {
6731                 String componentTypeForResponse = "SERVICE";
6732                 if (component instanceof Resource) {
6733                         componentTypeForResponse = ((Resource) component).getResourceType().name();
6734                 }
6735                 return componentTypeForResponse;
6736         }
6737
6738         private Either<Map<String, GroupDefinition>, ResponseFormat> createGroupsFromYaml(String yamlFileName, Map<String, Object> toscaJson, Resource resource) {
6739
6740                 Map<String, GroupDefinition> groups = new HashMap<String, GroupDefinition>();
6741                 Either<Map<String, GroupDefinition>, ResponseFormat> result = Either.left(groups);
6742
6743                 Either<Map<String, Object>, ResultStatusEnum> eitherNodesTemlates = ImportUtils.findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.GROUPS);
6744                 if (eitherNodesTemlates.isLeft()) {
6745                         Map<String, Object> jsonNodeTemplates = eitherNodesTemlates.left().value();
6746
6747                         if (jsonNodeTemplates != null && false == jsonNodeTemplates.isEmpty()) {
6748                                 Iterator<Entry<String, Object>> nodesNameValue = jsonNodeTemplates.entrySet().iterator();
6749                                 while (nodesNameValue.hasNext()) {
6750                                         Entry<String, Object> groupNameValue = nodesNameValue.next();
6751
6752                                         String groupName = groupNameValue.getKey();
6753                                         Either<GroupDefinition, ResponseFormat> eitherNode = createGroupInfo(groupName, groupNameValue.getValue());
6754                                         if (eitherNode.isRight()) {
6755                                                 String message = "Failed when creating group: " + groupNameValue.getKey() + " for resource:" + resource.getName();
6756                                                 BeEcompErrorManager.getInstance().logInternalFlowError("ImportResource", message, ErrorSeverity.INFO);
6757                                                 return Either.right(eitherNode.right().value());
6758                                         } else {
6759                                                 GroupDefinition groupDefinition = eitherNode.left().value();
6760                                                 groups.put(groupName, groupDefinition);
6761                                         }
6762                                 }
6763                         }
6764                 }
6765
6766                 return result;
6767         }
6768
6769         private Either<Map<String, InputDefinition>, ResponseFormat> createInputsFromYaml(String yamlFileName, Map<String, Object> toscaJson, Resource resource) {
6770
6771                 Either<Map<String, InputDefinition>, ResultStatusEnum> inputs = ImportUtils.getInputs(toscaJson);
6772                 if (inputs.isRight()) {
6773                         String message = "Failed when creating inputs:  for resource:" + resource.getName();
6774                         BeEcompErrorManager.getInstance().logInternalFlowError("ImportResource", message, ErrorSeverity.INFO);
6775                         Map<String, InputDefinition> resultMap = new HashMap<>();
6776                         return Either.left(resultMap);
6777
6778                 }
6779
6780                 Either<Map<String, InputDefinition>, ResponseFormat> result = Either.left(inputs.left().value());
6781
6782                 return result;
6783         }
6784
6785         private Either<GroupDefinition, ResponseFormat> createGroupInfo(String groupName, Object groupTemplateJson) {
6786
6787                 GroupDefinition groupInfo = new GroupDefinition();
6788                 groupInfo.setName(groupName);
6789                 Either<GroupDefinition, ResponseFormat> result = Either.left(groupInfo);
6790
6791                 try {
6792                         if (groupTemplateJson != null && groupTemplateJson instanceof Map) {
6793                                 Map<String, Object> groupTemplateJsonMap = (Map<String, Object>) groupTemplateJson;
6794                                 // Type
6795                                 String groupType = null;
6796                                 if (groupTemplateJsonMap.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) {
6797                                         groupType = (String) groupTemplateJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName());
6798                                         groupInfo.setType(groupType);
6799                                 } else {
6800                                         log.debug("The 'type' member is not found under group {}", groupName);
6801                                         result = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
6802                                 }
6803
6804                                 if (groupTemplateJsonMap.containsKey(ToscaTagNamesEnum.DESCRIPTION.getElementName())) {
6805                                         groupInfo.setDescription((String) groupTemplateJsonMap.get(ToscaTagNamesEnum.DESCRIPTION.getElementName()));
6806                                 }
6807
6808                                 if (groupTemplateJsonMap.containsKey(ToscaTagNamesEnum.MEMBERS.getElementName())) {
6809                                         Object members = groupTemplateJsonMap.get(ToscaTagNamesEnum.MEMBERS.getElementName());
6810                                         if (members != null) {
6811                                                 if (members instanceof List) {
6812                                                         Map<String, String> membersLoaded = new HashMap<>();
6813                                                         List<?> membersAsList = (List<?>) members;
6814                                                         for (Object member : membersAsList) {
6815                                                                 membersLoaded.put(member.toString(), "");
6816                                                         }
6817                                                         groupInfo.setMembers(membersLoaded);
6818                                                 } else {
6819                                                         log.debug("The 'type' member is not found under group {}", groupName);
6820                                                         result = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
6821                                                 }
6822                                         }
6823                                 }
6824
6825                                 if (groupTemplateJsonMap.containsKey(ToscaTagNamesEnum.PROPERTIES.getElementName())) {
6826                                         Object properties = groupTemplateJsonMap.get(ToscaTagNamesEnum.PROPERTIES.getElementName());
6827
6828                                         Either<List<GroupProperty>, ResponseFormat> regResponse = createPropertiesValueModuleFromYaml(properties, groupName, groupType);
6829                                         if (regResponse.isRight())
6830                                                 return Either.right(regResponse.right().value());
6831                                         if (regResponse.left().value().size() > 0) {
6832                                                 groupInfo.convertFromGroupProperties(regResponse.left().value());
6833                                         }
6834                                 }
6835
6836                         } else {
6837                                 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
6838                         }
6839                 } catch (Exception e) {
6840                         BeEcompErrorManager.getInstance().logBeSystemError("Import Resource - create group");
6841                         log.debug("error when creating group, message:{}", e.getMessage(), e);
6842                         result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML));
6843                 }
6844
6845                 return result;
6846         }
6847
6848         private Either<List<GroupProperty>, ResponseFormat> createPropertiesValueModuleFromYaml(Object properties, String groupName, String groupType) {
6849
6850                 List<GroupProperty> result = new ArrayList<>();
6851
6852                 if (properties == null) {
6853                         return Either.left(result);
6854                 }
6855
6856                 Either<GroupTypeDefinition, StorageOperationStatus> groupTypeRes = groupTypeOperation.getLatestGroupTypeByType(groupType, true);
6857
6858                 if (groupTypeRes.isRight()) {
6859                         return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_MISSING_GROUP_TYPE, groupType));
6860                 }
6861
6862                 Map<String, PropertyDefinition> gtProperties = new HashMap<>();
6863                 GroupTypeDefinition groupTypeDefinition = groupTypeRes.left().value();
6864
6865                 List<PropertyDefinition> propertiesDef = groupTypeDefinition.getProperties();
6866
6867                 if (propertiesDef != null) {
6868                         gtProperties = propertiesDef.stream().collect(Collectors.toMap(p -> p.getName(), p -> p));
6869                 }
6870
6871                 if (properties != null) {
6872
6873                         if (properties instanceof Map) {
6874
6875                                 Map<String, Object> props = (Map<String, Object>) properties;
6876                                 for (Entry<String, Object> entry : props.entrySet()) {
6877
6878                                         String propName = entry.getKey();
6879                                         Object value = entry.getValue();
6880
6881                                         PropertyDefinition gtDefinition = gtProperties.get(propName);
6882                                         if (gtDefinition == null) {
6883                                                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_PROPERTY_NOT_FOUND, propName, groupName, groupType));
6884                                         }
6885
6886                                         ToscaPropertyType type = ToscaPropertyType.isValidType(gtDefinition.getType());
6887
6888                                         String convertedValue = null;
6889                                         if (value != null) {
6890                                                 if (type == null || value instanceof Map || value instanceof List) {
6891                                                         convertedValue = gson.toJson(value);
6892                                                 } else {
6893                                                         convertedValue = value.toString();
6894                                                 }
6895                                         }
6896
6897                                         GroupProperty groupProperty = new GroupProperty();
6898                                         groupProperty.setValue(convertedValue);
6899                                         groupProperty.setName(propName);
6900
6901                                         log.trace("After building group property {}", groupProperty);
6902
6903                                         result.add(groupProperty);
6904                                 }
6905
6906                         }
6907
6908                 }
6909
6910                 return Either.left(result);
6911         }
6912
6913         public Either<Resource, ResponseFormat> getLatestResourceFromCsarUuid(String csarUuid, User user) {
6914
6915                 // validate user
6916                 if (user != null) {
6917                         Either<User, ResponseFormat> userValidation = validateUserExists(user, "Get resource from csar UUID", false);
6918                         if (userValidation.isRight()) {
6919                                 return Either.right(userValidation.right().value());
6920                         }
6921                 }
6922
6923                 // get resource from csar uuid
6924                 Either<Resource, StorageOperationStatus> either = toscaOperationFacade.getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUuid, "");
6925                 if (either.isRight()) {
6926                         ResponseFormat resp = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_FROM_CSAR_NOT_FOUND, csarUuid);
6927                         return Either.right(resp);
6928                 }
6929
6930                 return Either.left(either.left().value());
6931         }
6932
6933         @Override
6934         public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, ComponentTypeEnum componentTypeEnum, String userId, String searchText) {
6935                 return null;
6936         }
6937
6938         private Either<Map<String, List<CapabilityDefinition>>, ResponseFormat> getValidComponentInstanceCapabilities(Map<String, List<CapabilityDefinition>> defaultCapabilities, Map<String, List<UploadCapInfo>> uploadedCapabilities) {
6939                 ResponseFormat responseFormat;
6940                 Map<String, List<CapabilityDefinition>> validCapabilitiesMap = new HashMap<>();
6941
6942                 for (Entry<String, List<UploadCapInfo>> uploadedCapabilitiesEntry : uploadedCapabilities.entrySet()) {
6943                         String capabilityType = uploadedCapabilitiesEntry.getValue().get(0).getType();
6944                         if (!defaultCapabilities.containsKey(capabilityType)) {
6945                                 responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, capabilityType);
6946                                 return Either.right(responseFormat);
6947                         } else {
6948                                 CapabilityDefinition delaultCapability = defaultCapabilities.get(capabilityType).get(0);
6949                                 Either<Boolean, String> validationRes = validateUniquenessUpdateUploadedComponentInstanceCapability(delaultCapability, uploadedCapabilitiesEntry.getValue().get(0));
6950                                 if (validationRes.isRight()) {
6951                                         responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NAME_ALREADY_EXISTS, validationRes.right().value());
6952                                         return Either.right(responseFormat);
6953                                 }
6954                                 List<CapabilityDefinition> validCapabilityList = new ArrayList<>();
6955                                 validCapabilityList.add(delaultCapability);
6956                                 validCapabilitiesMap.put(uploadedCapabilitiesEntry.getKey(), validCapabilityList);
6957                         }
6958                 }
6959                 return Either.left(validCapabilitiesMap);
6960         }
6961
6962         private Either<Boolean, String> validateUniquenessUpdateUploadedComponentInstanceCapability(CapabilityDefinition defaultCapability, UploadCapInfo uploadedCapability) {
6963                 List<ComponentInstanceProperty> validProperties = new ArrayList<>();
6964                 Map<String, PropertyDefinition> defaultProperties = defaultCapability.getProperties().stream().collect(Collectors.toMap(PropertyDefinition::getName, Function.identity()));
6965                 List<UploadPropInfo> uploadedProperties = uploadedCapability.getProperties();
6966                 for (UploadPropInfo property : uploadedProperties) {
6967                         String propertyName = property.getName().toLowerCase();
6968                         String propertyType = property.getType();
6969                         ComponentInstanceProperty validProperty;
6970                         if (defaultProperties.containsKey(propertyName)) {
6971                                 if (propertyType != null && !defaultProperties.get(propertyName).getType().equals(propertyType)) {
6972                                         return Either.right(propertyName);
6973                                 }
6974                         }
6975                         validProperty = new ComponentInstanceProperty();
6976                         validProperty.setName(propertyName);
6977                         if (property.getValue() != null)
6978                                 validProperty.setValue(property.getValue().toString());
6979                         validProperty.setDescription(property.getDescription());
6980                         validProperty.setPassword(property.isPassword());
6981                         validProperties.add(validProperty);
6982                 }
6983                 defaultCapability.setProperties(validProperties);
6984                 return Either.left(true);
6985         }
6986
6987         private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> organizeVfCsarArtifactsByArtifactOperation(List<NonMetaArtifactInfo> artifactPathAndNameList, List<ArtifactDefinition> existingArtifactsToHandle,
6988                         Resource resource, User user) {
6989
6990                 EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
6991                 Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
6992                 Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> nodeTypeArtifactsToHandleRes = Either.left(nodeTypeArtifactsToHandle);
6993                 ;
6994                 try {
6995                         // add all found Csar artifacts to list to upload
6996                         List<NonMetaArtifactInfo> artifactsToUpload = new ArrayList<>(artifactPathAndNameList);
6997                         List<NonMetaArtifactInfo> artifactsToUpdate = new ArrayList<>();
6998                         List<NonMetaArtifactInfo> artifactsToDelete = new ArrayList<>();
6999                         for (NonMetaArtifactInfo currNewArtifact : artifactPathAndNameList) {
7000                                 ArtifactDefinition foundArtifact;
7001
7002                                 if (!existingArtifactsToHandle.isEmpty()) {
7003                                         foundArtifact = existingArtifactsToHandle.stream().filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst().orElse(null);
7004                                         if (foundArtifact != null) {
7005                                                 if (ArtifactTypeEnum.findType(foundArtifact.getArtifactType()) == currNewArtifact.getArtifactType()) {
7006                                                         if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) {
7007                                                                 currNewArtifact.setArtifactUniqueId(foundArtifact.getUniqueId());
7008                                                                 // if current artifact already exists, but has different content, add him to the list to update
7009                                                                 artifactsToUpdate.add(currNewArtifact);
7010                                                         }
7011                                                         // remove found artifact from the list of existing artifacts to handle, because it was already handled
7012                                                         existingArtifactsToHandle.remove(foundArtifact);
7013                                                         // and remove found artifact from the list to upload, because it should either be updated or be ignored
7014                                                         artifactsToUpload.remove(currNewArtifact);
7015                                                 } else {
7016                                                         log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName());
7017                                                         ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, currNewArtifact.getArtifactName(),
7018                                                                         currNewArtifact.getArtifactType().name(), foundArtifact.getArtifactType());
7019                                                         AuditingActionEnum auditingAction = artifactsBusinessLogic.detectAuditingType(artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create), foundArtifact.getArtifactChecksum());
7020                                                         artifactsBusinessLogic.handleAuditing(auditingAction, resource, resource.getUniqueId(), user, null, null, foundArtifact.getUniqueId(), responseFormat, resource.getComponentType(), null);
7021                                                         responseWrapper.setInnerElement(responseFormat);
7022                                                         break;
7023                                                 }
7024                                         }
7025                                 }
7026                         }
7027                         if (responseWrapper.isEmpty()) {
7028                                 existingArtifactsToHandle.stream()
7029                                                 // add all artifacts which was not detected as artifact to update or to ignore to the list to delete
7030                                                 .forEach(a -> artifactsToDelete.add(new NonMetaArtifactInfo(a.getArtifactName(), null, ArtifactTypeEnum.findType(a.getArtifactType()), a.getArtifactGroupType(), null, a.getUniqueId())));
7031                         }
7032                         if (responseWrapper.isEmpty()) {
7033                                 if (!artifactsToUpload.isEmpty())
7034                                         nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Create, artifactsToUpload);
7035                                 if (!artifactsToUpdate.isEmpty())
7036                                         nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Update, artifactsToUpdate);
7037                                 if (!artifactsToDelete.isEmpty())
7038                                         nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Delete, artifactsToDelete);
7039                         }
7040                         if (!responseWrapper.isEmpty()) {
7041                                 nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement());
7042                         }
7043                 } catch (Exception e) {
7044                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
7045                         responseWrapper.setInnerElement(responseFormat);
7046                         log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
7047                 }
7048                 return nodeTypeArtifactsToHandleRes;
7049         }
7050
7051         private String buildNestedVfcToscaNamespace(String nodeTypeFullName) {
7052
7053                 String actualName = this.getNodeTypeActualName(nodeTypeFullName);
7054                 return ImportUtils.Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + ResourceTypeEnum.VFC.name().toLowerCase() + actualName;
7055
7056         }
7057
7058         private String buildNestedVfcToscaResourceName(String vfResourceName, String nodeTypeFullName) {
7059                 String toscaResourceName;
7060                 String nameWithouNamespacePrefix = getNodeTypeActualName(nodeTypeFullName);
7061                 if (nameWithouNamespacePrefix.startsWith(Constants.ABSTRACT)) {
7062                         toscaResourceName = Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + ResourceTypeEnum.VFC.name().toLowerCase() + '.' + vfResourceName + '.' + nameWithouNamespacePrefix;
7063                 } else {
7064                         toscaResourceName = Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + ResourceTypeEnum.VFC.name().toLowerCase() + '.' + vfResourceName + '.' + Constants.ABSTRACT + nameWithouNamespacePrefix;
7065                 }
7066                 return toscaResourceName;
7067         }
7068         
7069         private String buildNodeToscaResourceName(String vfResourceName, String nodeTypeFullName) {
7070                 String toscaResourceName;
7071                 String nameWithouNamespacePrefix = nodeTypeFullName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
7072                 String[] findTypes = nameWithouNamespacePrefix.split("\\.");
7073                 String resourceType = findTypes[0];
7074                 String actualName =  nameWithouNamespacePrefix.substring(resourceType.length());        
7075                 
7076                 if (actualName.startsWith(Constants.ABSTRACT)) {
7077                         toscaResourceName = Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + ResourceTypeEnum.VFC.name().toLowerCase() + '.' + vfResourceName + '.' + actualName;
7078                 } else {
7079                         toscaResourceName = Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + resourceType.toLowerCase() + '.' + vfResourceName + '.' + Constants.ABSTRACT + actualName;
7080                 }
7081                 return toscaResourceName;
7082         }
7083
7084         public ICacheMangerOperation getCacheManagerOperation() {
7085                 return cacheManagerOperation;
7086         }
7087
7088         public void setCacheManagerOperation(ICacheMangerOperation cacheManagerOperation) {
7089                 this.cacheManagerOperation = cacheManagerOperation;
7090         }
7091
7092         ///////////////////////////////////////// DataModel refactoring/////////////////////////////////////////////
7093
7094         public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String resourceId, List<String> dataParamsToReturn) {
7095
7096                 ComponentParametersView paramsToRetuen = new ComponentParametersView(dataParamsToReturn);
7097                 Either<Resource, StorageOperationStatus> resourceResultEither = toscaOperationFacade.getToscaElement(resourceId, paramsToRetuen);
7098
7099                 if (resourceResultEither.isRight()) {
7100                         if (resourceResultEither.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
7101                                 log.debug("Failed to found resource with id {} ", resourceId);
7102                                 Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
7103                         }
7104
7105                         log.debug("failed to get resource by id {} with filters {}", resourceId, dataParamsToReturn.toString());
7106                         return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(resourceResultEither.right().value()), ""));
7107                 }
7108
7109                 Resource resource = resourceResultEither.left().value();
7110                 UiComponentDataTransfer dataTransfer = UiComponentDataConverter.getUiDataTransferFromResourceByParams(resource, dataParamsToReturn);
7111                 return Either.left(dataTransfer);
7112         }
7113
7114 }