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