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