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