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