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