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