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