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