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