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