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