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