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