Catalog-model dead code removal
[sdc.git] / catalog-model / src / main / java / org / openecomp / sdc / be / model / jsontitan / operations / ToscaOperationFacade.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.model.jsontitan.operations;
22
23 import java.util.ArrayList;
24 import java.util.Arrays;
25 import java.util.Collections;
26 import java.util.EnumMap;
27 import java.util.HashMap;
28 import java.util.HashSet;
29 import java.util.LinkedList;
30 import java.util.List;
31 import java.util.Map;
32 import java.util.Map.Entry;
33 import java.util.Optional;
34 import java.util.Set;
35 import java.util.function.BiPredicate;
36 import java.util.stream.Collectors;
37
38 import org.apache.commons.collections.CollectionUtils;
39 import org.apache.commons.collections.MapUtils;
40 import org.apache.commons.lang3.StringUtils;
41 import org.apache.commons.lang3.tuple.ImmutablePair;
42 import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
43 import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
44 import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
45 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
46 import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
47 import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
48 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
49 import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
50 import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition;
51 import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
52 import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition;
53 import org.openecomp.sdc.be.datatypes.elements.ListRequirementDataDefinition;
54 import org.openecomp.sdc.be.datatypes.elements.MapArtifactDataDefinition;
55 import org.openecomp.sdc.be.datatypes.elements.MapCapabiltyProperty;
56 import org.openecomp.sdc.be.datatypes.elements.MapListCapabiltyDataDefinition;
57 import org.openecomp.sdc.be.datatypes.elements.MapListRequirementDataDefinition;
58 import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition;
59 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
60 import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
61 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
62 import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
63 import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
64 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
65 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
66 import org.openecomp.sdc.be.model.ArtifactDefinition;
67 import org.openecomp.sdc.be.model.CapabilityDefinition;
68 import org.openecomp.sdc.be.model.Component;
69 import org.openecomp.sdc.be.model.ComponentInstance;
70 import org.openecomp.sdc.be.model.ComponentInstanceInput;
71 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
72 import org.openecomp.sdc.be.model.ComponentParametersView;
73 import org.openecomp.sdc.be.model.DistributionStatusEnum;
74 import org.openecomp.sdc.be.model.GroupDefinition;
75 import org.openecomp.sdc.be.model.GroupInstance;
76 import org.openecomp.sdc.be.model.InputDefinition;
77 import org.openecomp.sdc.be.model.LifecycleStateEnum;
78 import org.openecomp.sdc.be.model.PolicyDefinition;
79 import org.openecomp.sdc.be.model.PropertyDefinition;
80 import org.openecomp.sdc.be.model.RelationshipInfo;
81 import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
82 import org.openecomp.sdc.be.model.RequirementDefinition;
83 import org.openecomp.sdc.be.model.Resource;
84 import org.openecomp.sdc.be.model.Service;
85 import org.openecomp.sdc.be.model.User;
86 import org.openecomp.sdc.be.model.catalog.CatalogComponent;
87 import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate;
88 import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement;
89 import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
90 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
91 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
92 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
93 import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
94 import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
95 import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
96 import org.openecomp.sdc.common.util.ValidationUtils;
97 import org.slf4j.Logger;
98 import org.slf4j.LoggerFactory;
99 import org.springframework.beans.factory.annotation.Autowired;
100
101 import fj.data.Either;
102
103 @org.springframework.stereotype.Component("tosca-operation-facade")
104 public class ToscaOperationFacade {
105
106         // region - Fields
107
108         @Autowired
109         private NodeTypeOperation nodeTypeOperation;
110         @Autowired
111         private TopologyTemplateOperation topologyTemplateOperation;
112         @Autowired
113         private NodeTemplateOperation nodeTemplateOperation;
114         @Autowired
115         private GroupsOperation groupsOperation;
116         @Autowired
117         private TitanDao titanDao;
118         private static Logger log = LoggerFactory.getLogger(ToscaOperationFacade.class.getName());
119         // endregion
120
121         // region - ToscaElement - GetById
122         public static final String PROXY_SUFFIX = "_proxy";
123
124         public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId) {
125
126                 return getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
127
128         }
129
130         public <T extends Component> Either<T, StorageOperationStatus> getToscaFullElement(String componentId) {
131                 ComponentParametersView filters = new ComponentParametersView();
132                 filters.setIgnoreCapabiltyProperties(false);
133                 filters.setIgnoreForwardingPath(false);
134                 return getToscaElement(componentId, filters);
135         }
136
137         public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId, ComponentParametersView filters) {
138
139                 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, filters.detectParseFlag());
140                 if (getVertexEither.isRight()) {
141                         log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
142                         return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
143
144                 }
145                 return getToscaElementByOperation(getVertexEither.left().value(), filters);
146         }
147
148         public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId, JsonParseFlagEnum parseFlag) {
149
150                 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, parseFlag);
151                 if (getVertexEither.isRight()) {
152                         log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
153                         return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
154
155                 }
156                 return getToscaElementByOperation(getVertexEither.left().value());
157         }
158
159         public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(GraphVertex componentVertex) {
160                 return getToscaElementByOperation(componentVertex);
161         }
162
163         public Either<Boolean, StorageOperationStatus> validateComponentExists(String componentId) {
164
165                 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
166                 if (getVertexEither.isRight()) {
167                         TitanOperationStatus status = getVertexEither.right().value();
168                         if (status == TitanOperationStatus.NOT_FOUND) {
169                                 return Either.left(false);
170                         } else {
171                                 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
172                                 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
173                         }
174                 }
175                 return Either.left(true);
176         }
177
178         public <T extends Component> Either<T, StorageOperationStatus> findLastCertifiedToscaElementByUUID(T component) {
179                 Map<GraphPropertyEnum, Object> props = new HashMap<>();
180                 props.put(GraphPropertyEnum.UUID, component.getUUID());
181                 props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
182                 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
183
184                 Either<List<GraphVertex>, TitanOperationStatus> getVertexEither = titanDao.getByCriteria(ModelConverter.getVertexType(component), props);
185                 if (getVertexEither.isRight()) {
186                         log.debug("Couldn't fetch component with and unique id {}, error: {}", component.getUniqueId(), getVertexEither.right().value());
187                         return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
188
189                 }
190                 return getToscaElementByOperation(getVertexEither.left().value().get(0));
191         }
192
193         // endregion
194         // region - ToscaElement - GetByOperation
195         private <T extends Component> Either<T, StorageOperationStatus> getToscaElementByOperation(GraphVertex componentV) {
196                 return getToscaElementByOperation(componentV, new ComponentParametersView());
197         }
198
199         private <T extends Component> Either<T, StorageOperationStatus> getToscaElementByOperation(GraphVertex componentV, ComponentParametersView filters) {
200                 VertexTypeEnum label = componentV.getLabel();
201
202                 ToscaElementOperation toscaOperation = getToscaElementOperation(componentV);
203                 Either<ToscaElement, StorageOperationStatus> toscaElement;
204                 String componentId = componentV.getUniqueId();
205                 if (toscaOperation != null) {
206                         log.debug("Need to fetch tosca element for id {}", componentId);
207                         toscaElement = toscaOperation.getToscaElement(componentV, filters);
208                 } else {
209                         log.debug("not supported tosca type {} for id {}", label, componentId);
210                         toscaElement = Either.right(StorageOperationStatus.BAD_REQUEST);
211                 }
212                 if (toscaElement.isRight()) {
213                         return Either.right(toscaElement.right().value());
214                 }
215                 return Either.left(ModelConverter.convertFromToscaElement(toscaElement.left().value()));
216         }
217
218         // endregion
219         private ToscaElementOperation getToscaElementOperation(GraphVertex componentV) {
220                 VertexTypeEnum label = componentV.getLabel();
221                 switch (label) {
222                 case NODE_TYPE:
223                         return nodeTypeOperation;
224                 case TOPOLOGY_TEMPLATE:
225                         return topologyTemplateOperation;
226                 default:
227                         return null;
228                 }
229         }
230
231         /**
232          *
233          * @param resource
234          * @return
235          */
236         public <T extends Component> Either<T, StorageOperationStatus> createToscaComponent(T resource) {
237                 ToscaElement toscaElement = ModelConverter.convertToToscaElement(resource);
238
239                 ToscaElementOperation toscaElementOperation = getToscaElementOperation(resource);
240                 Either<ToscaElement, StorageOperationStatus> createToscaElement = toscaElementOperation.createToscaElement(toscaElement);
241                 if (createToscaElement.isLeft()) {
242                         log.debug("Component created successfully!!!");
243                         T dataModel = ModelConverter.convertFromToscaElement(createToscaElement.left().value());
244                         return Either.left(dataModel);
245                 }
246                 return Either.right(createToscaElement.right().value());
247         }
248
249         // region - ToscaElement Delete
250         /**
251          *
252          * @param componentToDelete
253          * @return
254          */
255         public StorageOperationStatus markComponentToDelete(Component componentToDelete) {
256
257                 if ((componentToDelete.getIsDeleted() != null) && componentToDelete.getIsDeleted() && !componentToDelete.isHighestVersion()) {
258                         // component already marked for delete
259                         return StorageOperationStatus.OK;
260                 } else {
261
262                         Either<GraphVertex, TitanOperationStatus> getResponse = titanDao.getVertexById(componentToDelete.getUniqueId(), JsonParseFlagEnum.ParseAll);
263                         if (getResponse.isRight()) {
264                                 log.debug("Couldn't fetch component with and unique id {}, error: {}", componentToDelete.getUniqueId(), getResponse.right().value());
265                                 return DaoStatusConverter.convertTitanStatusToStorageStatus(getResponse.right().value());
266
267                         }
268                         GraphVertex componentV = getResponse.left().value();
269
270                         // same operation for node type and topology template operations
271                         Either<GraphVertex, StorageOperationStatus> result = nodeTypeOperation.markComponentToDelete(componentV);
272                         if (result.isRight()) {
273                                 return result.right().value();
274                         }
275                         return StorageOperationStatus.OK;
276                 }
277         }
278
279         /**
280          *
281          * @param componentId
282          * @return
283          */
284         public <T extends Component> Either<T, StorageOperationStatus> deleteToscaComponent(String componentId) {
285
286                 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll);
287                 if (getVertexEither.isRight()) {
288                         log.debug("Couldn't fetch component vertex with and unique id {}, error: {}", componentId, getVertexEither.right().value());
289                         return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
290
291                 }
292                 Either<ToscaElement, StorageOperationStatus> deleteElement = deleteToscaElement(getVertexEither.left().value());
293                 if (deleteElement.isRight()) {
294                         log.debug("Failed to delete component with and unique id {}, error: {}", componentId, deleteElement.right().value());
295                         return Either.right(deleteElement.right().value());
296                 }
297                 T dataModel = ModelConverter.convertFromToscaElement(deleteElement.left().value());
298
299                 return Either.left(dataModel);
300         }
301
302         private Either<ToscaElement, StorageOperationStatus> deleteToscaElement(GraphVertex componentV) {
303                 VertexTypeEnum label = componentV.getLabel();
304                 Either<ToscaElement, StorageOperationStatus> toscaElement;
305                 Object componentId = componentV.getUniqueId();
306                 switch (label) {
307                 case NODE_TYPE:
308                         log.debug("Need to fetch node type for id {}", componentId);
309                         toscaElement = nodeTypeOperation.deleteToscaElement(componentV);
310                         break;
311                 case TOPOLOGY_TEMPLATE:
312                         log.debug("Need to fetch topology template for id {}", componentId);
313                         toscaElement = topologyTemplateOperation.deleteToscaElement(componentV);
314                         break;
315                 default:
316                         log.debug("not supported tosca type {} for id {}", label, componentId);
317                         toscaElement = Either.right(StorageOperationStatus.BAD_REQUEST);
318                         break;
319                 }
320                 return toscaElement;
321         }
322         // endregion
323
324         private ToscaElementOperation getToscaElementOperation(Component component) {
325                 return ModelConverter.isAtomicComponent(component) ? nodeTypeOperation : topologyTemplateOperation;
326         }
327
328         public <T extends Component> Either<T, StorageOperationStatus> getLatestByToscaResourceName(String toscaResourceName) {
329                 return getLatestByName(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName);
330         }
331
332         public <T extends Component> Either<T, StorageOperationStatus> getFullLatestComponentByToscaResourceName(String toscaResourceName) {
333                 ComponentParametersView fetchAllFilter = new ComponentParametersView();
334                 fetchAllFilter.setIgnoreForwardingPath(true);
335                 fetchAllFilter.setIgnoreCapabiltyProperties(false);
336                 return getLatestByName(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName, JsonParseFlagEnum.ParseAll, fetchAllFilter);
337         }
338
339         public <T extends Component> Either<T, StorageOperationStatus> getLatestByName(String resourceName) {
340                 return getLatestByName(GraphPropertyEnum.NAME, resourceName);
341
342         }
343
344         public Either<Integer, StorageOperationStatus> validateCsarUuidUniqueness(String csarUUID) {
345
346                 Map<GraphPropertyEnum, Object> properties = new HashMap<GraphPropertyEnum, Object>();
347                 properties.put(GraphPropertyEnum.CSAR_UUID, csarUUID);
348
349                 Either<List<GraphVertex>, TitanOperationStatus> resources = titanDao.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata);
350
351                 if (resources.isRight()) {
352                         if (resources.right().value() == TitanOperationStatus.NOT_FOUND) {
353                                 return Either.left(new Integer(0));
354                         } else {
355                                 log.debug("failed to get resources from graph with property name: {}", csarUUID);
356                                 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resources.right().value()));
357                         }
358                 }
359
360                 List<GraphVertex> resourceList = (resources.isLeft() ? resources.left().value() : null);
361
362                 return Either.left(new Integer(resourceList.size()));
363
364         }
365
366         public <T extends Component> Either<Set<T>, StorageOperationStatus> getFollowed(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates, ComponentTypeEnum componentType) {
367                 Either<List<ToscaElement>, StorageOperationStatus> followedResources;
368                 if (componentType == ComponentTypeEnum.RESOURCE) {
369                         followedResources = nodeTypeOperation.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType);
370                 } else {
371                         followedResources = topologyTemplateOperation.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType);
372                 }
373
374                 Set<T> components = new HashSet<>();
375                 if (followedResources.isRight() && followedResources.right().value() != StorageOperationStatus.NOT_FOUND) {
376                         return Either.right(followedResources.right().value());
377                 }
378                 if (followedResources.isLeft()) {
379                         List<ToscaElement> toscaElements = followedResources.left().value();
380                         toscaElements.forEach(te -> {
381                                 T component = ModelConverter.convertFromToscaElement(te);
382                                 components.add(component);
383                         });
384                 }
385                 return Either.left(components);
386         }
387
388         public Either<Resource, StorageOperationStatus> getLatestCertifiedNodeTypeByToscaResourceName(String toscaResourceName) {
389
390                 return getLatestCertifiedByToscaResourceName(toscaResourceName, VertexTypeEnum.NODE_TYPE, JsonParseFlagEnum.ParseMetadata);
391         }
392
393         public Either<Resource, StorageOperationStatus> getLatestCertifiedByToscaResourceName(String toscaResourceName, VertexTypeEnum vertexType, JsonParseFlagEnum parseFlag) {
394
395                 Either<Resource, StorageOperationStatus> result = null;
396                 Map<GraphPropertyEnum, Object> props = new HashMap<GraphPropertyEnum, Object>();
397                 props.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName);
398                 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
399                 props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
400                 Either<List<GraphVertex>, TitanOperationStatus> getLatestRes = titanDao.getByCriteria(vertexType, props, parseFlag);
401
402                 if (getLatestRes.isRight()) {
403                         TitanOperationStatus status = getLatestRes.right().value();
404                         CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch {} with name {}. status={} ", vertexType, toscaResourceName, status);
405                         result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
406                 }
407                 if (result == null) {
408                         List<GraphVertex> resources = getLatestRes.left().value();
409                         double version = 0.0;
410                         GraphVertex highestResource = null;
411                         for (GraphVertex resource : resources) {
412                                 double resourceVersion = Double.parseDouble((String) resource.getJsonMetadataField(JsonPresentationFields.VERSION));
413                                 if (resourceVersion > version) {
414                                         version = resourceVersion;
415                                         highestResource = resource;
416                                 }
417                         }
418                         result = getToscaFullElement(highestResource.getUniqueId());
419                 }
420                 return result;
421         }
422
423         public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExists(String templateName) {
424                 Either<Boolean, StorageOperationStatus> validateUniquenessRes = validateToscaResourceNameUniqueness(templateName);
425                 if (validateUniquenessRes.isLeft()) {
426                         return Either.left(!validateUniquenessRes.left().value());
427                 }
428                 return validateUniquenessRes;
429         }
430
431         public Either<RequirementCapabilityRelDef, StorageOperationStatus> dissociateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) {
432                 return nodeTemplateOperation.dissociateResourceInstances(componentId, requirementDef);
433         }
434         /**
435          * Allows to get fulfilled requirement by relation and received predicate
436          * @param componentId
437          * @param instanceId
438          * @param relation
439          * @param predicate
440          * @return
441          */
442         public Either<RequirementDataDefinition, StorageOperationStatus> getFulfilledRequirementByRelation(String componentId, String instanceId, RequirementCapabilityRelDef relation, BiPredicate<RelationshipInfo, RequirementDataDefinition> predicate) {
443                 return nodeTemplateOperation.getFulfilledRequirementByRelation(componentId, instanceId, relation, predicate);
444         }
445         /**
446          * Allows to get fulfilled capability by relation and received predicate
447          * @param componentId
448          * @param instanceId
449          * @param relation
450          * @param predicate
451          * @return
452          */
453         public Either<CapabilityDataDefinition, StorageOperationStatus> getFulfilledCapabilityByRelation(String componentId, String instanceId, RequirementCapabilityRelDef relation, BiPredicate<RelationshipInfo, CapabilityDataDefinition> predicate) {
454                 return nodeTemplateOperation.getFulfilledCapabilityByRelation(componentId, instanceId, relation, predicate);
455         }
456
457         public StorageOperationStatus associateResourceInstances(String componentId, List<RequirementCapabilityRelDef> relations) {
458                 Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> status = nodeTemplateOperation.associateResourceInstances(componentId, relations);
459                 if (status.isRight()) {
460                         return status.right().value();
461                 }
462                 return StorageOperationStatus.OK;
463         }
464
465         protected Either<Boolean, StorageOperationStatus> validateToscaResourceNameUniqueness(String name) {
466
467                 Map<GraphPropertyEnum, Object> properties = new HashMap<GraphPropertyEnum, Object>();
468                 properties.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, name);
469
470                 Either<List<GraphVertex>, TitanOperationStatus> resources = titanDao.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata);
471
472                 if (resources.isRight() && resources.right().value() != TitanOperationStatus.NOT_FOUND) {
473                         log.debug("failed to get resources from graph with property name: {}", name);
474                         return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resources.right().value()));
475                 }
476                 List<GraphVertex> resourceList = (resources.isLeft() ? resources.left().value() : null);
477                 if (resourceList != null && resourceList.size() > 0) {
478                         if (log.isDebugEnabled()) {
479                                 StringBuilder builder = new StringBuilder();
480                                 for (GraphVertex resourceData : resourceList) {
481                                         builder.append(resourceData.getUniqueId() + "|");
482                                 }
483                                 log.debug("resources  with property name:{} exists in graph. found {}", name, builder.toString());
484                         }
485                         return Either.left(false);
486                 } else {
487                         log.debug("resources  with property name:{} does not exists in graph", name);
488                         return Either.left(true);
489                 }
490
491         }
492
493         // region - Component Update
494         /**
495          *
496          * @param newComponent
497          * @param oldComponent
498          * @return vendor
499          */
500         public Either<Resource, StorageOperationStatus> overrideComponent(Resource newComponent, Resource oldComponent) {
501
502                 // TODO
503                 // newComponent.setInterfaces(oldComponent.getInterfaces);
504                 newComponent.setArtifacts(oldComponent.getArtifacts());
505                 newComponent.setDeploymentArtifacts(oldComponent.getDeploymentArtifacts());
506                 newComponent.setGroups(oldComponent.getGroups());
507                 newComponent.setLastUpdateDate(null);
508                 newComponent.setHighestVersion(true);
509
510                 Either<GraphVertex, TitanOperationStatus> componentVEither = titanDao.getVertexById(oldComponent.getUniqueId(), JsonParseFlagEnum.NoParse);
511                 if (componentVEither.isRight()) {
512                         log.debug("Falied to fetch component {} error {}", oldComponent.getUniqueId(), componentVEither.right().value());
513                         return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(componentVEither.right().value()));
514                 }
515                 GraphVertex componentv = componentVEither.left().value();
516                 Either<GraphVertex, TitanOperationStatus> parentVertexEither = titanDao.getParentVertex(componentv, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse);
517                 if (parentVertexEither.isRight() && parentVertexEither.right().value() != TitanOperationStatus.NOT_FOUND) {
518                         log.debug("Falied to fetch parent version for component {} error {}", oldComponent.getUniqueId(), parentVertexEither.right().value());
519                         return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(parentVertexEither.right().value()));
520                 }
521
522                 Either<ToscaElement, StorageOperationStatus> deleteToscaComponent = deleteToscaElement(componentv);
523                 if (deleteToscaComponent.isRight()) {
524                         log.debug("Falied to remove old component {} error {}", oldComponent.getUniqueId(), deleteToscaComponent.right().value());
525                         return Either.right(deleteToscaComponent.right().value());
526                 }
527                 Either<Resource, StorageOperationStatus> createToscaComponent = createToscaComponent(newComponent);
528                 if (createToscaComponent.isRight()) {
529                         log.debug("Falied to create tosca element component {} error {}", newComponent.getUniqueId(), createToscaComponent.right().value());
530                         return Either.right(createToscaComponent.right().value());
531                 }
532                 Resource newElement = createToscaComponent.left().value();
533                 Either<GraphVertex, TitanOperationStatus> newVersionEither = titanDao.getVertexById(newElement.getUniqueId(), JsonParseFlagEnum.NoParse);
534                 if (newVersionEither.isRight()) {
535                         log.debug("Falied to fetch new tosca element component {} error {}", newComponent.getUniqueId(), newVersionEither.right().value());
536                         return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(newVersionEither.right().value()));
537                 }
538                 if (parentVertexEither.isLeft()) {
539                         GraphVertex previousVersionV = parentVertexEither.left().value();
540                         TitanOperationStatus createEdge = titanDao.createEdge(previousVersionV, newVersionEither.left().value(), EdgeLabelEnum.VERSION, null);
541                         if (createEdge != TitanOperationStatus.OK) {
542                                 log.debug("Falied to associate to previous version {} new version {} error {}", previousVersionV.getUniqueId(), newVersionEither.right().value(), createEdge);
543                                 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createEdge));
544                         }
545                 }
546                 return Either.left(newElement);
547         }
548
549         /**
550          *
551          * @param componentToUpdate
552          * @return
553          */
554         public <T extends Component> Either<T, StorageOperationStatus> updateToscaElement(T componentToUpdate) {
555                 return updateToscaElement(componentToUpdate, new ComponentParametersView());
556         }
557
558         /**
559          *
560          * @param componentToUpdate
561          * @param type
562          * @param filterResult
563          * @return
564          */
565         public <T extends Component> Either<T, StorageOperationStatus> updateToscaElement(T componentToUpdate, ComponentParametersView filterResult) {
566                 String componentId = componentToUpdate.getUniqueId();
567                 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll);
568                 if (getVertexEither.isRight()) {
569                         log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
570                         return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
571                 }
572                 GraphVertex elementV = getVertexEither.left().value();
573                 ToscaElementOperation toscaElementOperation = getToscaElementOperation(elementV);
574
575                 ToscaElement toscaElementToUpdate = ModelConverter.convertToToscaElement(componentToUpdate);
576                 Either<ToscaElement, StorageOperationStatus> updateToscaElement = toscaElementOperation.updateToscaElement(toscaElementToUpdate, elementV, filterResult);
577                 if (updateToscaElement.isRight()) {
578                         log.debug("Failed to update tosca element {} error {}", componentId, updateToscaElement.right().value());
579                         return Either.right(updateToscaElement.right().value());
580                 }
581                 return Either.left(ModelConverter.convertFromToscaElement(updateToscaElement.left().value()));
582         }
583
584         private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName, JsonParseFlagEnum parseFlag) {
585                 return getLatestByName(property, nodeName, parseFlag, new ComponentParametersView());
586         }
587
588         private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName, JsonParseFlagEnum parseFlag, ComponentParametersView filter) {
589                 Either<T, StorageOperationStatus> result;
590
591                 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
592                 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
593
594                 propertiesToMatch.put(property, nodeName);
595                 propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
596
597                 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
598
599                 Either<List<GraphVertex>, TitanOperationStatus> highestResources = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, parseFlag);
600                 if (highestResources.isRight()) {
601                         TitanOperationStatus status = highestResources.right().value();
602                         log.debug("failed to find resource with name {}. status={} ", nodeName, status);
603                         result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
604                         return result;
605                 }
606
607                 List<GraphVertex> resources = highestResources.left().value();
608                 double version = 0.0;
609                 GraphVertex highestResource = null;
610                 for (GraphVertex vertex : resources) {
611                         Object versionObj = vertex.getMetadataProperty(GraphPropertyEnum.VERSION);
612                         double resourceVersion = Double.valueOf((String) versionObj);
613                         if (resourceVersion > version) {
614                                 version = resourceVersion;
615                                 highestResource = vertex;
616                         }
617                 }
618                 return getToscaElementByOperation(highestResource, filter);
619         }
620
621         // endregion
622         // region - Component Get By ..
623         private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName) {
624                 return getLatestByName(property, nodeName, JsonParseFlagEnum.ParseMetadata);
625         }
626
627         public <T extends Component> Either<List<T>, StorageOperationStatus> getBySystemName(ComponentTypeEnum componentType, String systemName) {
628
629                 Either<List<T>, StorageOperationStatus> result = null;
630                 Either<T, StorageOperationStatus> getComponentRes;
631                 List<T> components = new ArrayList<>();
632                 List<GraphVertex> componentVertices;
633                 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
634                 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
635
636                 propertiesToMatch.put(GraphPropertyEnum.SYSTEM_NAME, systemName);
637                 if (componentType != null)
638                         propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
639
640                 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
641
642                 Either<List<GraphVertex>, TitanOperationStatus> getComponentsRes = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
643                 if (getComponentsRes.isRight()) {
644                         TitanOperationStatus status = getComponentsRes.right().value();
645                         log.debug("Failed to fetch the component with system name {}. Status is {} ", systemName, status);
646                         result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
647                 }
648                 if (result == null) {
649                         componentVertices = getComponentsRes.left().value();
650                         for (GraphVertex componentVertex : componentVertices) {
651                                 getComponentRes = getToscaElementByOperation(componentVertex);
652                                 if (getComponentRes.isRight()) {
653                                         log.debug("Failed to get the component {}. Status is {} ", componentVertex.getJsonMetadataField(JsonPresentationFields.NAME), getComponentRes.right().value());
654                                         result = Either.right(getComponentRes.right().value());
655                                         break;
656                                 }
657                                 T componentBySystemName = getComponentRes.left().value();
658                                 log.debug("Found component, id: {}", componentBySystemName.getUniqueId());
659                                 components.add(componentBySystemName);
660                         }
661                 }
662                 if (result == null) {
663                         result = Either.left(components);
664                 }
665                 return result;
666         }
667
668         public <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVersion(ComponentTypeEnum componentType, String name, String version) {
669                 return getComponentByNameAndVersion(componentType, name, version, JsonParseFlagEnum.ParseAll);
670         }
671
672         public <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVersion(ComponentTypeEnum componentType, String name, String version, JsonParseFlagEnum parseFlag) {
673                 Either<T, StorageOperationStatus> result;
674
675                 Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
676                 Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class);
677
678                 hasProperties.put(GraphPropertyEnum.NAME, name);
679                 hasProperties.put(GraphPropertyEnum.VERSION, version);
680                 hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true);
681                 if (componentType != null) {
682                         hasProperties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
683                 }
684                 Either<List<GraphVertex>, TitanOperationStatus> getResourceRes = titanDao.getByCriteria(null, hasProperties, hasNotProperties, parseFlag);
685                 if (getResourceRes.isRight()) {
686                         TitanOperationStatus status = getResourceRes.right().value();
687                         log.debug("failed to find resource with name {}, version {}. Status is {} ", name, version, status);
688                         result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
689                         return result;
690                 }
691                 return getToscaElementByOperation(getResourceRes.left().value().get(0));
692         }
693         public Either<List<CatalogComponent>, StorageOperationStatus> getCatalogComponents() {
694                 return topologyTemplateOperation.getElementCatalogData();
695         }
696
697         // endregion
698         public <T extends Component> Either<List<T>, StorageOperationStatus> getCatalogComponents(ComponentTypeEnum componentType, List<OriginTypeEnum> excludeTypes, boolean isHighestVersions) {
699                 List<T> components = new ArrayList<>();
700                 Either<List<ToscaElement>, StorageOperationStatus> catalogDataResult;
701                 List<ToscaElement> toscaElements = new ArrayList<>();
702                 List<ResourceTypeEnum> excludedResourceTypes = Optional.ofNullable(excludeTypes).orElse(Collections.emptyList()).stream().filter(type -> !type.equals(OriginTypeEnum.SERVICE)).map(type -> ResourceTypeEnum.getTypeByName(type.name()))
703                                 .collect(Collectors.toList());
704
705                 switch (componentType) {
706                 case RESOURCE:
707                         catalogDataResult = nodeTypeOperation.getElementCatalogData(ComponentTypeEnum.RESOURCE, excludedResourceTypes, isHighestVersions);
708                         if (catalogDataResult.isRight()) {
709                                 return Either.right(catalogDataResult.right().value());
710                         }
711                         toscaElements = catalogDataResult.left().value();
712                         break;
713                 case SERVICE:
714                         if (excludeTypes != null && excludeTypes.contains(OriginTypeEnum.SERVICE)) {
715                                 break;
716                         }
717                         catalogDataResult = topologyTemplateOperation.getElementCatalogData(ComponentTypeEnum.SERVICE, null, isHighestVersions);
718                         if (catalogDataResult.isRight()) {
719                                 return Either.right(catalogDataResult.right().value());
720                         }
721                         toscaElements = catalogDataResult.left().value();
722                         break;
723                 default:
724                         log.debug("Not supported component type {}", componentType);
725                         return Either.right(StorageOperationStatus.BAD_REQUEST);
726                 }
727                 toscaElements.forEach(te -> {
728                         T component = ModelConverter.convertFromToscaElement(te);
729                         components.add(component);
730                 });
731                 return Either.left(components);
732         }
733
734         public Either<List<String>, StorageOperationStatus> deleteMarkedElements(ComponentTypeEnum componentType) {
735                 Either<List<GraphVertex>, StorageOperationStatus> allComponentsMarkedForDeletion;
736                 List<String> deleted = new ArrayList<>();
737                 switch (componentType) {
738                 case RESOURCE:
739                         allComponentsMarkedForDeletion = nodeTypeOperation.getAllComponentsMarkedForDeletion(componentType);
740                         break;
741                 case SERVICE:
742                 case PRODUCT:
743                         allComponentsMarkedForDeletion = topologyTemplateOperation.getAllComponentsMarkedForDeletion(componentType);
744                         break;
745                 default:
746                         log.debug("Not supported component type {}", componentType);
747                         return Either.right(StorageOperationStatus.BAD_REQUEST);
748                 }
749                 if (allComponentsMarkedForDeletion.isRight()) {
750                         return Either.right(allComponentsMarkedForDeletion.right().value());
751                 }
752                 List<GraphVertex> allMarked = allComponentsMarkedForDeletion.left().value();
753
754                 Either<List<GraphVertex>, TitanOperationStatus> allNotDeletedElements = topologyTemplateOperation.getAllNotDeletedElements();
755                 if (allNotDeletedElements.isRight()) {
756                         return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(allNotDeletedElements.right().value()));
757                 }
758                 List<GraphVertex> allNonMarked = allNotDeletedElements.left().value();
759                 for (GraphVertex elementV : allMarked) {
760                         if (topologyTemplateOperation.isInUse(elementV, allNonMarked) == false) {
761                                 Either<ToscaElement, StorageOperationStatus> deleteToscaElement = deleteToscaElement(elementV);
762                                 if (deleteToscaElement.isRight()) {
763                                         log.debug("Failed to delete marked element {} error {}", elementV.getUniqueId(), deleteToscaElement.right().value());
764                                 }
765                         } else {
766                                 deleted.add(elementV.getUniqueId());
767                                 log.debug("Marked element {} in use. don't delete it", elementV.getUniqueId());
768                         }
769                 }
770                 return Either.left(deleted);
771         }
772
773         public Either<List<String>, StorageOperationStatus> getAllComponentsMarkedForDeletion(ComponentTypeEnum componentType) {
774                 Either<List<GraphVertex>, StorageOperationStatus> allComponentsMarkedForDeletion;
775                 switch (componentType) {
776                 case RESOURCE:
777                         allComponentsMarkedForDeletion = nodeTypeOperation.getAllComponentsMarkedForDeletion(componentType);
778                         break;
779                 case SERVICE:
780                 case PRODUCT:
781                         allComponentsMarkedForDeletion = topologyTemplateOperation.getAllComponentsMarkedForDeletion(componentType);
782                         break;
783                 default:
784                         log.debug("Not supported component type {}", componentType);
785                         return Either.right(StorageOperationStatus.BAD_REQUEST);
786                 }
787                 if (allComponentsMarkedForDeletion.isRight()) {
788                         return Either.right(allComponentsMarkedForDeletion.right().value());
789                 }
790                 return Either.left(allComponentsMarkedForDeletion.left().value().stream().map(v -> v.getUniqueId()).collect(Collectors.toList()));
791         }
792
793         public Either<Boolean, StorageOperationStatus> isComponentInUse(String componentId) {
794                 Either<Boolean, StorageOperationStatus> result;
795                 Either<List<GraphVertex>, TitanOperationStatus> allNotDeletedElements = topologyTemplateOperation.getAllNotDeletedElements();
796                 if (allNotDeletedElements.isRight()) {
797                         result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(allNotDeletedElements.right().value()));
798                 } else {
799                         result = Either.left(topologyTemplateOperation.isInUse(componentId, allNotDeletedElements.left().value()));
800                 }
801                 return result;
802         }
803
804         // region - Component Update
805         public Either<ImmutablePair<Component, String>, StorageOperationStatus> addComponentInstanceToTopologyTemplate(Component containerComponent, Component origComponent, ComponentInstance componentInstance, boolean allowDeleted, User user) {
806
807                 Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
808                 Either<ToscaElement, StorageOperationStatus> updateContainerComponentRes = null;
809                 if (StringUtils.isEmpty(componentInstance.getIcon())) {
810                         componentInstance.setIcon(origComponent.getIcon());
811                 }
812                 String nameToFindForCounter = componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy ? componentInstance.getSourceModelName() + PROXY_SUFFIX : origComponent.getName();
813                 String nextComponentInstanceCounter = getNextComponentInstanceCounter(containerComponent, nameToFindForCounter);
814                 Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> addResult = nodeTemplateOperation.addComponentInstanceToTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent),
815                                 ModelConverter.convertToToscaElement(origComponent), nextComponentInstanceCounter, componentInstance, allowDeleted, user);
816
817                 if (addResult.isRight()) {
818                         CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the component instance {} to container component {}. ", componentInstance.getName(), containerComponent.getName());
819                         result = Either.right(addResult.right().value());
820                 }
821                 if (result == null) {
822                         updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponent.getUniqueId());
823                         if (updateContainerComponentRes.isRight()) {
824                                 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} with updated component instance {}. ", containerComponent.getName(), componentInstance.getName());
825                                 result = Either.right(updateContainerComponentRes.right().value());
826                         }
827                 }
828                 if (result == null) {
829                         Component updatedComponent = ModelConverter.convertFromToscaElement(updateContainerComponentRes.left().value());
830                         String createdInstanceId = addResult.left().value().getRight();
831                         CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been added to container component {}. ", createdInstanceId, updatedComponent.getName());
832                         result = Either.left(new ImmutablePair<>(updatedComponent, createdInstanceId));
833                 }
834                 return result;
835         }
836
837         public StorageOperationStatus associateComponentInstancesToComponent(Component containerComponent, Map<ComponentInstance, Resource> resourcesInstancesMap, boolean allowDeleted) {
838
839                 StorageOperationStatus result = null;
840                 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Going to add component instances to component {}", containerComponent.getUniqueId());
841
842                 Either<GraphVertex, TitanOperationStatus> metadataVertex = titanDao.getVertexById(containerComponent.getUniqueId(), JsonParseFlagEnum.ParseAll);
843                 if (metadataVertex.isRight()) {
844                         TitanOperationStatus status = metadataVertex.right().value();
845                         if (status == TitanOperationStatus.NOT_FOUND) {
846                                 status = TitanOperationStatus.INVALID_ID;
847                         }
848                         result = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
849                 }
850                 if (result == null) {
851                         result = nodeTemplateOperation.associateComponentInstancesToComponent(containerComponent, resourcesInstancesMap, metadataVertex.left().value(), allowDeleted);
852                 }
853                 return result;
854         }
855
856         public Either<ImmutablePair<Component, String>, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent, Component origComponent, ComponentInstance componentInstance) {
857
858                 Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
859
860                 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(), containerComponent.getName());
861                 componentInstance.setIcon(origComponent.getIcon());
862                 Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> updateResult = nodeTemplateOperation.updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent),
863                                 ModelConverter.convertToToscaElement(origComponent), componentInstance);
864                 if (updateResult.isRight()) {
865                         CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(), containerComponent.getName());
866                         result = Either.right(updateResult.right().value());
867                 }
868                 if (result == null) {
869                         Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value().getLeft());
870                         String createdInstanceId = updateResult.left().value().getRight();
871                         CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The metadata of the component instance {} has been updated to container component {}. ", createdInstanceId, updatedComponent.getName());
872                         result = Either.left(new ImmutablePair<>(updatedComponent, createdInstanceId));
873                 }
874                 return result;
875         }
876
877         public Either<Component, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent) {
878                 return updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, new ComponentParametersView());
879         }
880
881         public Either<Component, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent, ComponentParametersView filter) {
882
883                 Either<Component, StorageOperationStatus> result = null;
884
885                 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update the metadata  belonging to container component {}. ", containerComponent.getName());
886
887                 Either<TopologyTemplate, StorageOperationStatus> updateResult = nodeTemplateOperation.updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), filter);
888                 if (updateResult.isRight()) {
889                         CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the metadata  belonging to container component {}. ", containerComponent.getName());
890                         result = Either.right(updateResult.right().value());
891                 }
892                 if (result == null) {
893                         Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value());
894                         CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The metadata has been updated to container component {}. ", updatedComponent.getName());
895                         result = Either.left(updatedComponent);
896                 }
897                 return result;
898         }
899         // endregion
900
901         public Either<ImmutablePair<Component, String>, StorageOperationStatus> deleteComponentInstanceFromTopologyTemplate(Component containerComponent, String resourceInstanceId) {
902
903                 Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
904
905                 CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to delete the component instance {} belonging to container component {}. ", resourceInstanceId, containerComponent.getName());
906
907                 Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> updateResult = nodeTemplateOperation.deleteComponentInstanceFromTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), resourceInstanceId);
908                 if (updateResult.isRight()) {
909                         CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete the component instance {} belonging to container component {}. ", resourceInstanceId, containerComponent.getName());
910                         result = Either.right(updateResult.right().value());
911                 }
912                 if (result == null) {
913                         Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value().getLeft());
914                         String deletedInstanceId = updateResult.left().value().getRight();
915                         CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been deleted from container component {}. ", deletedInstanceId, updatedComponent.getName());
916                         result = Either.left(new ImmutablePair<>(updatedComponent, deletedInstanceId));
917                 }
918                 return result;
919         }
920
921         private String getNextComponentInstanceCounter(Component containerComponent, String originResourceName) {
922
923                 Integer nextCounter = 0;
924
925                 if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) {
926
927                         String normalizedName = ValidationUtils.normalizeComponentInstanceName(originResourceName);
928                         Integer maxCounterFromNames = getMaxCounterFromNames(containerComponent, normalizedName);
929                         Integer maxCounterFromIds = getMaxCounterFromIds(containerComponent, normalizedName);
930
931                         if (maxCounterFromNames == null && maxCounterFromIds != null) {
932                                 nextCounter = maxCounterFromIds + 1;
933                         } else if (maxCounterFromIds == null && maxCounterFromNames != null) {
934                                 nextCounter = maxCounterFromNames + 1;
935                         } else if (maxCounterFromIds != null && maxCounterFromNames != null) {
936                                 nextCounter = maxCounterFromNames > maxCounterFromIds ? maxCounterFromNames + 1 : maxCounterFromIds + 1;
937                         }
938                 }
939                 return nextCounter.toString();
940         }
941
942         private Integer getMaxCounterFromNames(Component containerComponent, String normalizedName) {
943
944                 Integer maxCounter = 0;
945                 List<String> countersStr = containerComponent.getComponentInstances().stream().filter(ci -> ci.getNormalizedName() != null && ci.getNormalizedName().startsWith(normalizedName)).map(ci -> ci.getNormalizedName().split(normalizedName)[1])
946                                 .collect(Collectors.toList());
947
948                 if (CollectionUtils.isEmpty(countersStr)) {
949                         return null;
950                 }
951                 Integer currCounter = null;
952                 for (String counter : countersStr) {
953                         if (StringUtils.isEmpty(counter)) {
954                                 continue;
955                         }
956                         try {
957                                 currCounter = Integer.parseInt(counter);
958                         } catch (Exception e) {
959                                 continue;
960                         }
961                         maxCounter = maxCounter < currCounter ? currCounter : maxCounter;
962                 }
963                 if (currCounter == null) {
964                         return null;
965                 }
966                 return maxCounter;
967         }
968
969         private Integer getMaxCounterFromIds(Component containerComponent, String normalizedName) {
970
971                 Integer maxCounter = 0;
972                 List<String> countersStr = containerComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId() != null && ci.getUniqueId().contains(normalizedName)).map(ci -> ci.getUniqueId().split(normalizedName)[1])
973                                 .collect(Collectors.toList());
974
975                 if (CollectionUtils.isEmpty(countersStr)) {
976                         return null;
977                 }
978                 Integer currCounter = null;
979                 for (String counter : countersStr) {
980                         if (StringUtils.isEmpty(counter)) {
981                                 continue;
982                         }
983                         try {
984                                 currCounter = Integer.parseInt(counter);
985                         } catch (Exception e) {
986                                 continue;
987                         }
988                         maxCounter = maxCounter < currCounter ? currCounter : maxCounter;
989                 }
990                 if (currCounter == null) {
991                         return null;
992                 }
993                 return maxCounter;
994         }
995
996         public Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) {
997                 return nodeTemplateOperation.associateResourceInstances(componentId, requirementDef);
998
999         }
1000
1001         public Either<List<InputDefinition>, StorageOperationStatus> createAndAssociateInputs(Map<String, InputDefinition> inputs, String componentId) {
1002
1003                 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1004                 if (getVertexEither.isRight()) {
1005                         log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
1006                         return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
1007
1008                 }
1009
1010                 GraphVertex vertex = getVertexEither.left().value();
1011                 Map<String, PropertyDataDefinition> inputsMap = inputs.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDataDefinition(e.getValue())));
1012
1013                 StorageOperationStatus status = topologyTemplateOperation.associateInputsToComponent(vertex, inputsMap, componentId);
1014
1015                 if (StorageOperationStatus.OK == status) {
1016                         log.debug("Component created successfully!!!");
1017                         List<InputDefinition> inputsResList = null;
1018                         if (inputsMap != null && !inputsMap.isEmpty()) {
1019                                 inputsResList = inputsMap.values().stream().map(i -> new InputDefinition(i)).collect(Collectors.toList());
1020                         }
1021                         return Either.left(inputsResList);
1022                 }
1023                 return Either.right(status);
1024
1025         }
1026
1027         public Either<List<InputDefinition>, StorageOperationStatus> addInputsToComponent(Map<String, InputDefinition> inputs, String componentId) {
1028
1029                 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1030                 if (getVertexEither.isRight()) {
1031                         log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
1032                         return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
1033
1034                 }
1035
1036                 GraphVertex vertex = getVertexEither.left().value();
1037                 Map<String, PropertyDataDefinition> inputsMap = inputs.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDataDefinition(e.getValue())));
1038
1039                 StorageOperationStatus status = topologyTemplateOperation.addToscaDataToToscaElement(vertex, EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputsMap, JsonPresentationFields.NAME);
1040
1041                 if (StorageOperationStatus.OK == status) {
1042                         log.debug("Component created successfully!!!");
1043                         List<InputDefinition> inputsResList = null;
1044                         if (inputsMap != null && !inputsMap.isEmpty()) {
1045                                 inputsResList = inputsMap.values().stream().map(i -> new InputDefinition(i)).collect(Collectors.toList());
1046                         }
1047                         return Either.left(inputsResList);
1048                 }
1049                 return Either.right(status);
1050
1051         }
1052
1053         public Either<List<InputDefinition>, StorageOperationStatus> updateInputsToComponent(List<InputDefinition> inputs, String componentId) {
1054
1055                 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1056                 if (getVertexEither.isRight()) {
1057                         log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
1058                         return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
1059
1060                 }
1061
1062                 GraphVertex vertex = getVertexEither.left().value();
1063                 List<PropertyDataDefinition> inputsAsDataDef = inputs.stream().map(PropertyDataDefinition::new).collect(Collectors.toList());
1064
1065                 StorageOperationStatus status = topologyTemplateOperation.updateToscaDataOfToscaElement(vertex, EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputsAsDataDef, JsonPresentationFields.NAME);
1066
1067                 if (StorageOperationStatus.OK == status) {
1068                         log.debug("Component created successfully!!!");
1069                         List<InputDefinition> inputsResList = null;
1070                         if (inputsAsDataDef != null && !inputsAsDataDef.isEmpty()) {
1071                                 inputsResList = inputsAsDataDef.stream().map(InputDefinition::new).collect(Collectors.toList());
1072                         }
1073                         return Either.left(inputsResList);
1074                 }
1075                 return Either.right(status);
1076
1077         }
1078
1079         // region - ComponentInstance
1080         public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> associateComponentInstancePropertiesToComponent(Map<String, List<ComponentInstanceProperty>> instProperties, String componentId) {
1081
1082                 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1083                 if (getVertexEither.isRight()) {
1084                         log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
1085                         return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
1086
1087                 }
1088
1089                 GraphVertex vertex = getVertexEither.left().value();
1090                 Map<String, MapPropertiesDataDefinition> instPropsMap = new HashMap<>();
1091                 if (instProperties != null) {
1092
1093                         MapPropertiesDataDefinition propertiesMap;
1094                         for (Entry<String, List<ComponentInstanceProperty>> entry : instProperties.entrySet()) {
1095                                 propertiesMap = new MapPropertiesDataDefinition();
1096
1097                                 propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e)));
1098
1099                                 instPropsMap.put(entry.getKey(), propertiesMap);
1100                         }
1101                 }
1102
1103                 StorageOperationStatus status = topologyTemplateOperation.associateInstPropertiesToComponent(vertex, instPropsMap);
1104
1105                 if (StorageOperationStatus.OK == status) {
1106                         log.debug("Component created successfully!!!");
1107                         return Either.left(instProperties);
1108                 }
1109                 return Either.right(status);
1110
1111         }
1112
1113         /**
1114          * saves the instInputs as the updated instance inputs of the component container in DB
1115          * @param instInputs
1116          * @param componentId
1117          * @return
1118          */
1119         public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> updateComponentInstanceInputsToComponent(Map<String, List<ComponentInstanceInput>> instInputs, String componentId) {
1120                 if (instInputs == null || instInputs.isEmpty()) {
1121                         return Either.left(instInputs);
1122                 }
1123                 StorageOperationStatus status;
1124                 for ( Entry<String, List<ComponentInstanceInput>> inputsPerIntance : instInputs.entrySet() ) {
1125                         List<ComponentInstanceInput> toscaDataListPerInst = inputsPerIntance.getValue();
1126                         List<String> pathKeysPerInst = new ArrayList<>();
1127                         pathKeysPerInst.add(inputsPerIntance.getKey());
1128                         status = topologyTemplateOperation.updateToscaDataDeepElementsOfToscaElement(componentId, EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, toscaDataListPerInst, pathKeysPerInst, JsonPresentationFields.NAME);
1129                         if ( status != StorageOperationStatus.OK) {
1130                                 log.debug("Failed to update component instance inputs for instance {} in component {} edge type {} error {}", inputsPerIntance.getKey(), componentId,  EdgeLabelEnum.INST_INPUTS, status);
1131                                 return Either.right(status);
1132                         }
1133                 }
1134
1135                 return Either.left(instInputs);
1136         }
1137
1138         /**
1139          * saves the instProps as the updated instance properties of the component container in DB
1140          * @param instProps
1141          * @param componentId
1142          * @return
1143          */
1144         public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> updateComponentInstancePropsToComponent(Map<String, List<ComponentInstanceProperty>> instProps, String componentId) {
1145                 if (instProps == null || instProps.isEmpty()) {
1146                         return Either.left(instProps);
1147                 }
1148                 StorageOperationStatus status;
1149                 for ( Entry<String, List<ComponentInstanceProperty>> propsPerIntance : instProps.entrySet() ) {
1150                         List<ComponentInstanceProperty> toscaDataListPerInst = propsPerIntance.getValue();
1151                         List<String> pathKeysPerInst = new ArrayList<>();
1152                         pathKeysPerInst.add(propsPerIntance.getKey());
1153                         status = topologyTemplateOperation.updateToscaDataDeepElementsOfToscaElement(componentId, EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, toscaDataListPerInst, pathKeysPerInst, JsonPresentationFields.NAME);
1154                         if ( status != StorageOperationStatus.OK) {
1155                                 log.debug("Failed to update component instance inputs for instance {} in component {} edge type {} error {}", propsPerIntance.getKey(), componentId,  EdgeLabelEnum.INST_PROPERTIES, status);
1156                                 return Either.right(status);
1157                         }
1158                 }
1159
1160                 return Either.left(instProps);
1161         }
1162
1163         public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> associateComponentInstanceInputsToComponent(Map<String, List<ComponentInstanceInput>> instInputs, String componentId) {
1164
1165                 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1166                 if (getVertexEither.isRight()) {
1167                         log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
1168                         return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
1169
1170                 }
1171                 GraphVertex vertex = getVertexEither.left().value();
1172                 Map<String, MapPropertiesDataDefinition> instPropsMap = new HashMap<>();
1173                 if (instInputs != null) {
1174
1175                         MapPropertiesDataDefinition propertiesMap;
1176                         for (Entry<String, List<ComponentInstanceInput>> entry : instInputs.entrySet()) {
1177                                 propertiesMap = new MapPropertiesDataDefinition();
1178
1179                                 propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e)));
1180
1181                                 instPropsMap.put(entry.getKey(), propertiesMap);
1182                         }
1183                 }
1184
1185                 StorageOperationStatus status = topologyTemplateOperation.associateInstInputsToComponent(vertex, instPropsMap);
1186
1187                 if (StorageOperationStatus.OK == status) {
1188                         log.debug("Component created successfully!!!");
1189                         return Either.left(instInputs);
1190                 }
1191                 return Either.right(status);
1192
1193         }
1194
1195         public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addComponentInstanceInputsToComponent(Component containerComponent, Map<String, List<ComponentInstanceInput>> instProperties) {
1196
1197                 StorageOperationStatus status = StorageOperationStatus.OK;
1198                 if (instProperties != null) {
1199
1200                         for (Entry<String, List<ComponentInstanceInput>> entry : instProperties.entrySet()) {
1201                                 List<ComponentInstanceInput> props = entry.getValue();
1202                                 String componentInstanseId = entry.getKey();
1203                                 if (props != null && !props.isEmpty()) {
1204                                         for (ComponentInstanceInput property : props) {
1205                                                 List<ComponentInstanceInput> componentInstancesInputs = containerComponent.getComponentInstancesInputs().get(componentInstanseId);
1206                                                 Optional<ComponentInstanceInput> instanceProperty = componentInstancesInputs.stream().filter(p -> p.getName().equals(property.getName())).findAny();
1207                                                 if (instanceProperty.isPresent()) {
1208                                                         status = updateComponentInstanceInput(containerComponent, componentInstanseId, property);
1209                                                 } else {
1210                                                         status = addComponentInstanceInput(containerComponent, componentInstanseId, property);
1211                                                 }
1212                                                 if (status != StorageOperationStatus.OK) {
1213                                                         log.debug("Failed to update instance input {} for instance {} error {} ", property, componentInstanseId, status);
1214                                                         return Either.right(status);
1215                                                 } else {
1216                                                         log.trace("instance input {} for instance {} updated", property, componentInstanseId);
1217                                                 }
1218                                         }
1219                                 }
1220                         }
1221                 }
1222                 return Either.left(instProperties);
1223         }
1224
1225         public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addComponentInstancePropertiesToComponent(Component containerComponent, Map<String, List<ComponentInstanceProperty>> instProperties, String componentId) {
1226
1227                 if (instProperties != null) {
1228
1229                         for (Entry<String, List<ComponentInstanceProperty>> entry : instProperties.entrySet()) {
1230                                 List<ComponentInstanceProperty> props = entry.getValue();
1231                                 String componentInstanseId = entry.getKey();
1232                                 List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(componentInstanseId);
1233                                 if (props != null && !props.isEmpty()) {
1234                                         for (ComponentInstanceProperty property : props) {
1235                                                 Optional<ComponentInstanceProperty> instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
1236                                                 if (instanceProperty.isPresent()) {
1237                                                         updateComponentInstanceProperty(containerComponent, componentInstanseId, property);
1238                                                 } else {
1239                                                         addComponentInstanceProperty(containerComponent, componentInstanseId, property);
1240                                                 }
1241
1242                                         }
1243                                 }
1244                         }
1245                 }
1246
1247                 return Either.left(instProperties);
1248
1249         }
1250
1251         public StorageOperationStatus associateDeploymentArtifactsToInstances(Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts, String componentId, User user) {
1252
1253                 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1254                 if (getVertexEither.isRight()) {
1255                         log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
1256                         return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
1257
1258                 }
1259
1260                 GraphVertex vertex = getVertexEither.left().value();
1261                 Map<String, MapArtifactDataDefinition> instArtMap = new HashMap<>();
1262                 if (instDeploymentArtifacts != null) {
1263
1264                         MapArtifactDataDefinition artifactsMap;
1265                         for (Entry<String, Map<String, ArtifactDefinition>> entry : instDeploymentArtifacts.entrySet()) {
1266                                 Map<String, ArtifactDefinition> artList = entry.getValue();
1267                                 Map<String, ArtifactDataDefinition> artifacts = artList.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
1268                                 artifactsMap = nodeTemplateOperation.prepareInstDeploymentArtifactPerInstance(artifacts, entry.getKey(), user, NodeTemplateOperation.HEAT_VF_ENV_NAME);
1269
1270                                 instArtMap.put(entry.getKey(), artifactsMap);
1271                         }
1272                 }
1273
1274                 return topologyTemplateOperation.associateInstDeploymentArtifactsToComponent(vertex, instArtMap);
1275
1276         }
1277
1278         public StorageOperationStatus associateArtifactsToInstances(Map<String, Map<String, ArtifactDefinition>> instArtifacts, String componentId, User user) {
1279
1280                 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1281                 if (getVertexEither.isRight()) {
1282                         log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
1283                         return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
1284
1285                 }
1286
1287                 GraphVertex vertex = getVertexEither.left().value();
1288                 Map<String, MapArtifactDataDefinition> instArtMap = new HashMap<>();
1289                 if (instArtifacts != null) {
1290
1291                         MapArtifactDataDefinition artifactsMap;
1292                         for (Entry<String, Map<String, ArtifactDefinition>> entry : instArtifacts.entrySet()) {
1293                                 Map<String, ArtifactDefinition> artList = entry.getValue();
1294                                 Map<String, ArtifactDataDefinition> artifacts = artList.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
1295                                 artifactsMap = new MapArtifactDataDefinition(artifacts);
1296
1297                                 instArtMap.put(entry.getKey(), artifactsMap);
1298                         }
1299                 }
1300
1301                 return topologyTemplateOperation.associateInstArtifactsToComponent(vertex, instArtMap);
1302
1303         }
1304
1305         public StorageOperationStatus associateInstAttributeToComponentToInstances(Map<String, List<PropertyDefinition>> instArttributes, String componentId) {
1306
1307                 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1308                 if (getVertexEither.isRight()) {
1309                         log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
1310                         return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
1311
1312                 }
1313
1314                 GraphVertex vertex = getVertexEither.left().value();
1315                 Map<String, MapPropertiesDataDefinition> instAttr = new HashMap<>();
1316                 if (instArttributes != null) {
1317
1318                         MapPropertiesDataDefinition attributesMap;
1319                         for (Entry<String, List<PropertyDefinition>> entry : instArttributes.entrySet()) {
1320                                 attributesMap = new MapPropertiesDataDefinition();
1321                                 attributesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e)));
1322                                 instAttr.put(entry.getKey(), attributesMap);
1323                         }
1324                 }
1325
1326                 return topologyTemplateOperation.associateInstAttributeToComponent(vertex, instAttr);
1327
1328         }
1329         // endregion
1330
1331         public StorageOperationStatus associateCalculatedCapReq(Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties, Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instReg, String componentId) {
1332                 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
1333                 if (getVertexEither.isRight()) {
1334                         log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
1335                         return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
1336
1337                 }
1338
1339                 GraphVertex vertex = getVertexEither.left().value();
1340
1341                 Map<String, MapListRequirementDataDefinition> calcRequirements = new HashMap<>();
1342
1343                 Map<String, MapListCapabiltyDataDefinition> calcCapabilty = new HashMap<>();
1344                 Map<String, MapCapabiltyProperty> calculatedCapabilitiesProperties = new HashMap<>();
1345                 ;
1346                 if (instCapabilties != null) {
1347                         for (Entry<ComponentInstance, Map<String, List<CapabilityDefinition>>> entry : instCapabilties.entrySet()) {
1348
1349                                 Map<String, List<CapabilityDefinition>> caps = entry.getValue();
1350                                 Map<String, ListCapabilityDataDefinition> mapToscaDataDefinition = new HashMap<>();
1351                                 for (Entry<String, List<CapabilityDefinition>> instCapability : caps.entrySet()) {
1352                                         mapToscaDataDefinition.put(instCapability.getKey(), new ListCapabilityDataDefinition(instCapability.getValue().stream().map(iCap -> new CapabilityDataDefinition(iCap)).collect(Collectors.toList())));
1353                                 }
1354
1355                                 ComponentInstanceDataDefinition componentInstance = new ComponentInstanceDataDefinition(entry.getKey());
1356                                 MapListCapabiltyDataDefinition capMap = nodeTemplateOperation.prepareCalculatedCapabiltyForNodeType(mapToscaDataDefinition, componentInstance);
1357
1358                                 MapCapabiltyProperty mapCapabiltyProperty = ModelConverter.convertToMapOfMapCapabiltyProperties(caps, componentInstance.getUniqueId(), true);
1359
1360                                 calcCapabilty.put(entry.getKey().getUniqueId(), capMap);
1361                                 calculatedCapabilitiesProperties.put(entry.getKey().getUniqueId(), mapCapabiltyProperty);
1362                         }
1363                 }
1364
1365                 if (instReg != null) {
1366                         for (Entry<ComponentInstance, Map<String, List<RequirementDefinition>>> entry : instReg.entrySet()) {
1367
1368                                 Map<String, List<RequirementDefinition>> req = entry.getValue();
1369                                 Map<String, ListRequirementDataDefinition> mapToscaDataDefinition = new HashMap<>();
1370                                 for (Entry<String, List<RequirementDefinition>> instReq : req.entrySet()) {
1371                                         mapToscaDataDefinition.put(instReq.getKey(), new ListRequirementDataDefinition(instReq.getValue().stream().map(iCap -> new RequirementDataDefinition(iCap)).collect(Collectors.toList())));
1372                                 }
1373
1374                                 MapListRequirementDataDefinition capMap = nodeTemplateOperation.prepareCalculatedRequirementForNodeType(mapToscaDataDefinition, new ComponentInstanceDataDefinition(entry.getKey()));
1375
1376                                 calcRequirements.put(entry.getKey().getUniqueId(), capMap);
1377                         }
1378                 }
1379
1380                 StorageOperationStatus status = topologyTemplateOperation.associateCalcCapReqToComponent(vertex, calcRequirements, calcCapabilty, calculatedCapabilitiesProperties);
1381
1382                 return status;
1383         }
1384
1385         private Either<List<Service>, StorageOperationStatus> getLatestVersionNonCheckoutServicesMetadataOnly(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps) {
1386                 List<Service> services = new ArrayList<>();
1387                 List<LifecycleStateEnum> states = new ArrayList<>();
1388                 // include props
1389                 hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
1390                 hasProps.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1391
1392                 // exclude props
1393                 states.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
1394                 hasNotProps.put(GraphPropertyEnum.STATE, states);
1395                 hasNotProps.put(GraphPropertyEnum.IS_DELETED, true);
1396                 return fetchServicesByCriteria(services, hasProps, hasNotProps);
1397         }
1398
1399         private Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractToscaElementsMetadataOnly(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType, VertexTypeEnum vertexType) {
1400                 List<Service> services = null;
1401                 Map<GraphPropertyEnum, Object> hasProps = new EnumMap<>(GraphPropertyEnum.class);
1402                 Map<GraphPropertyEnum, Object> hasNotProps = new EnumMap<>(GraphPropertyEnum.class);
1403                 fillPropsMap(hasProps, hasNotProps, internalComponentType, componentTypeEnum, isAbstract, vertexType);
1404                 Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(vertexType, hasProps, hasNotProps, JsonParseFlagEnum.ParseMetadata);
1405                 if (getRes.isRight()) {
1406                         if (getRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
1407                                 return Either.left(new ArrayList<>());
1408                         } else {
1409                                 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
1410                         }
1411                 } else {
1412                         // region -> Fetch non checked-out services
1413                         if (internalComponentType != null && internalComponentType.toLowerCase().trim().equals("service") && VertexTypeEnum.NODE_TYPE == vertexType) { // and NODE_TYPE==vertextype
1414                                 Either<List<Service>, StorageOperationStatus> result = getLatestVersionNonCheckoutServicesMetadataOnly(new EnumMap<>(GraphPropertyEnum.class), new EnumMap<>(GraphPropertyEnum.class));
1415                                 if (result.isRight()) {
1416                                         log.debug("Failed to fetch services for");
1417                                         return Either.right(result.right().value());
1418                                 }
1419                                 services = result.left().value();
1420                                 if (CollectionUtils.isEmpty(services) && log.isTraceEnabled())
1421                                         log.trace("No relevant services available");
1422                         }
1423                         // endregion
1424                         List<Component> nonAbstractLatestComponents = new ArrayList<>();
1425                         ComponentParametersView params = new ComponentParametersView(true);
1426                         params.setIgnoreAllVersions(false);
1427                         for (GraphVertex vertexComponent : getRes.left().value()) {
1428                                 Either<ToscaElement, StorageOperationStatus> componentRes = topologyTemplateOperation.getLightComponent(vertexComponent, componentTypeEnum, params);
1429                                 if (componentRes.isRight()) {
1430                                         log.debug("Failed to fetch ligth element for {} error {}", vertexComponent.getUniqueId(), componentRes.right().value());
1431                                         return Either.right(componentRes.right().value());
1432                                 } else {
1433                                         Component component = ModelConverter.convertFromToscaElement(componentRes.left().value());
1434                                         nonAbstractLatestComponents.add(component);
1435                                 }
1436                         }
1437                         if (CollectionUtils.isNotEmpty(services))
1438                                 nonAbstractLatestComponents.addAll(services);
1439                         return Either.left(nonAbstractLatestComponents);
1440                 }
1441         }
1442
1443         public Either<ComponentMetadataData, StorageOperationStatus> getLatestComponentMetadataByUuid(String componentUuid, JsonParseFlagEnum parseFlag, Boolean isHighest) {
1444
1445                 Either<ComponentMetadataData, StorageOperationStatus> result;
1446
1447                 Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
1448
1449                 hasProperties.put(GraphPropertyEnum.UUID, componentUuid);
1450                 if (isHighest != null) {
1451                         hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, isHighest.booleanValue());
1452                 }
1453
1454                 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
1455                 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
1456
1457                 Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(null, hasProperties, propertiesNotToMatch, parseFlag);
1458                 if (getRes.isRight()) {
1459                         result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
1460                 } else {
1461                         List<ComponentMetadataData> latestVersionList = getRes.left().value().stream().map(ModelConverter::convertToComponentMetadata).collect(Collectors.toList());
1462                         ComponentMetadataData latestVersion = latestVersionList.size() == 1 ? latestVersionList.get(0)
1463                                         : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getMetadataDataDefinition().getVersion()), Double.parseDouble(c2.getMetadataDataDefinition().getVersion()))).get();
1464                         result = Either.left(latestVersion);
1465                 }
1466                 return result;
1467         }
1468
1469         public Either<ComponentMetadataData, StorageOperationStatus> getComponentMetadata(String componentId) {
1470
1471                 Either<ComponentMetadataData, StorageOperationStatus> result;
1472                 Either<GraphVertex, TitanOperationStatus> getRes = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata);
1473                 if (getRes.isRight()) {
1474                         result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
1475                 } else {
1476                         ComponentMetadataData componentMetadata = ModelConverter.convertToComponentMetadata(getRes.left().value());
1477                         result = Either.left(componentMetadata);
1478                 }
1479                 return result;
1480         }
1481
1482         public Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractComponents(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType, List<String> componentUids) {
1483
1484                 Either<List<Component>, StorageOperationStatus> result = null;
1485                 List<Component> components = new ArrayList<>();
1486                 if (componentUids == null) {
1487                         Either<List<String>, StorageOperationStatus> componentUidsRes = getComponentUids(isAbstract, isHighest, componentTypeEnum, internalComponentType, componentUids);
1488                         if (componentUidsRes.isRight()) {
1489                                 result = Either.right(componentUidsRes.right().value());
1490                         } else {
1491                                 componentUids = componentUidsRes.left().value();
1492                         }
1493                 }
1494                 if (!componentUids.isEmpty()) {
1495                         for (String componentUid : componentUids) {
1496                                 ComponentParametersView componentParametersView = buildComponentViewForNotAbstract();
1497                                 if (internalComponentType != null && "vl".equalsIgnoreCase(internalComponentType)) {
1498                                         componentParametersView.setIgnoreCapabilities(false);
1499                                         componentParametersView.setIgnoreRequirements(false);
1500                                 }
1501                                 Either<ToscaElement, StorageOperationStatus> getToscaElementRes = nodeTemplateOperation.getToscaElementOperation(componentTypeEnum).getLightComponent(componentUid, componentTypeEnum, componentParametersView);
1502                                 if (getToscaElementRes.isRight()) {
1503                                         if (log.isDebugEnabled())
1504                                                 log.debug("Failed to fetch resource for error is {}", getToscaElementRes.right().value());
1505                                         result = Either.right(getToscaElementRes.right().value());
1506                                         break;
1507                                 }
1508                                 Component component = ModelConverter.convertFromToscaElement(getToscaElementRes.left().value());
1509                                 component.setContactId(null);
1510                                 component.setCreationDate(null);
1511                                 component.setCreatorUserId(null);
1512                                 component.setCreatorFullName(null);
1513                                 component.setLastUpdateDate(null);
1514                                 component.setLastUpdaterUserId(null);
1515                                 component.setLastUpdaterFullName(null);
1516                                 component.setNormalizedName(null);
1517                                 components.add(component);
1518                         }
1519                 }
1520                 if (result == null) {
1521                         result = Either.left(components);
1522                 }
1523                 return result;
1524         }
1525
1526         private Either<List<String>, StorageOperationStatus> getComponentUids(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType, List<String> componentUids) {
1527
1528                 Either<List<String>, StorageOperationStatus> result = null;
1529                 Either<List<Component>, StorageOperationStatus> getToscaElementsRes = getLatestVersionNotAbstractMetadataOnly(isAbstract, isHighest, componentTypeEnum, internalComponentType);
1530                 if (getToscaElementsRes.isRight()) {
1531                         result = Either.right(getToscaElementsRes.right().value());
1532                 } else {
1533                         List<Component> collection = getToscaElementsRes.left().value();
1534                         if (collection == null) {
1535                                 componentUids = new ArrayList<>();
1536                         } else {
1537                                 componentUids = collection.stream().map(p -> p.getUniqueId()).collect(Collectors.toList());
1538                         }
1539                 }
1540                 if (result == null) {
1541                         result = Either.left(componentUids);
1542                 }
1543                 return result;
1544         }
1545
1546         private ComponentParametersView buildComponentViewForNotAbstract() {
1547                 ComponentParametersView componentParametersView = new ComponentParametersView();
1548                 componentParametersView.disableAll();
1549                 componentParametersView.setIgnoreCategories(false);
1550                 componentParametersView.setIgnoreAllVersions(false);
1551                 return componentParametersView;
1552         }
1553
1554         public Either<Boolean, StorageOperationStatus> validateComponentNameExists(String name, ResourceTypeEnum resourceType, ComponentTypeEnum componentType) {
1555                 Either<Boolean, StorageOperationStatus> result = validateComponentNameUniqueness(name, resourceType, componentType);
1556                 if (result.isLeft()) {
1557                         result = Either.left(!result.left().value());
1558                 }
1559                 return result;
1560         }
1561
1562         public Either<Boolean, StorageOperationStatus> validateComponentNameUniqueness(String name, ResourceTypeEnum resourceType, ComponentTypeEnum componentType) {
1563                 VertexTypeEnum vertexType = ModelConverter.isAtomicComponent(resourceType) ? VertexTypeEnum.NODE_TYPE : VertexTypeEnum.TOPOLOGY_TEMPLATE;
1564                 String normalizedName = ValidationUtils.normaliseComponentName(name);
1565                 Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
1566                 properties.put(GraphPropertyEnum.NORMALIZED_NAME, normalizedName);
1567                 properties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
1568
1569                 Either<List<GraphVertex>, TitanOperationStatus> vertexEither = titanDao.getByCriteria(vertexType, properties, JsonParseFlagEnum.NoParse);
1570                 if (vertexEither.isRight() && vertexEither.right().value() != TitanOperationStatus.NOT_FOUND) {
1571                         log.debug("failed to get vertex from graph with property normalizedName: {}", normalizedName);
1572                         return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexEither.right().value()));
1573                 }
1574                 List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
1575                 if (vertexList != null && !vertexList.isEmpty()) {
1576                         return Either.left(false);
1577                 } else {
1578                         return Either.left(true);
1579                 }
1580         }
1581
1582         private void fillNodeTypePropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, String internalComponentType) {
1583                 switch (internalComponentType.toLowerCase()) {
1584                 case "vf":
1585                 case "cvfc":
1586                         hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, Arrays.asList(ResourceTypeEnum.VFCMT.name(), ResourceTypeEnum.Configuration.name()));
1587                         break;
1588                 case "service":
1589                 case "pnf":
1590                 case "cr":
1591                         hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, Arrays.asList(ResourceTypeEnum.VFC.name(), ResourceTypeEnum.VFCMT.name()));
1592                         break;
1593                 case "vl":
1594                         hasProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VL.name());
1595                         break;
1596                 default:
1597                         break;
1598                 }
1599         }
1600
1601         private void fillTopologyTemplatePropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, ComponentTypeEnum componentTypeEnum, String internalComponentType) {
1602                 switch (componentTypeEnum) {
1603                 case RESOURCE:
1604                         hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
1605                         break;
1606                 case SERVICE:
1607                         hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
1608                         break;
1609                 default:
1610                         break;
1611                 }
1612                 switch (internalComponentType.toLowerCase()) {
1613                 case "vf":
1614                 case "cvfc":
1615                         hasProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.CVFC.name());
1616                         break;
1617                 case "service":
1618                         hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.CVFC.name());
1619                         break;
1620                 default:
1621                         break;
1622                 }
1623         }
1624
1625         private void fillPropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, String internalComponentType, ComponentTypeEnum componentTypeEnum, boolean isAbstract, VertexTypeEnum internalVertexType) {
1626                 hasNotProps.put(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name());
1627
1628                 hasNotProps.put(GraphPropertyEnum.IS_DELETED, true);
1629                 hasProps.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1630                 if (VertexTypeEnum.NODE_TYPE == internalVertexType) {
1631                         hasProps.put(GraphPropertyEnum.IS_ABSTRACT, isAbstract);
1632                         if (internalComponentType != null) {
1633                                 fillNodeTypePropsMap(hasProps, hasNotProps, internalComponentType);
1634                         }
1635                 } else {
1636                         fillTopologyTemplatePropsMap(hasProps, hasNotProps, componentTypeEnum, internalComponentType);
1637                 }
1638         }
1639
1640         private List<VertexTypeEnum> getInternalVertexTypes(ComponentTypeEnum componentTypeEnum, String internalComponentType) {
1641                 List<VertexTypeEnum> internalVertexTypes = new ArrayList<>();
1642                 if (ComponentTypeEnum.RESOURCE == componentTypeEnum) {
1643                         internalVertexTypes.add(VertexTypeEnum.NODE_TYPE);
1644                 }
1645                 if (ComponentTypeEnum.SERVICE == componentTypeEnum || "service".equalsIgnoreCase(internalComponentType) || "vf".equalsIgnoreCase(internalComponentType)) {
1646                         internalVertexTypes.add(VertexTypeEnum.TOPOLOGY_TEMPLATE);
1647                 }
1648                 return internalVertexTypes;
1649         }
1650
1651         public Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractMetadataOnly(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType) {
1652                 List<VertexTypeEnum> internalVertexTypes = getInternalVertexTypes(componentTypeEnum, internalComponentType);
1653                 List<Component> result = new ArrayList<>();
1654                 for (VertexTypeEnum vertexType : internalVertexTypes) {
1655                         Either<List<Component>, StorageOperationStatus> listByVertexType = getLatestVersionNotAbstractToscaElementsMetadataOnly(isAbstract, isHighest, componentTypeEnum, internalComponentType, vertexType);
1656                         if (listByVertexType.isRight()) {
1657                                 return listByVertexType;
1658                         }
1659                         result.addAll(listByVertexType.left().value());
1660                 }
1661                 return Either.left(result);
1662
1663         }
1664
1665         private Either<List<Component>, StorageOperationStatus> getLatestComponentListByUuid(String componentUuid, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
1666                 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1667                 if (additionalPropertiesToMatch != null) {
1668                         propertiesToMatch.putAll(additionalPropertiesToMatch);
1669                 }
1670                 propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1671                 Either<List<Component>, StorageOperationStatus> componentListByUuid = getComponentListByUuid(componentUuid, propertiesToMatch);
1672                 return componentListByUuid;
1673         }
1674
1675         public Either<Component, StorageOperationStatus> getComponentByUuidAndVersion(String componentUuid, String version) {
1676                 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1677
1678                 propertiesToMatch.put(GraphPropertyEnum.UUID, componentUuid);
1679                 propertiesToMatch.put(GraphPropertyEnum.VERSION, version);
1680
1681                 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
1682                 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
1683                 Either<List<GraphVertex>, TitanOperationStatus> vertexEither = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
1684                 if (vertexEither.isRight()) {
1685                         return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexEither.right().value()));
1686                 }
1687
1688                 List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
1689                 if (vertexList == null || vertexList.isEmpty() || vertexList.size() > 1) {
1690                         return Either.right(StorageOperationStatus.NOT_FOUND);
1691                 }
1692
1693                 return getToscaElementByOperation(vertexList.get(0));
1694         }
1695
1696         public Either<List<Component>, StorageOperationStatus> getComponentListByUuid(String componentUuid, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
1697
1698                 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1699
1700                 if (additionalPropertiesToMatch != null) {
1701                         propertiesToMatch.putAll(additionalPropertiesToMatch);
1702                 }
1703
1704                 propertiesToMatch.put(GraphPropertyEnum.UUID, componentUuid);
1705
1706                 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
1707                 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
1708
1709                 Either<List<GraphVertex>, TitanOperationStatus> vertexEither = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
1710
1711                 if (vertexEither.isRight()) {
1712                         log.debug("Couldn't fetch metadata for component with type {} and uuid {}, error: {}", componentUuid, vertexEither.right().value());
1713                         return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexEither.right().value()));
1714                 }
1715                 List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
1716
1717                 if (vertexList == null || vertexList.isEmpty()) {
1718                         log.debug("Component with uuid {} was not found", componentUuid);
1719                         return Either.right(StorageOperationStatus.NOT_FOUND);
1720                 }
1721
1722                 ArrayList<Component> latestComponents = new ArrayList<>();
1723                 for (GraphVertex vertex : vertexList) {
1724                         Either<Component, StorageOperationStatus> toscaElementByOperation = getToscaElementByOperation(vertex);
1725
1726                         if (toscaElementByOperation.isRight()) {
1727                                 log.debug("Could not fetch the following Component by UUID {}", vertex.getUniqueId());
1728                                 return Either.right(toscaElementByOperation.right().value());
1729                         }
1730
1731                         latestComponents.add(toscaElementByOperation.left().value());
1732                 }
1733
1734                 if (latestComponents.size() > 1) {
1735                         for (Component component : latestComponents) {
1736                                 if (component.isHighestVersion()) {
1737                                         LinkedList<Component> highestComponent = new LinkedList<>();
1738                                         highestComponent.add(component);
1739                                         return Either.left(highestComponent);
1740                                 }
1741                         }
1742                 }
1743
1744                 return Either.left(latestComponents);
1745         }
1746
1747         public Either<Component, StorageOperationStatus> getLatestServiceByUuid(String serviceUuid) {
1748                 Map<GraphPropertyEnum, Object> propertiesToMatch = new HashMap<>();
1749                 propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
1750                 return getLatestComponentByUuid(serviceUuid, propertiesToMatch);
1751         }
1752
1753         public Either<Component, StorageOperationStatus> getLatestComponentByUuid(String componentUuid) {
1754                 return getLatestComponentByUuid(componentUuid, null);
1755         }
1756
1757         public Either<Component, StorageOperationStatus> getLatestComponentByUuid(String componentUuid, Map<GraphPropertyEnum, Object> propertiesToMatch) {
1758
1759                 Either<List<Component>, StorageOperationStatus> latestVersionListEither = getLatestComponentListByUuid(componentUuid, propertiesToMatch);
1760
1761                 if (latestVersionListEither.isRight()) {
1762                         return Either.right(latestVersionListEither.right().value());
1763                 }
1764
1765                 List<Component> latestVersionList = latestVersionListEither.left().value();
1766
1767                 if (latestVersionList.isEmpty()) {
1768                         return Either.right(StorageOperationStatus.NOT_FOUND);
1769                 }
1770                 Component component = latestVersionList.size() == 1 ? latestVersionList.get(0) : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getVersion()), Double.parseDouble(c2.getVersion()))).get();
1771
1772                 return Either.left(component);
1773         }
1774
1775         public Either<List<Resource>, StorageOperationStatus> getAllCertifiedResources(boolean isAbstract, Boolean isHighest) {
1776
1777                 List<Resource> resources = new ArrayList<>();
1778                 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
1779                 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
1780
1781                 propertiesToMatch.put(GraphPropertyEnum.IS_ABSTRACT, isAbstract);
1782                 if (isHighest != null) {
1783                         propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, isHighest.booleanValue());
1784                 }
1785                 propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
1786                 propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
1787                 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
1788
1789                 Either<List<GraphVertex>, TitanOperationStatus> getResourcesRes = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
1790
1791                 if (getResourcesRes.isRight()) {
1792                         log.debug("Failed to fetch all certified resources. Status is {}", getResourcesRes.right().value());
1793                         return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getResourcesRes.right().value()));
1794                 }
1795                 List<GraphVertex> resourceVerticies = getResourcesRes.left().value();
1796                 for (GraphVertex resourceV : resourceVerticies) {
1797                         Either<Resource, StorageOperationStatus> getResourceRes = getToscaElement(resourceV);
1798                         if (getResourceRes.isRight()) {
1799                                 return Either.right(getResourceRes.right().value());
1800                         }
1801                         resources.add(getResourceRes.left().value());
1802                 }
1803                 return Either.left(resources);
1804         }
1805
1806         public <T extends Component> Either<T, StorageOperationStatus> getLatestByNameAndVersion(String name, String version, JsonParseFlagEnum parseFlag) {
1807                 Either<T, StorageOperationStatus> result;
1808
1809                 Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
1810                 Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class);
1811
1812                 hasProperties.put(GraphPropertyEnum.NAME, name);
1813                 hasProperties.put(GraphPropertyEnum.VERSION, version);
1814                 hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1815
1816                 hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true);
1817
1818                 Either<List<GraphVertex>, TitanOperationStatus> getResourceRes = titanDao.getByCriteria(null, hasProperties, hasNotProperties, parseFlag);
1819                 if (getResourceRes.isRight()) {
1820                         TitanOperationStatus status = getResourceRes.right().value();
1821                         log.debug("failed to find resource with name {}, version {}. Status is {} ", name, version, status);
1822                         result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1823                         return result;
1824                 }
1825                 return getToscaElementByOperation(getResourceRes.left().value().get(0));
1826         }
1827
1828         public Either<Resource, StorageOperationStatus> getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID, String systemName) {
1829                 return getLatestComponentByCsarOrName(componentType, csarUUID, systemName, false, JsonParseFlagEnum.ParseAll);
1830         }
1831
1832         public Either<Resource, StorageOperationStatus> getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID, String systemName, boolean allowDeleted, JsonParseFlagEnum parseFlag) {
1833                 Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
1834                 props.put(GraphPropertyEnum.CSAR_UUID, csarUUID);
1835                 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1836                 if (componentType != null) {
1837                         props.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
1838                 }
1839                 Map<GraphPropertyEnum, Object> propsHasNot = new EnumMap<>(GraphPropertyEnum.class);
1840                 propsHasNot.put(GraphPropertyEnum.IS_DELETED, true);
1841
1842                 GraphVertex resourceMetadataData = null;
1843                 List<GraphVertex> resourceMetadataDataList = null;
1844                 Either<List<GraphVertex>, TitanOperationStatus> byCsar = titanDao.getByCriteria(null, props, propsHasNot, JsonParseFlagEnum.ParseMetadata);
1845                 if (byCsar.isRight()) {
1846                         if (TitanOperationStatus.NOT_FOUND == byCsar.right().value()) {
1847                                 // Fix Defect DE256036
1848                                 if (StringUtils.isEmpty(systemName)) {
1849                                         return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.NOT_FOUND));
1850                                 }
1851
1852                                 props.clear();
1853                                 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1854                                 props.put(GraphPropertyEnum.SYSTEM_NAME, systemName);
1855                                 Either<List<GraphVertex>, TitanOperationStatus> bySystemname = titanDao.getByCriteria(null, props, JsonParseFlagEnum.ParseMetadata);
1856                                 if (bySystemname.isRight()) {
1857                                         log.debug("getLatestResourceByCsarOrName - Failed to find by system name {}  error {} ", systemName, bySystemname.right().value());
1858                                         return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(bySystemname.right().value()));
1859                                 }
1860                                 if (bySystemname.left().value().size() > 2) {
1861                                         log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) must return only 2 latest version, but was returned - {}", bySystemname.left().value().size());
1862                                         return Either.right(StorageOperationStatus.GENERAL_ERROR);
1863                                 }
1864                                 resourceMetadataDataList = bySystemname.left().value();
1865                                 if (resourceMetadataDataList.size() == 1) {
1866                                         resourceMetadataData = resourceMetadataDataList.get(0);
1867                                 } else {
1868                                         for (GraphVertex curResource : resourceMetadataDataList) {
1869                                                 if (!((String) curResource.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals("CERTIFIED")) {
1870                                                         resourceMetadataData = curResource;
1871                                                         break;
1872                                                 }
1873                                         }
1874                                 }
1875                                 if (resourceMetadataData == null) {
1876                                         log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) returned 2 latest CERTIFIED versions");
1877                                         return Either.right(StorageOperationStatus.GENERAL_ERROR);
1878                                 }
1879                                 if (resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID) != null && !((String) resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID)).equals(csarUUID)) {
1880                                         log.debug("getLatestResourceByCsarOrName - same system name {} but different csarUUID. exist {} and new {} ", systemName, resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID), csarUUID);
1881                                         // correct error will be returned from create flow. with all
1882                                         // correct audit records!!!!!
1883                                         return Either.right(StorageOperationStatus.NOT_FOUND);
1884                                 }
1885                                 Either<Resource, StorageOperationStatus> resource = getToscaElement((String) resourceMetadataData.getUniqueId());
1886                                 return resource;
1887                         }
1888                 } else {
1889                         resourceMetadataDataList = byCsar.left().value();
1890                         if (resourceMetadataDataList.size() > 2) {
1891                                 log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) must return only 2 latest version, but was returned - {}", byCsar.left().value().size());
1892                                 return Either.right(StorageOperationStatus.GENERAL_ERROR);
1893                         }
1894                         if (resourceMetadataDataList.size() == 1) {
1895                                 resourceMetadataData = resourceMetadataDataList.get(0);
1896                         } else {
1897                                 for (GraphVertex curResource : resourceMetadataDataList) {
1898                                         if (!((String) curResource.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals("CERTIFIED")) {
1899                                                 resourceMetadataData = curResource;
1900                                                 break;
1901                                         }
1902                                 }
1903                         }
1904                         if (resourceMetadataData == null) {
1905                                 log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) returned 2 latest CERTIFIED versions");
1906                                 return Either.right(StorageOperationStatus.GENERAL_ERROR);
1907                         }
1908                         Either<Resource, StorageOperationStatus> resource = getToscaElement((String) resourceMetadataData.getJsonMetadataField(JsonPresentationFields.UNIQUE_ID), parseFlag);
1909                         return resource;
1910                 }
1911                 return null;
1912         }
1913
1914         public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExtends(String templateNameCurrent, String templateNameExtends) {
1915
1916                 String currentTemplateNameChecked = templateNameExtends;
1917
1918                 while (currentTemplateNameChecked != null && !currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) {
1919                         Either<Resource, StorageOperationStatus> latestByToscaResourceName = getLatestByToscaResourceName(currentTemplateNameChecked);
1920
1921                         if (latestByToscaResourceName.isRight()) {
1922                                 return latestByToscaResourceName.right().value() == StorageOperationStatus.NOT_FOUND ? Either.left(false) : Either.right(latestByToscaResourceName.right().value());
1923                         }
1924
1925                         Resource value = latestByToscaResourceName.left().value();
1926
1927                         if (value.getDerivedFrom() != null) {
1928                                 currentTemplateNameChecked = value.getDerivedFrom().get(0);
1929                         } else {
1930                                 currentTemplateNameChecked = null;
1931                         }
1932                 }
1933
1934                 return (currentTemplateNameChecked != null && currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) ? Either.left(true) : Either.left(false);
1935         }
1936
1937         public Either<List<Component>, StorageOperationStatus> fetchMetaDataByResourceType(String resourceType, ComponentParametersView filterBy) {
1938                 Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
1939                 props.put(GraphPropertyEnum.RESOURCE_TYPE, resourceType);
1940                 props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
1941                 Map<GraphPropertyEnum, Object> propsHasNotToMatch = new HashMap<>();
1942                 propsHasNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
1943                 Either<List<GraphVertex>, TitanOperationStatus> resourcesByTypeEither = titanDao.getByCriteria(null, props, propsHasNotToMatch, JsonParseFlagEnum.ParseMetadata);
1944
1945                 if (resourcesByTypeEither.isRight()) {
1946                         return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resourcesByTypeEither.right().value()));
1947                 }
1948
1949                 List<GraphVertex> vertexList = resourcesByTypeEither.left().value();
1950                 List<Component> components = new ArrayList<>();
1951
1952                 for (GraphVertex vertex : vertexList) {
1953                         components.add(getToscaElementByOperation(vertex, filterBy).left().value());
1954                 }
1955
1956                 return Either.left(components);
1957         }
1958
1959         public void commit() {
1960                 titanDao.commit();
1961         }
1962
1963         public Either<Service, StorageOperationStatus> updateDistributionStatus(Service service, User user, DistributionStatusEnum distributionStatus) {
1964                 Either<GraphVertex, StorageOperationStatus> updateDistributionStatus = topologyTemplateOperation.updateDistributionStatus(service.getUniqueId(), user, distributionStatus);
1965                 if (updateDistributionStatus.isRight()) {
1966                         return Either.right(updateDistributionStatus.right().value());
1967                 }
1968                 GraphVertex serviceV = updateDistributionStatus.left().value();
1969                 service.setDistributionStatus(distributionStatus);
1970                 service.setLastUpdateDate((Long) serviceV.getJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE));
1971                 return Either.left(service);
1972         }
1973
1974         public Either<ComponentMetadataData, StorageOperationStatus> updateComponentLastUpdateDateOnGraph(Component component, Long modificationTime) {
1975
1976                 Either<ComponentMetadataData, StorageOperationStatus> result = null;
1977                 GraphVertex serviceVertex;
1978                 Either<GraphVertex, TitanOperationStatus> updateRes = null;
1979                 Either<GraphVertex, TitanOperationStatus> getRes = titanDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.ParseMetadata);
1980                 if (getRes.isRight()) {
1981                         TitanOperationStatus status = getRes.right().value();
1982                         log.error("Failed to fetch component {}. status is {}", component.getUniqueId(), status);
1983                         result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1984                 }
1985                 if (result == null) {
1986                         serviceVertex = getRes.left().value();
1987                         long lastUpdateDate = System.currentTimeMillis();
1988                         serviceVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, lastUpdateDate);
1989                         component.setLastUpdateDate(lastUpdateDate);
1990                         updateRes = titanDao.updateVertex(serviceVertex);
1991                         if (updateRes.isRight()) {
1992                                 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateRes.right().value()));
1993                         }
1994                 }
1995                 if (result == null) {
1996                         result = Either.left(ModelConverter.convertToComponentMetadata(updateRes.left().value()));
1997                 }
1998                 return result;
1999         }
2000
2001         public TitanDao getTitanDao() {
2002                 return titanDao;
2003         }
2004
2005         public Either<List<Service>, StorageOperationStatus> getCertifiedServicesWithDistStatus(Set<DistributionStatusEnum> distStatus) {
2006                 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
2007                 propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
2008
2009                 return getServicesWithDistStatus(distStatus, propertiesToMatch);
2010         }
2011
2012         public Either<List<Service>, StorageOperationStatus> getServicesWithDistStatus(Set<DistributionStatusEnum> distStatus, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
2013
2014                 List<Service> servicesAll = new ArrayList<>();
2015
2016                 Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
2017                 Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
2018
2019                 if (additionalPropertiesToMatch != null && !additionalPropertiesToMatch.isEmpty()) {
2020                         propertiesToMatch.putAll(additionalPropertiesToMatch);
2021                 }
2022
2023                 propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
2024
2025                 propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
2026
2027                 if (distStatus != null && !distStatus.isEmpty()) {
2028                         for (DistributionStatusEnum state : distStatus) {
2029                                 propertiesToMatch.put(GraphPropertyEnum.DISTRIBUTION_STATUS, state.name());
2030                                 Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria = fetchServicesByCriteria(servicesAll, propertiesToMatch, propertiesNotToMatch);
2031                                 if (fetchServicesByCriteria.isRight()) {
2032                                         return fetchServicesByCriteria;
2033                                 } else {
2034                                         servicesAll = fetchServicesByCriteria.left().value();
2035                                 }
2036                         }
2037                         return Either.left(servicesAll);
2038                 } else {
2039                         return fetchServicesByCriteria(servicesAll, propertiesToMatch, propertiesNotToMatch);
2040                 }
2041         }
2042
2043         private Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria(List<Service> servicesAll, Map<GraphPropertyEnum, Object> propertiesToMatch, Map<GraphPropertyEnum, Object> propertiesNotToMatch) {
2044                 Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
2045                 if (getRes.isRight()) {
2046                         if (getRes.right().value() != TitanOperationStatus.NOT_FOUND) {
2047                                 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified services by match properties {} not match properties {} . Status is {}. ", propertiesToMatch, propertiesNotToMatch, getRes.right().value());
2048                                 return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
2049                         }
2050                 } else {
2051                         for (GraphVertex vertex : getRes.left().value()) {
2052                                 // Either<Component, StorageOperationStatus> getServiceRes = getToscaElementByOperation(vertex);
2053                                 Either<ToscaElement, StorageOperationStatus> getServiceRes = topologyTemplateOperation.getLightComponent(vertex, ComponentTypeEnum.SERVICE, new ComponentParametersView(true));
2054
2055                                 if (getServiceRes.isRight()) {
2056                                         CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified service {}. Status is {}. ", vertex.getJsonMetadataField(JsonPresentationFields.NAME), getServiceRes.right().value());
2057                                         return Either.right(getServiceRes.right().value());
2058                                 } else {
2059                                         servicesAll.add(ModelConverter.convertFromToscaElement(getServiceRes.left().value()));
2060                                 }
2061                         }
2062                 }
2063                 return Either.left(servicesAll);
2064         }
2065
2066         public void rollback() {
2067                 titanDao.rollback();
2068         }
2069
2070         public StorageOperationStatus addDeploymentArtifactsToInstance(String componentId, ComponentInstance componentInstance, Map<String, ArtifactDefinition> finalDeploymentArtifacts) {
2071                 Map<String, ArtifactDataDefinition> instDeplArtifacts = finalDeploymentArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
2072
2073                 return nodeTemplateOperation.addDeploymentArtifactsToInstance(componentId, componentInstance.getUniqueId(), instDeplArtifacts);
2074         }
2075
2076         public StorageOperationStatus addInformationalArtifactsToInstance(String componentId, ComponentInstance componentInstance, Map<String, ArtifactDefinition> artifacts) {
2077                 StorageOperationStatus status = StorageOperationStatus.OK;
2078                 if (MapUtils.isNotEmpty(artifacts)) {
2079                         Map<String, ArtifactDataDefinition> instDeplArtifacts = artifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
2080                         status = nodeTemplateOperation.addInformationalArtifactsToInstance(componentId, componentInstance.getUniqueId(), instDeplArtifacts);
2081                 }
2082                 return status;
2083         }
2084
2085         public StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId) {
2086                 return nodeTemplateOperation.generateCustomizationUUIDOnInstance(componentId, instanceId);
2087         }
2088
2089         public StorageOperationStatus generateCustomizationUUIDOnInstanceGroup(String componentId, String instanceId, List<String> groupInstances) {
2090                 return nodeTemplateOperation.generateCustomizationUUIDOnInstanceGroup(componentId, instanceId, groupInstances);
2091         }
2092
2093         /*
2094         * adds property to a resource
2095         * @warn this method has SIDE EFFECT on ownerId ,use it with caution
2096         * */
2097         public Either<PropertyDefinition, StorageOperationStatus> addPropertyToResource(String propertyName, PropertyDefinition newPropertyDefinition, Resource resource) {
2098
2099                 Either<PropertyDefinition, StorageOperationStatus> result = null;
2100                 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
2101                 newPropertyDefinition.setName(propertyName);
2102                 StorageOperationStatus status = getToscaElementOperation(resource).addToscaDataToToscaElement(resource.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition, JsonPresentationFields.NAME);
2103                 if (status != StorageOperationStatus.OK) {
2104                         CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", propertyName, resource.getName(), status);
2105                         result = Either.right(status);
2106                 }
2107                 if (result == null) {
2108                         ComponentParametersView filter = new ComponentParametersView(true);
2109                         filter.setIgnoreProperties(false);
2110                         getUpdatedComponentRes = getToscaElement(resource.getUniqueId(), filter);
2111                         if (getUpdatedComponentRes.isRight()) {
2112                                 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", resource.getUniqueId(), getUpdatedComponentRes.right().value());
2113                                 result = Either.right(status);
2114                         }
2115                 }
2116                 if (result == null) {
2117                         PropertyDefinition newProperty = null;
2118                         List<PropertyDefinition> properties = ((Resource) getUpdatedComponentRes.left().value()).getProperties();
2119                         if (CollectionUtils.isNotEmpty(properties)) {
2120                                 Optional<PropertyDefinition> newPropertyOptional = properties.stream().filter(p -> p.getName().equals(propertyName)).findAny();
2121                                 if (newPropertyOptional.isPresent()) {
2122                                         newProperty = newPropertyOptional.get();
2123                                 }
2124                         }
2125                         if (newProperty == null) {
2126                                 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", propertyName, resource.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2127                                 result = Either.right(StorageOperationStatus.NOT_FOUND);
2128                         } else {
2129                                 result = Either.left(newProperty);
2130                         }
2131                 }
2132                 return result;
2133         }
2134
2135         public StorageOperationStatus deletePropertyOfResource(Resource resource, String propertyName) {
2136                 return getToscaElementOperation(resource).deleteToscaDataElement(resource.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, propertyName, JsonPresentationFields.NAME);
2137         }
2138
2139         public StorageOperationStatus deleteAttributeOfResource(Component component, String attributeName) {
2140                 return getToscaElementOperation(component).deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, attributeName, JsonPresentationFields.NAME);
2141         }
2142
2143         public StorageOperationStatus deleteInputOfResource(Component resource, String inputName) {
2144                 return getToscaElementOperation(resource).deleteToscaDataElement(resource.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputName, JsonPresentationFields.NAME);
2145         }
2146
2147         public Either<PropertyDefinition, StorageOperationStatus> updatePropertyOfResource(Resource resource, PropertyDefinition newPropertyDefinition) {
2148
2149                 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
2150                 Either<PropertyDefinition, StorageOperationStatus> result = null;
2151                 StorageOperationStatus status = getToscaElementOperation(resource).updateToscaDataOfToscaElement(resource.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition, JsonPresentationFields.NAME);
2152                 if (status != StorageOperationStatus.OK) {
2153                         CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", newPropertyDefinition.getName(), resource.getName(), status);
2154                         result = Either.right(status);
2155                 }
2156                 if (result == null) {
2157                         ComponentParametersView filter = new ComponentParametersView(true);
2158                         filter.setIgnoreProperties(false);
2159                         getUpdatedComponentRes = getToscaElement(resource.getUniqueId(), filter);
2160                         if (getUpdatedComponentRes.isRight()) {
2161                                 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", resource.getUniqueId(), getUpdatedComponentRes.right().value());
2162                                 result = Either.right(status);
2163                         }
2164                 }
2165                 if (result == null) {
2166                         Optional<PropertyDefinition> newProperty = ((Resource) getUpdatedComponentRes.left().value()).getProperties().stream().filter(p -> p.getName().equals(newPropertyDefinition.getName())).findAny();
2167                         if (newProperty.isPresent()) {
2168                                 result = Either.left(newProperty.get());
2169                         } else {
2170                                 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", newPropertyDefinition.getName(), resource.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2171                                 result = Either.right(StorageOperationStatus.NOT_FOUND);
2172                         }
2173                 }
2174                 return result;
2175         }
2176
2177         public Either<PropertyDefinition, StorageOperationStatus> addAttributeOfResource(Component component, PropertyDefinition newAttributeDef) {
2178
2179                 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
2180                 Either<PropertyDefinition, StorageOperationStatus> result = null;
2181                 if (newAttributeDef.getUniqueId() == null || newAttributeDef.getUniqueId().isEmpty()) {
2182                         String attUniqueId = UniqueIdBuilder.buildAttributeUid(component.getUniqueId(), newAttributeDef.getName());
2183                         newAttributeDef.setUniqueId(attUniqueId);
2184                 }
2185
2186                 StorageOperationStatus status = getToscaElementOperation(component).addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef, JsonPresentationFields.NAME);
2187                 if (status != StorageOperationStatus.OK) {
2188                         CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", newAttributeDef.getName(), component.getName(), status);
2189                         result = Either.right(status);
2190                 }
2191                 if (result == null) {
2192                         ComponentParametersView filter = new ComponentParametersView(true);
2193                         filter.setIgnoreAttributesFrom(false);
2194                         getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
2195                         if (getUpdatedComponentRes.isRight()) {
2196                                 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value());
2197                                 result = Either.right(status);
2198                         }
2199                 }
2200                 if (result == null) {
2201                         Optional<PropertyDefinition> newAttribute = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream().filter(p -> p.getName().equals(newAttributeDef.getName())).findAny();
2202                         if (newAttribute.isPresent()) {
2203                                 result = Either.left(newAttribute.get());
2204                         } else {
2205                                 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2206                                 result = Either.right(StorageOperationStatus.NOT_FOUND);
2207                         }
2208                 }
2209                 return result;
2210         }
2211
2212         public Either<PropertyDefinition, StorageOperationStatus> updateAttributeOfResource(Component component, PropertyDefinition newAttributeDef) {
2213
2214                 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
2215                 Either<PropertyDefinition, StorageOperationStatus> result = null;
2216                 StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef, JsonPresentationFields.NAME);
2217                 if (status != StorageOperationStatus.OK) {
2218                         CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", newAttributeDef.getName(), component.getName(), status);
2219                         result = Either.right(status);
2220                 }
2221                 if (result == null) {
2222                         ComponentParametersView filter = new ComponentParametersView(true);
2223                         filter.setIgnoreAttributesFrom(false);
2224                         getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
2225                         if (getUpdatedComponentRes.isRight()) {
2226                                 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value());
2227                                 result = Either.right(status);
2228                         }
2229                 }
2230                 if (result == null) {
2231                         Optional<PropertyDefinition> newProperty = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream().filter(p -> p.getName().equals(newAttributeDef.getName())).findAny();
2232                         if (newProperty.isPresent()) {
2233                                 result = Either.left(newProperty.get());
2234                         } else {
2235                                 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2236                                 result = Either.right(StorageOperationStatus.NOT_FOUND);
2237                         }
2238                 }
2239                 return result;
2240         }
2241
2242         public Either<InputDefinition, StorageOperationStatus> updateInputOfComponent(Component component, InputDefinition newInputDefinition) {
2243
2244                 Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
2245                 Either<InputDefinition, StorageOperationStatus> result = null;
2246                 StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, newInputDefinition, JsonPresentationFields.NAME);
2247                 if (status != StorageOperationStatus.OK) {
2248                         CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the input {} to the component {}. Status is {}. ", newInputDefinition.getName(), component.getName(), status);
2249                         result = Either.right(status);
2250                 }
2251                 if (result == null) {
2252                         ComponentParametersView filter = new ComponentParametersView(true);
2253                         filter.setIgnoreInputs(false);
2254                         getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
2255                         if (getUpdatedComponentRes.isRight()) {
2256                                 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value());
2257                                 result = Either.right(status);
2258                         }
2259                 }
2260                 if (result == null) {
2261                         Optional<InputDefinition> updatedInput = getUpdatedComponentRes.left().value().getInputs().stream().filter(p -> p.getName().equals(newInputDefinition.getName())).findAny();
2262                         if (updatedInput.isPresent()) {
2263                                 result = Either.left(updatedInput.get());
2264                         } else {
2265                                 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently updated inputs {} on the resource {}. Status is {}. ", newInputDefinition.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
2266                                 result = Either.right(StorageOperationStatus.NOT_FOUND);
2267                         }
2268                 }
2269                 return result;
2270         }
2271
2272         /**
2273          * method - ename the group instances after referenced container name renamed flow - VF rename -(triggers)-> Group rename
2274          *
2275          * @param containerComponent
2276          *            - container such as service
2277          * @param componentInstance
2278          *            - context component
2279          * @param componentInstanceId
2280          *            - id
2281          *
2282          * @return - successfull/failed status
2283          **/
2284         public Either<StorageOperationStatus, StorageOperationStatus> cleanAndAddGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, String componentInstanceId) {
2285                 String uniqueId = componentInstance.getUniqueId();
2286                 StorageOperationStatus status = nodeTemplateOperation.deleteToscaDataDeepElementsBlockToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS, uniqueId);
2287                 if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
2288                         CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete group instances for container {}. error {] ", componentInstanceId, status);
2289                         return Either.right(status);
2290                 }
2291                 if (componentInstance.getGroupInstances() != null) {
2292                         status = addGroupInstancesToComponentInstance(containerComponent, componentInstance, componentInstance.getGroupInstances());
2293                         if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
2294                                 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add group instances for container {}. error {] ", componentInstanceId, status);
2295                                 return Either.right(status);
2296                         }
2297                 }
2298                 return Either.left(status);
2299         }
2300
2301         public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List<GroupDefinition> groups, Map<String, List<ArtifactDefinition>> groupInstancesArtifacts) {
2302                 return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groups, groupInstancesArtifacts);
2303         }
2304
2305         public Either<List<GroupDefinition>, StorageOperationStatus> updateGroupsOnComponent(Component component, List<GroupDataDefinition> updatedGroups) {
2306                 return groupsOperation.updateGroups(component, updatedGroups);
2307         }
2308
2309         public Either<List<GroupInstance>, StorageOperationStatus> updateGroupInstancesOnComponent(Component component, ComponentTypeEnum componentType, String instanceId, List<GroupInstance> updatedGroupInstances) {
2310                 return groupsOperation.updateGroupInstances(component, instanceId, updatedGroupInstances);
2311         }
2312
2313         public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List<GroupInstance> groupInstances) {
2314                 return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groupInstances);
2315         }
2316
2317         public StorageOperationStatus addDeploymentArtifactsToComponentInstance(Component containerComponent, ComponentInstance componentInstance, Map<String, ArtifactDefinition> deploymentArtifacts) {
2318                 return nodeTemplateOperation.addDeploymentArtifactsToComponentInstance(containerComponent, componentInstance, deploymentArtifacts);
2319         }
2320
2321         public StorageOperationStatus updateComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) {
2322                 return nodeTemplateOperation.updateComponentInstanceProperty(containerComponent, componentInstanceId, property);
2323         }
2324
2325         public StorageOperationStatus updateComponentInstanceProperties(Component containerComponent, String componentInstanceId, List<ComponentInstanceProperty> properties) {
2326                 return nodeTemplateOperation.updateComponentInstanceProperties(containerComponent, componentInstanceId, properties);
2327         }
2328
2329
2330         public StorageOperationStatus addComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) {
2331                 return nodeTemplateOperation.addComponentInstanceProperty(containerComponent, componentInstanceId, property);
2332         }
2333
2334         public StorageOperationStatus updateComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) {
2335                 return nodeTemplateOperation.updateComponentInstanceInput(containerComponent, componentInstanceId, property);
2336         }
2337
2338         public StorageOperationStatus updateComponentInstanceInputs(Component containerComponent, String componentInstanceId, List<ComponentInstanceInput> instanceInputs) {
2339                 return nodeTemplateOperation.updateComponentInstanceInputs(containerComponent, componentInstanceId, instanceInputs);
2340         }
2341
2342         public StorageOperationStatus addComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) {
2343                 return nodeTemplateOperation.addComponentInstanceInput(containerComponent, componentInstanceId, property);
2344         }
2345
2346         public void setNodeTypeOperation(NodeTypeOperation nodeTypeOperation) {
2347                 this.nodeTypeOperation = nodeTypeOperation;
2348         }
2349
2350         public void setTopologyTemplateOperation(TopologyTemplateOperation topologyTemplateOperation) {
2351                 this.topologyTemplateOperation = topologyTemplateOperation;
2352         }
2353
2354         public StorageOperationStatus deleteComponentInstanceInputsFromTopologyTemplate(Component containerComponent, ComponentTypeEnum componentType, List<InputDefinition> inputsToDelete) {
2355                 return topologyTemplateOperation.deleteToscaDataElements(containerComponent.getUniqueId(), EdgeLabelEnum.INPUTS, inputsToDelete.stream().map(i -> i.getName()).collect(Collectors.toList()));
2356         }
2357
2358         public StorageOperationStatus updateComponentInstanceCapabiltyProperty(Component containerComponent, String componentInstanceUniqueId, String capabilityUniqueId, ComponentInstanceProperty property) {
2359                 return nodeTemplateOperation.updateComponentInstanceCapabilityProperty(containerComponent, componentInstanceUniqueId, capabilityUniqueId, property);
2360         }
2361
2362         public StorageOperationStatus updateComponentInstanceCapabilityProperties(Component containerComponent, String componentInstanceUniqueId) {
2363                 return convertComponentInstanceProperties(containerComponent, componentInstanceUniqueId)
2364                                 .map(instanceCapProps -> topologyTemplateOperation.updateComponentInstanceCapabilityProperties(containerComponent, componentInstanceUniqueId, instanceCapProps))
2365                                 .orElse(StorageOperationStatus.NOT_FOUND);
2366         }
2367
2368         public StorageOperationStatus updateComponentCalculatedCapabilitiesProperties(Component containerComponent) {
2369                 Map<String, MapCapabiltyProperty> mapCapabiltyPropertyMap = convertComponentCapabilitiesProperties(containerComponent);
2370                 return nodeTemplateOperation.overrideComponentCapabilitiesProperties(containerComponent, mapCapabiltyPropertyMap);
2371         }
2372
2373         public StorageOperationStatus deleteAllCalculatedCapabilitiesRequirements(String topologyTemplateId) {
2374                 StorageOperationStatus status = topologyTemplateOperation.removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES);
2375                 if (status == StorageOperationStatus.OK) {
2376                         status = topologyTemplateOperation.removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS);
2377                 }
2378                 if(status == StorageOperationStatus.OK){
2379                         status = topologyTemplateOperation.removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES);
2380                 }
2381                 return status;
2382         }
2383
2384         public Either<Component, StorageOperationStatus> shouldUpgradeToLatestDerived(Resource clonedResource) {
2385                 String componentId = clonedResource.getUniqueId();
2386                 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
2387                 if (getVertexEither.isRight()) {
2388                         log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
2389                         return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
2390
2391                 }
2392                 GraphVertex nodeTypeV = getVertexEither.left().value();
2393                 
2394                 ToscaElement toscaElementToUpdate = ModelConverter.convertToToscaElement(clonedResource);
2395
2396                 Either<ToscaElement, StorageOperationStatus> shouldUpdateDerivedVersion = nodeTypeOperation.shouldUpdateDerivedVersion(toscaElementToUpdate, nodeTypeV);
2397                 if ( shouldUpdateDerivedVersion.isRight() && StorageOperationStatus.OK != shouldUpdateDerivedVersion.right().value() ){
2398                         log.debug("Failed to update derived version for node type {} derived {}, error: {}", componentId, clonedResource.getDerivedFrom().get(0), shouldUpdateDerivedVersion.right().value());
2399                         return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
2400                 }
2401                 if ( shouldUpdateDerivedVersion.isLeft() ){
2402                         return Either.left(ModelConverter.convertFromToscaElement(shouldUpdateDerivedVersion.left().value()));
2403                 }
2404                 return Either.left(clonedResource);
2405         }
2406         /**
2407          * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name, type and ownerId
2408          * @param componentId
2409          * @param instanceId
2410          * @param capabilityName
2411          * @param capabilityType
2412          * @param ownerId 
2413          * @return
2414          */
2415         public Either<List<ComponentInstanceProperty>, StorageOperationStatus> getComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityName, String capabilityType, String ownerId) {
2416                 return topologyTemplateOperation.getComponentInstanceCapabilityProperties(componentId, instanceId, capabilityName, capabilityType, ownerId);
2417         }
2418
2419         private Map<String, MapCapabiltyProperty> convertComponentCapabilitiesProperties(Component currComponent) {
2420                 return currComponent.getComponentInstances()
2421                                 .stream()
2422                                 .collect(Collectors.toMap(ComponentInstanceDataDefinition::getUniqueId,
2423                                                 ci -> ModelConverter.convertToMapOfMapCapabiltyProperties(ci.getCapabilities(), ci.getUniqueId(), true)));
2424         }
2425
2426         private Optional<MapCapabiltyProperty> convertComponentInstanceProperties(Component component, String instanceId) {
2427                 return component.fetchInstanceById(instanceId)
2428                                 .map(ci -> ModelConverter.convertToMapOfMapCapabiltyProperties(ci.getCapabilities(),instanceId));
2429         }
2430
2431         public Either<PolicyDefinition, StorageOperationStatus> associatePolicyToComponent(String componentId, PolicyDefinition policyDefinition, int counter) {
2432                 Either<PolicyDefinition, StorageOperationStatus> result = null;
2433                 Either<GraphVertex, TitanOperationStatus> getVertexEither;
2434                 getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata);
2435                 if (getVertexEither.isRight()) {
2436                         log.error("Couldn't fetch a component with and UniqueId {}, error: {}", componentId, getVertexEither.right().value());
2437                         result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
2438                 } else {
2439                         if(getVertexEither.left().value().getLabel() != VertexTypeEnum.TOPOLOGY_TEMPLATE){
2440                                 log.error("Policy association to component of Tosca type {} is not allowed. ", getVertexEither.left().value().getLabel());
2441                                 result = Either.right(StorageOperationStatus.BAD_REQUEST);
2442                         }
2443                 }
2444                 if(result == null){
2445                         StorageOperationStatus status = topologyTemplateOperation.addPolicyToToscaElement(getVertexEither.left().value(), policyDefinition, counter);
2446                         if(status != StorageOperationStatus.OK){
2447                                 return Either.right(status);
2448                         }
2449                 }
2450                 if(result == null){
2451                         result = Either.left(policyDefinition);
2452                 }
2453                 return result;
2454         }
2455
2456         public Either<PolicyDefinition, StorageOperationStatus> updatePolicyOfComponent(String componentId,     PolicyDefinition policyDefinition) {
2457                 Either<PolicyDefinition, StorageOperationStatus> result = null;
2458                 Either<GraphVertex, TitanOperationStatus> getVertexEither;
2459                 getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
2460                 if (getVertexEither.isRight()) {
2461                         log.error("Couldn't fetch a component with and UniqueId {}, error: {}", componentId, getVertexEither.right().value());
2462                         result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
2463                 }
2464                 if(result == null){
2465                         StorageOperationStatus status = topologyTemplateOperation.updatePolicyOfToscaElement(getVertexEither.left().value(), policyDefinition);
2466                         if(status != StorageOperationStatus.OK){
2467                                 return Either.right(status);
2468                         }
2469                 }
2470                 if(result == null){
2471                         result = Either.left(policyDefinition);
2472                 }
2473                 return result;
2474         }
2475
2476         public StorageOperationStatus updatePoliciesOfComponent(String componentId, List<PolicyDefinition> policyDefinition) {
2477                 log.debug("#updatePoliciesOfComponent - updating policies for component {}", componentId);
2478                 return titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse)
2479                                 .right()
2480                                 .map(DaoStatusConverter::convertTitanStatusToStorageStatus)
2481                                 .either(containerVertex -> topologyTemplateOperation.updatePoliciesOfToscaElement(containerVertex, policyDefinition),
2482                                                 err -> err);
2483         }
2484
2485         public StorageOperationStatus removePolicyFromComponent(String componentId,     String policyId) {
2486                 StorageOperationStatus status = null;
2487                 Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
2488                 if (getVertexEither.isRight()) {
2489                         log.error("Couldn't fetch a component with and UniqueId {}, error: {}", componentId, getVertexEither.right().value());
2490                         status = DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
2491                 }
2492                 if(status == null){
2493                         status = topologyTemplateOperation.removePolicyFromToscaElement(getVertexEither.left().value(), policyId);
2494                 }
2495                 return status;
2496         }
2497 }