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