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