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