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