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