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