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