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