c487b0ce71f3974fb40ad6a3169b88af5809d08b
[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.operations.impl;
22
23 import java.util.ArrayList;
24 import java.util.HashMap;
25 import java.util.HashSet;
26 import java.util.Iterator;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.Map.Entry;
30 import java.util.Optional;
31 import java.util.Set;
32 import java.util.UUID;
33 import java.util.function.Function;
34 import java.util.function.Supplier;
35 import java.util.stream.Collectors;
36
37 import org.apache.commons.lang3.tuple.ImmutablePair;
38 import org.apache.tinkerpop.gremlin.structure.Direction;
39 import org.apache.tinkerpop.gremlin.structure.Edge;
40 import org.apache.tinkerpop.gremlin.structure.Vertex;
41 import org.apache.tinkerpop.gremlin.structure.VertexProperty;
42 import org.openecomp.sdc.be.config.BeEcompErrorManager;
43 import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
44 import org.openecomp.sdc.be.dao.graph.GraphElementFactory;
45 import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
46 import org.openecomp.sdc.be.dao.graph.datatype.GraphElementTypeEnum;
47 import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
48 import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation;
49 import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
50 import org.openecomp.sdc.be.dao.neo4j.GraphEdgePropertiesDictionary;
51 import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
52 import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
53 import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
54 import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
55 import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition;
56 import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
57 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
58 import org.openecomp.sdc.be.datatypes.elements.PropertyRule;
59 import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
60 import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
61 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
62 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
63 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
64 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
65 import org.openecomp.sdc.be.model.ArtifactDefinition;
66 import org.openecomp.sdc.be.model.CapabilityDefinition;
67 import org.openecomp.sdc.be.model.Component;
68 import org.openecomp.sdc.be.model.ComponentInstance;
69 import org.openecomp.sdc.be.model.ComponentInstanceAttribute;
70 import org.openecomp.sdc.be.model.ComponentInstanceInput;
71 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
72 import org.openecomp.sdc.be.model.DataTypeDefinition;
73 import org.openecomp.sdc.be.model.GroupDefinition;
74 import org.openecomp.sdc.be.model.GroupInstance;
75 import org.openecomp.sdc.be.model.HeatParameterDefinition;
76 import org.openecomp.sdc.be.model.IComponentInstanceConnectedElement;
77 import org.openecomp.sdc.be.model.InputDefinition;
78 import org.openecomp.sdc.be.model.LifecycleStateEnum;
79 import org.openecomp.sdc.be.model.PropertyDefinition;
80 import org.openecomp.sdc.be.model.RelationshipImpl;
81 import org.openecomp.sdc.be.model.RequirementAndRelationshipPair;
82 import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
83 import org.openecomp.sdc.be.model.RequirementDefinition;
84 import org.openecomp.sdc.be.model.Resource;
85 import org.openecomp.sdc.be.model.User;
86 import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
87 import org.openecomp.sdc.be.model.operations.api.IAttributeOperation;
88 import org.openecomp.sdc.be.model.operations.api.IComponentInstanceOperation;
89 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
90 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
91 import org.openecomp.sdc.be.resources.data.ArtifactData;
92 import org.openecomp.sdc.be.resources.data.AttributeData;
93 import org.openecomp.sdc.be.resources.data.AttributeValueData;
94 import org.openecomp.sdc.be.resources.data.CapabilityData;
95 import org.openecomp.sdc.be.resources.data.CapabilityInstData;
96 import org.openecomp.sdc.be.resources.data.ComponentInstanceData;
97 import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
98 import org.openecomp.sdc.be.resources.data.InputValueData;
99 import org.openecomp.sdc.be.resources.data.InputsData;
100 import org.openecomp.sdc.be.resources.data.PropertyData;
101 import org.openecomp.sdc.be.resources.data.PropertyValueData;
102 import org.openecomp.sdc.be.resources.data.RelationshipInstData;
103 import org.openecomp.sdc.be.resources.data.RelationshipTypeData;
104 import org.openecomp.sdc.be.resources.data.RequirementData;
105 import org.openecomp.sdc.be.resources.data.ResourceMetadataData;
106 import org.openecomp.sdc.be.resources.data.UniqueIdData;
107 import org.openecomp.sdc.be.resources.data.UserData;
108 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
109 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
110 import org.openecomp.sdc.common.config.EcompErrorName;
111 import org.openecomp.sdc.common.datastructure.Wrapper;
112 import org.openecomp.sdc.common.util.ValidationUtils;
113 import org.slf4j.Logger;
114 import org.slf4j.LoggerFactory;
115 import org.springframework.beans.factory.annotation.Autowired;
116
117 import com.thinkaurelius.titan.core.TitanEdge;
118 import com.thinkaurelius.titan.core.TitanGraph;
119 import com.thinkaurelius.titan.core.TitanVertex;
120 import com.thinkaurelius.titan.core.TitanVertexQuery;
121
122 import fj.data.Either;
123
124 @org.springframework.stereotype.Component("component-instance-operation")
125 public class ComponentInstanceOperation extends AbstractOperation implements IComponentInstanceOperation {
126
127         public ComponentInstanceOperation() {
128                 super();
129         }
130
131         private static Logger log = LoggerFactory.getLogger(ComponentInstanceOperation.class.getName());
132
133         @Autowired
134         private ResourceOperation resourceOperation;
135
136         @Autowired
137         private ServiceOperation serviceOperation;
138
139         @Autowired
140         CapabilityOperation capabilityOperation;
141
142         @Autowired
143         private CapabilityInstanceOperation capabilityInstanceOperation;
144
145         @Autowired
146         private RequirementOperation requirementOperation;
147
148         @Autowired
149         private ArtifactOperation artifactOperation;
150
151         @Autowired
152         TitanGenericDao titanGenericDao;
153
154         @Autowired
155         PropertyOperation propertyOperation;
156
157         @Autowired
158         InputsOperation inputOperation;
159
160         @Autowired
161         private IAttributeOperation attributeOperation;
162
163         @Autowired
164         private ApplicationDataTypeCache dataTypeCache;
165
166         @Autowired
167         protected GroupOperation groupOperation;
168
169         @Autowired
170         protected GroupInstanceOperation groupInstanceOperation;
171
172         /**
173          * FOR TEST ONLY
174          * 
175          * @param titanGenericDao
176          */
177         public void setTitanGenericDao(TitanGenericDao titanGenericDao) {
178                 this.titanGenericDao = titanGenericDao;
179         }
180
181         @Override
182         public Either<ComponentInstance, StorageOperationStatus> createComponentInstance(String parentComponentId, NodeTypeEnum nodeType, String instanceNumber, ComponentInstance componentInstance, NodeTypeEnum compInstNodeType, boolean inTransaction) {
183
184                 return createComponentInstance(parentComponentId, nodeType, instanceNumber, true, componentInstance, compInstNodeType, false, inTransaction);
185
186         }
187
188         private Either<ComponentInstance, StorageOperationStatus> createComponentInstance(String containerComponentId, NodeTypeEnum containerNodeType, String instanceNumber, boolean isCreateLocgicalName, ComponentInstance componentInstance,
189                         NodeTypeEnum compInstNodeType, boolean allowDeleted, boolean inTransaction) {
190                 Either<ComponentInstance, StorageOperationStatus> result = null;
191
192                 if (!ValidationUtils.validateStringNotEmpty(componentInstance.getCustomizationUUID())) {
193                         generateCustomizationUUID(componentInstance);
194                 }
195                 try {
196
197                         Either<ComponentInstance, TitanOperationStatus> addRes = addComponentInstanceToContainerComponent(containerComponentId, containerNodeType, instanceNumber, isCreateLocgicalName, componentInstance, compInstNodeType, allowDeleted);
198                         if (addRes.isRight()) {
199                                 TitanOperationStatus status = addRes.right().value();
200                                 log.error("Failed to add resource instance {} to service {}. status is {}", componentInstance, containerComponentId, status);
201                                 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
202                                 return result;
203                         }
204
205                         ComponentInstance value = addRes.left().value();
206                         result = Either.left(value);
207
208                         return result;
209
210                 } finally {
211                         if (false == inTransaction) {
212                                 commitOrRollback(result);
213                         }
214                 }
215         }
216
217         private Either<TitanVertex, StorageOperationStatus> createComponentInstance(String containerComponentId, NodeTypeEnum containerNodeType, String instanceNumber, boolean isCreateLocgicalName, ComponentInstance componentInstance,
218                         NodeTypeEnum compInstNodeType, boolean allowDeleted, boolean inTransaction, TitanVertex metadataVertex) {
219                 Either<TitanVertex, StorageOperationStatus> result = null;
220
221                 try {
222
223                         Either<TitanVertex, TitanOperationStatus> addRes = addComponentInstanceToContainerComponent(containerComponentId, containerNodeType, instanceNumber, isCreateLocgicalName, componentInstance, compInstNodeType, allowDeleted, metadataVertex);
224                         if (addRes.isRight()) {
225                                 TitanOperationStatus status = addRes.right().value();
226                                 log.error("Failed to add resource instance {} to service {}. status is {}", componentInstance, containerComponentId, status);
227                                 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
228                                 return result;
229                         }
230
231                         TitanVertex value = addRes.left().value();
232                         result = Either.left(value);
233
234                         return result;
235
236                 } finally {
237                         if (false == inTransaction) {
238                                 commitOrRollback(result);
239                         }
240                 }
241         }
242
243         @Override
244         public Either<ComponentInstance, StorageOperationStatus> createComponentInstance(String containerComponentId, NodeTypeEnum containerNodeType, String instanceNumber, ComponentInstance componentInstance, NodeTypeEnum instNodeType) {
245
246                 return createComponentInstance(containerComponentId, containerNodeType, instanceNumber, componentInstance, instNodeType, false);
247
248         }
249
250         @Override
251         public Either<ComponentInstance, StorageOperationStatus> deleteComponentInstance(NodeTypeEnum containerNodeType, String containerComponentId, String resourceInstUid, boolean inTransaction) {
252
253                 Either<ComponentInstance, StorageOperationStatus> result = null;
254
255                 try {
256
257                         Either<ComponentInstance, TitanOperationStatus> deleteRes = removeComponentInstanceFromComponent(containerNodeType, containerComponentId, resourceInstUid);
258
259                         if (deleteRes.isRight()) {
260                                 TitanOperationStatus status = deleteRes.right().value();
261                                 log.error("Failed to remove resource instance {} from component {}. status is {}", resourceInstUid, containerComponentId, status);
262                                 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
263                                 return result;
264                         }
265
266                         ComponentInstance value = deleteRes.left().value();
267                         result = Either.left(value);
268
269                         return result;
270
271                 } finally {
272                         if (false == inTransaction) {
273                                 commitOrRollback(result);
274                         }
275                 }
276
277         }
278
279         @Override
280         public Either<ComponentInstance, StorageOperationStatus> deleteComponentInstance(NodeTypeEnum containerNodeType, String containerComponentId, String resourceInstUid) {
281
282                 return deleteComponentInstance(containerNodeType, containerComponentId, resourceInstUid, false);
283         }
284
285         private <T> void commitOrRollback(Either<T, StorageOperationStatus> result) {
286                 if (result == null || result.isRight()) {
287                         log.error("Going to execute rollback on graph.");
288                         titanGenericDao.rollback();
289                 } else {
290                         log.debug("Going to execute commit on graph.");
291                         titanGenericDao.commit();
292                 }
293         }
294
295         @Override
296         public Either<Boolean, StorageOperationStatus> validateParent(String parentId, String uniqId, boolean inTransaction) {
297
298                 Either<Boolean, StorageOperationStatus> result = null;
299                 Either<Boolean, TitanOperationStatus> updateRes = validateParentonGraph(parentId, uniqId, inTransaction);
300
301                 if (updateRes.isRight()) {
302                         TitanOperationStatus status = updateRes.right().value();
303                         log.error("Failed to find resource instance name {}. status is {}", uniqId, status);
304                         result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
305                         return result;
306                 }
307
308                 Boolean value = updateRes.left().value();
309
310                 result = Either.left(value);
311
312                 return result;
313
314         }
315
316         public Either<Boolean, TitanOperationStatus> validateParentonGraph(String parentId, String uniqId, boolean inTransaction) {
317
318                 Either<TitanGraph, TitanOperationStatus> graphRes = titanGenericDao.getGraph();
319                 if (graphRes.isRight()) {
320                         log.debug("Failed to retrieve graph. status is {}", graphRes);
321                         return Either.right(graphRes.right().value());
322                 }
323                 TitanGraph titanGraph = graphRes.left().value();
324                 try {
325                         Iterable<TitanVertex> vertices = titanGraph.query().has(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), uniqId).vertices();
326                         if (vertices == null || false == vertices.iterator().hasNext()) {
327                                 return Either.right(TitanOperationStatus.INVALID_ID);
328                         }
329
330                         TitanVertex vertex = vertices.iterator().next();
331
332                         TitanVertexQuery query = vertex.query();
333                         query = query.labels(GraphEdgeLabels.RESOURCE_INST.getProperty()).direction(Direction.IN);
334                         Iterable<Vertex> verts = query.vertices();
335                         if (verts == null) {
336                                 log.debug("No edges in graph for criteria");
337                                 return Either.right(TitanOperationStatus.INVALID_ID);
338                         }
339                         Iterator<Vertex> vIter = verts.iterator();
340                         if (vIter.hasNext()) {
341                                 Vertex vert = vIter.next();
342                                 // vert.getProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
343                                 String resInstName = vert.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
344                                 if (resInstName.equals(parentId))
345                                         return Either.left(Boolean.TRUE);
346                         }
347                         return Either.left(Boolean.FALSE);
348                 } finally {
349                         if (false == inTransaction) {
350                                 titanGraph.tx().commit();
351                         }
352                 }
353         }
354
355         public Either<ComponentInstance, TitanOperationStatus> addComponentInstanceToContainerComponent(String containerComponentId, NodeTypeEnum containerNodeType, String instanceNumber, boolean isCreateLogicaName, ComponentInstance componentInstance,
356                         NodeTypeEnum compInstNodeType, boolean allowDeleted) {
357                 log.debug("Going to create component instance {} in component {}", componentInstance, containerComponentId);
358
359                 Either<TitanVertex, TitanOperationStatus> metadataVertex = titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), containerComponentId);
360                 if (metadataVertex.isRight()) {
361                         TitanOperationStatus status = metadataVertex.right().value();
362                         if (status == TitanOperationStatus.NOT_FOUND) {
363                                 status = TitanOperationStatus.INVALID_ID;
364                         }
365                         return Either.right(status);
366                 }
367                 Either<TitanVertex, TitanOperationStatus> addComponentInstanceToContainerComponent = addComponentInstanceToContainerComponent(containerComponentId, containerNodeType, instanceNumber, isCreateLogicaName, componentInstance, compInstNodeType,
368                                 allowDeleted, metadataVertex.left().value());
369
370                 if (addComponentInstanceToContainerComponent.isRight()) {
371                         TitanOperationStatus status = addComponentInstanceToContainerComponent.right().value();
372                         if (status == TitanOperationStatus.NOT_FOUND) {
373                                 status = TitanOperationStatus.INVALID_ID;
374                         }
375                         return Either.right(status);
376                 }
377                 TitanVertex ciVertex = addComponentInstanceToContainerComponent.left().value();
378                 Map<String, Object> properties = titanGenericDao.getProperties(ciVertex);
379                 ComponentInstanceData createdComponentInstance = GraphElementFactory.createElement(NodeTypeEnum.ResourceInstance.getName(), GraphElementTypeEnum.Node, properties, ComponentInstanceData.class);
380
381                 Either<ComponentInstance, TitanOperationStatus> createdResourceInstanceRes = createGroupInstancesOnComponentInstance(componentInstance, ciVertex, createdComponentInstance);
382                 return createdResourceInstanceRes;
383         }
384
385
386         public Either<ComponentInstance, TitanOperationStatus> createGroupInstancesOnComponentInstance(ComponentInstance componentInstance, TitanVertex ciVertex, ComponentInstanceData createdComponentInstance) {
387                 ComponentInstance createdResourceInstance = new ComponentInstance(createdComponentInstance.getComponentInstDataDefinition());
388                 createdResourceInstance.setGroupInstances(componentInstance.getGroupInstances());
389                 List<GroupInstance> groupInstancesList = new ArrayList<GroupInstance>();
390                 List<GroupDefinition> group = null;
391                 Either<List<GroupDefinition>, TitanOperationStatus> groupEither = groupOperation.getAllGroupsFromGraph(createdResourceInstance.getComponentUid(), NodeTypeEnum.Resource);
392                 if (groupEither.isRight() && groupEither.right().value() != TitanOperationStatus.OK && groupEither.right().value() != TitanOperationStatus.NOT_FOUND) {
393                         TitanOperationStatus status = groupEither.right().value();
394                         log.debug("Failed to associate group instances to component instance {}. Status is {}", componentInstance.getUniqueId(), status);
395                         return Either.right(status);
396                 } else {
397                         if (groupEither.isLeft()) {
398                                 group = groupEither.left().value();
399                                 if (group != null && !group.isEmpty()) {
400                                         List<GroupDefinition> vfGroupsList = group.stream().filter(p -> p.getType().equals("org.openecomp.groups.VfModule")).collect(Collectors.toList());
401                                         for (GroupDefinition groupDefinition : vfGroupsList) {
402                                                 Either<GroupInstance, StorageOperationStatus> status = createGroupInstance(ciVertex, groupDefinition, createdResourceInstance);
403                                                 if (status.isRight()) {
404                                                         log.debug("Failed to associate group instances to component instance {}. Status is {}", componentInstance.getUniqueId(), status);
405
406                                                 } else {
407                                                         GroupInstance groupInstance = status.left().value();
408                                                         groupInstancesList.add(groupInstance);
409                                                 }
410
411                                         }
412                                         createdResourceInstance.setGroupInstances(groupInstancesList);
413                                 }
414                         }
415
416                 }
417                 return Either.left(createdResourceInstance);
418         }
419
420         public void generateCustomizationUUID(ComponentInstance componentInstance) {
421                 UUID uuid = UUID.randomUUID();
422                 componentInstance.setCustomizationUUID(uuid.toString());
423         }
424
425         /**
426          * 
427          * @param containerComponentId
428          * @param containerNodeType
429          * @param instanceNumber
430          * @param isCreateLogicaName
431          * @param componentInstance
432          * @param compInstNodeType
433          * @param allowDeleted
434          * @param metadataVertex
435          * @return
436          */
437         public Either<TitanVertex, TitanOperationStatus> addComponentInstanceToContainerComponent(String containerComponentId, NodeTypeEnum containerNodeType, String instanceNumber, boolean isCreateLogicaName, ComponentInstance componentInstance,
438                         NodeTypeEnum compInstNodeType, boolean allowDeleted, TitanVertex metadataVertex) {
439                 TitanOperationStatus status;
440                 log.debug("Going to create component instance {} in component {}", componentInstance, containerComponentId);
441                 String instOriginComponentId = componentInstance.getComponentUid();
442                 String logicalName = componentInstance.getName();
443                 if (isCreateLogicaName)
444                         logicalName = createComponentInstLogicalName(instanceNumber, componentInstance.getName());
445
446                 ComponentInstanceData componentInstanceData = buildComponentInstanceData(componentInstance, containerComponentId, logicalName);
447                 Either<TitanVertex, TitanOperationStatus> originVertexEither = titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), instOriginComponentId);
448                 if (originVertexEither.isRight()) {
449                         log.debug("Failed to fetch vertex of origin resource for id {} error {}", instOriginComponentId, originVertexEither.right().value());
450                         return Either.right(originVertexEither.right().value());
451                 }
452                 TitanVertex originVertex = originVertexEither.left().value();
453
454                 Boolean isDeleted = (Boolean) titanGenericDao.getProperty(metadataVertex, GraphPropertiesDictionary.IS_DELETED.getProperty());
455
456                 if (!allowDeleted && (isDeleted != null) && (isDeleted == true)) {
457                         log.debug("Component {} is already deleted. Cannot add component instance", instOriginComponentId);
458                         return Either.right(TitanOperationStatus.INVALID_ID);
459                 }
460                 String originType = (String) titanGenericDao.getProperty(originVertex, GraphPropertiesDictionary.LABEL.getProperty());
461                 String resourceType = (String) titanGenericDao.getProperty(originVertex, GraphPropertiesDictionary.RESOURCE_TYPE.getProperty());
462
463                 log.trace("Before adding component instance to graph. componentInstanceData = {}", componentInstanceData);
464
465                 Either<TitanVertex, TitanOperationStatus> createCIResult = titanGenericDao.createNode(componentInstanceData);
466
467                 log.debug("After adding component instance to graph. status is = {}", createCIResult);
468
469                 if (createCIResult.isRight()) {
470                         status = createCIResult.right().value();
471                         BeEcompErrorManager.getInstance().logBeDaoSystemError("Add Component Instance");
472                         log.debug("Failed to create component instance node in graph. status is {}", status);
473                         return Either.right(status);
474                 }
475                 TitanVertex createdComponentInstanceVertex = createCIResult.left().value();
476                 TitanOperationStatus associateContainerRes = associateContainerCompToComponentInstance(metadataVertex, createdComponentInstanceVertex, logicalName);
477
478                 String componentInstanceUniqueId = componentInstanceData.getUniqueId();
479                 if (associateContainerRes != TitanOperationStatus.OK) {
480                         BeEcompErrorManager.getInstance().logBeDaoSystemError("Add Component Instance");
481                         log.debug("Failed to associate container component {} to component instance {}. Status is {}", containerComponentId, componentInstanceUniqueId, associateContainerRes);
482                         return Either.right(associateContainerRes);
483                 }
484                 String originId = (String) titanGenericDao.getProperty(createdComponentInstanceVertex, GraphPropertiesDictionary.TYPE.getProperty());
485
486                 TitanOperationStatus associateToInstOriginComponent = associateToInstOriginComponent(createdComponentInstanceVertex, originVertex, originId);
487                 if (associateToInstOriginComponent != TitanOperationStatus.OK) {
488                         BeEcompErrorManager.getInstance().logBeDaoSystemError("Add Component Instance");
489                         log.debug("Failed to associate component instance {} to its origin component {}. Status is {}", componentInstanceUniqueId, componentInstanceData.getComponentInstDataDefinition().getComponentUid(), associateToInstOriginComponent);
490                         return Either.right(associateToInstOriginComponent);
491                 }
492
493                 TitanOperationStatus associateCompInstToRequirements = associateCompInstToRequirements(createdComponentInstanceVertex, containerNodeType, compInstNodeType, originId);
494                 if (associateCompInstToRequirements != TitanOperationStatus.OK) {
495                         BeEcompErrorManager.getInstance().logBeDaoSystemError("Add Component Instance");
496                         log.debug("Failed to associate component instance {} to its origin requirements. Status is {}", componentInstanceUniqueId, associateCompInstToRequirements);
497                         return Either.right(associateCompInstToRequirements);
498                 }
499                 TitanOperationStatus associateCompInstToCapabilities = associateCompInstToCapabilities(createdComponentInstanceVertex, containerNodeType, compInstNodeType, originId);
500                 if (associateCompInstToCapabilities != TitanOperationStatus.OK) {
501                         BeEcompErrorManager.getInstance().logBeDaoSystemError("Add Component Instance");
502                         log.debug("Failed to associate component instance {} to its origin capabilities. Status is {}", componentInstanceUniqueId, associateCompInstToCapabilities);
503                         return Either.right(associateCompInstToCapabilities);
504                 }
505                 // Capability instance with property values implementation
506                 Either<List<ImmutablePair<TitanVertex, GraphEdge>>, TitanOperationStatus> cloneCapabilityInstancesRes = null;
507                 Either<List<GraphRelation>, TitanOperationStatus> associateComponentInstanceToCapabilityInstancesRes;
508                 status = null;
509                 if (!isCreateLogicaName) {
510                         // in case of cloning of component instance
511                         log.debug("Before cloning of capability instances of component instance {}.", componentInstance.getUniqueId());
512                         cloneCapabilityInstancesRes = cloneCapabilityInstancesOfResourceInstance(createdComponentInstanceVertex, componentInstance);
513                         if (cloneCapabilityInstancesRes.isRight() && !cloneCapabilityInstancesRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
514                                 status = cloneCapabilityInstancesRes.right().value();
515                                 log.debug("Failed to clone capability instances of component instance {}. Status is {}", componentInstance.getUniqueId(), status);
516                         }
517                         log.trace("After cloning of capability instances of component instance {}. Status is {}", componentInstance.getUniqueId(), status);
518                 } else if (containerNodeType.equals(NodeTypeEnum.Resource) && componentInstance.getCapabilities() != null && !componentInstance.getCapabilities().isEmpty()) {
519                         // in case of creation from scar
520                         TitanOperationStatus addPropertiesRes = createCapabilityInstancesWithPropertyValues(createdComponentInstanceVertex, componentInstanceUniqueId, componentInstance.getCapabilities(), true);
521                         if (addPropertiesRes != TitanOperationStatus.OK) {
522                                 status = addPropertiesRes;
523                                 log.debug("Failed to create capability instances with property values for component instance {}. Status is {}", componentInstance.getUniqueId(), status);
524                         }
525                 }
526                 if (status == null && containerNodeType.equals(NodeTypeEnum.Service)) {
527                         Map<String, Object> properties = titanGenericDao.getProperties(createdComponentInstanceVertex);
528                         ComponentInstanceData createdComponentInstance = GraphElementFactory.createElement(NodeTypeEnum.ResourceInstance.getName(), GraphElementTypeEnum.Node, properties, ComponentInstanceData.class);
529                         if (cloneCapabilityInstancesRes == null || cloneCapabilityInstancesRes.isRight()) {
530                                 // in case of creating of service
531                                 log.trace("Before associating component instance {} to capability instances .", componentInstance.getUniqueId());
532                                 associateComponentInstanceToCapabilityInstancesRes = associateComponentInstanceToCapabilityInstancesOfResourceInstance(componentInstance);
533                                 if (associateComponentInstanceToCapabilityInstancesRes.isRight() && !associateComponentInstanceToCapabilityInstancesRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
534                                         status = associateComponentInstanceToCapabilityInstancesRes.right().value();
535                                         log.debug("Failed to associate capability instances to component instance {}. Status is {}", componentInstance.getUniqueId(), status);
536                                 }
537                                 log.trace("After associating component instance {} to capability instances . Status is {}", componentInstance.getUniqueId(), status);
538                         } else {
539                                 // in case of cloning of service
540                                 log.trace("Before associating created component instance {} to cloned capability instances.", componentInstanceUniqueId);
541                                 TitanOperationStatus associationStatus = associateCreatedComponentInstanceToClonedCapabilityInstances(createdComponentInstanceVertex, componentInstanceUniqueId, cloneCapabilityInstancesRes.left().value());
542                                 if (associationStatus != TitanOperationStatus.OK && associationStatus != TitanOperationStatus.NOT_FOUND) {
543                                         status = associationStatus;
544                                         log.debug("Failed to associate capability instances to component instance {}. Status is {}", componentInstance.getUniqueId(), status);
545                                 }
546                                 log.trace("After associating created component instance {} to cloned capability instances. Status is {}", componentInstanceUniqueId, status);
547                         }
548                 }
549
550                 if (status == null) {
551                         // ComponentInstance createdResourceInstance = new
552                         // ComponentInstance(createdComponentInstance.getComponentInstDataDefinition());
553                         //
554                         // String icon = (String) titanGenericDao.getProperty(originVertex,
555                         // GraphPropertiesDictionary.ICON.getProperty());
556                         // createdResourceInstance.setIcon(icon);
557                         return Either.left(createdComponentInstanceVertex);
558                 }
559                 return Either.right(status);
560         }
561
562         private Either<Map<CapabilityInstData, List<PropertyValueData>>, TitanOperationStatus> createCapabilityInstancesWithPropertyValues(String resourceInstanceId, Map<String, List<CapabilityDefinition>> capabilities,
563                         boolean isNewlyCreatedResourceInstance) {
564                 TitanOperationStatus error;
565                 Map<CapabilityInstData, List<PropertyValueData>> result = new HashMap<>();
566                 for (Entry<String, List<CapabilityDefinition>> capailityEntry : capabilities.entrySet()) {
567                         CapabilityDefinition capability = capailityEntry.getValue().get(0);
568                         if (capability.getProperties() != null && !capability.getProperties().isEmpty()) {
569                                 Either<Map<CapabilityInstData, List<PropertyValueData>>, TitanOperationStatus> addPropertiesRes = addCapabilityPropertyValuesToResourceInstance(resourceInstanceId, capability, isNewlyCreatedResourceInstance);
570                                 if (addPropertiesRes.isRight()) {
571                                         error = addPropertiesRes.right().value();
572                                         log.debug("Failed to add property values to capabilities of component instance {}. Status is {}", resourceInstanceId, error);
573                                         return Either.right(error);
574                                 } else {
575                                         result.putAll(addPropertiesRes.left().value());
576                                 }
577                         }
578                 }
579                 return Either.left(result);
580         }
581
582         private TitanOperationStatus createCapabilityInstancesWithPropertyValues(TitanVertex resourceInstanceVertex, String resourceInstanceId, Map<String, List<CapabilityDefinition>> capabilities, boolean isNewlyCreatedResourceInstance) {
583                 TitanOperationStatus result = TitanOperationStatus.OK;
584
585                 for (Entry<String, List<CapabilityDefinition>> capailityEntry : capabilities.entrySet()) {
586                         CapabilityDefinition capability = capailityEntry.getValue().get(0);
587                         if (capability.getProperties() != null && !capability.getProperties().isEmpty()) {
588                                 TitanOperationStatus addPropertiesRes = addCapabilityPropertyValuesToResourceInstance(resourceInstanceVertex, resourceInstanceId, capability, isNewlyCreatedResourceInstance);
589                                 if (addPropertiesRes != TitanOperationStatus.OK) {
590                                         result = addPropertiesRes;
591                                         log.debug("Failed to add property values to capabilities of component instance {}. Status is {}", resourceInstanceId, result);
592                                         return result;
593                                 }
594                         }
595                 }
596                 return result;
597         }
598
599         private Either<List<GraphRelation>, TitanOperationStatus> associateCreatedComponentInstanceToClonedCapabilityInstances(String newComponentResourceId, List<ImmutablePair<CapabilityInstData, GraphEdge>> capabilityInstances) {
600                 TitanOperationStatus error = null;
601                 List<GraphRelation> relationsToCapabilityInstances = new ArrayList<>();
602                 UniqueIdData componentInstanceIdData = new UniqueIdData(NodeTypeEnum.ResourceInstance, newComponentResourceId);
603                 for (ImmutablePair<CapabilityInstData, GraphEdge> capInstPair : capabilityInstances) {
604                         Either<GraphRelation, TitanOperationStatus> associateComponentInstanceToCapabilityinstanceRes = titanGenericDao.createRelation(componentInstanceIdData, capInstPair.getLeft(), GraphEdgeLabels.CAPABILITY_INST,
605                                         capInstPair.getRight().getProperties());
606                         if (associateComponentInstanceToCapabilityinstanceRes.isRight()) {
607                                 error = associateComponentInstanceToCapabilityinstanceRes.right().value();
608                                 log.debug("Failed to associate capability instance {} to resource instance {} status is {}.", capInstPair.getLeft().getUniqueId(), newComponentResourceId, error);
609                                 break;
610                         } else {
611                                 relationsToCapabilityInstances.add(associateComponentInstanceToCapabilityinstanceRes.left().value());
612                         }
613                 }
614                 if (error == null) {
615                         return Either.left(relationsToCapabilityInstances);
616                 }
617                 return Either.right(error);
618         }
619
620         private TitanOperationStatus associateCreatedComponentInstanceToClonedCapabilityInstances(TitanVertex riVertex, String newComponentResourceId, List<ImmutablePair<TitanVertex, GraphEdge>> capabilityInstances) {
621                 TitanOperationStatus error = null;
622                 for (ImmutablePair<TitanVertex, GraphEdge> capInstPair : capabilityInstances) {
623                         TitanOperationStatus associateComponentInstanceToCapabilityinstanceRes = titanGenericDao.createEdge(riVertex, capInstPair.getLeft(), GraphEdgeLabels.CAPABILITY_INST, capInstPair.getRight().getProperties());
624                         if (associateComponentInstanceToCapabilityinstanceRes != TitanOperationStatus.OK) {
625                                 error = associateComponentInstanceToCapabilityinstanceRes;
626                                 log.debug("Failed to associate capability instance {} to resource instance {} status is {} .", capInstPair.getLeft(), newComponentResourceId, error);
627                                 break;
628                         }
629                 }
630                 if (error == null) {
631                         return TitanOperationStatus.OK;
632                 }
633                 return error;
634         }
635
636         private Either<List<GraphRelation>, TitanOperationStatus> associateComponentInstanceToCapabilityInstancesOfResourceInstance(ComponentInstance componentInstance) {
637                 TitanOperationStatus error = null;
638                 String resourceId = componentInstance.getComponentUid();
639                 String componentResourceId = componentInstance.getUniqueId();
640                 UniqueIdData componentInstanceIdData = new UniqueIdData(NodeTypeEnum.ResourceInstance, componentResourceId);
641                 List<ImmutablePair<ComponentInstanceData, GraphEdge>> resourceInstancesPair;
642                 List<ImmutablePair<CapabilityInstData, GraphEdge>> allCapabilityInstancesList = new ArrayList<>();
643                 List<GraphRelation> relationsToCapabilityInstances = new ArrayList<>();
644                 Either<List<ImmutablePair<ComponentInstanceData, GraphEdge>>, TitanOperationStatus> getAllResourceInstanceRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId,
645                                 GraphEdgeLabels.RESOURCE_INST, NodeTypeEnum.ResourceInstance, ComponentInstanceData.class);
646                 if (getAllResourceInstanceRes.isRight() && !getAllResourceInstanceRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
647                         error = getAllResourceInstanceRes.right().value();
648                         log.debug("Failed to retrieve resource instances from resource {} status is {}.", resourceId, error);
649                 }
650                 if (getAllResourceInstanceRes.isLeft()) {
651                         resourceInstancesPair = getAllResourceInstanceRes.left().value();
652                         ComponentInstanceData ri;
653                         for (ImmutablePair<ComponentInstanceData, GraphEdge> riPair : resourceInstancesPair) {
654                                 ri = riPair.getLeft();
655                                 Either<List<ImmutablePair<CapabilityInstData, GraphEdge>>, TitanOperationStatus> getCapabilityInstancesRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), ri.getUniqueId(),
656                                                 GraphEdgeLabels.CAPABILITY_INST, NodeTypeEnum.CapabilityInst, CapabilityInstData.class);
657                                 if (getCapabilityInstancesRes.isRight() && !getCapabilityInstancesRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
658                                         error = getCapabilityInstancesRes.right().value();
659                                         log.debug("Failed to retrieve capability instances of resource instance {} status is {}.", ri.getUniqueId(), error);
660                                         break;
661                                 }
662                                 if (getCapabilityInstancesRes.isLeft()) {
663                                         allCapabilityInstancesList.addAll(getCapabilityInstancesRes.left().value());
664                                 }
665                         }
666                 }
667                 if (error == null && !allCapabilityInstancesList.isEmpty()) {
668                         for (ImmutablePair<CapabilityInstData, GraphEdge> capInstPair : allCapabilityInstancesList) {
669                                 Either<GraphRelation, TitanOperationStatus> associateComponentInstanceToCapabilityinstanceRes = titanGenericDao.createRelation(componentInstanceIdData, capInstPair.getLeft(), GraphEdgeLabels.CAPABILITY_INST,
670                                                 capInstPair.getRight().getProperties());
671                                 if (associateComponentInstanceToCapabilityinstanceRes.isRight()) {
672                                         error = associateComponentInstanceToCapabilityinstanceRes.right().value();
673                                         log.debug("Failed to associate capability instance {} to resource instance {} status is {}.", capInstPair.getLeft().getUniqueId(), componentResourceId, error);
674                                         break;
675                                 } else {
676                                         relationsToCapabilityInstances.add(associateComponentInstanceToCapabilityinstanceRes.left().value());
677                                 }
678                         }
679                 }
680                 if (error == null) {
681                         return Either.left(relationsToCapabilityInstances);
682                 }
683                 return Either.right(error);
684         }
685
686         private NodeTypeEnum detectOriginType(String label, ComponentInstanceData componentInstanceData, String resourceTypeStr) {
687                 NodeTypeEnum res = null;
688                 res = NodeTypeEnum.getByName(label);
689                 switch (res) {
690                 case Service:
691                         componentInstanceData.getComponentInstDataDefinition().setOriginType(OriginTypeEnum.SERVICE);
692                         break;
693                 case Product:
694                         componentInstanceData.getComponentInstDataDefinition().setOriginType(OriginTypeEnum.PRODUCT);
695                         break;
696                 case Resource:
697                         ResourceTypeEnum resourceType = ResourceTypeEnum.valueOf(resourceTypeStr);
698                         switch (resourceType) {
699                         case VF:
700                                 componentInstanceData.getComponentInstDataDefinition().setOriginType(OriginTypeEnum.VF);
701                                 break;
702                         case VFC:
703                                 componentInstanceData.getComponentInstDataDefinition().setOriginType(OriginTypeEnum.VFC);
704                                 break;
705                         case VFCMT:
706                                 componentInstanceData.getComponentInstDataDefinition().setOriginType(OriginTypeEnum.VFCMT);
707                                 break;
708                         case CP:
709                                 componentInstanceData.getComponentInstDataDefinition().setOriginType(OriginTypeEnum.CP);
710                                 break;
711                         case VL:
712                                 componentInstanceData.getComponentInstDataDefinition().setOriginType(OriginTypeEnum.VL);
713                                 break;
714                         }
715                         break;
716                 default:
717                         break;
718                 }
719                 return res;
720         }
721
722         private Either<GraphRelation, TitanOperationStatus> associateToInstOriginComponent(ComponentInstanceData componentInstanceData, NodeTypeEnum compInstNodeType) {
723
724                 UniqueIdData resourceIdData = new UniqueIdData(compInstNodeType, componentInstanceData.getComponentInstDataDefinition().getComponentUid());
725
726                 Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(componentInstanceData, resourceIdData, GraphEdgeLabels.INSTANCE_OF, null);
727
728                 log.debug("After associating resource instance {} to resource {}. status is {}", componentInstanceData.getUniqueId(), componentInstanceData.getComponentInstDataDefinition().getUniqueId(), createRelation);
729
730                 return createRelation;
731         }
732
733         private TitanOperationStatus associateToInstOriginComponent(TitanVertex componentInstanceVertex, TitanVertex originVertex, String originId) {
734
735                 TitanOperationStatus createRelation = titanGenericDao.createEdge(componentInstanceVertex, originVertex, GraphEdgeLabels.INSTANCE_OF, null);
736
737                 log.debug("After associating resource instance {} to resource {}. status is {}", componentInstanceVertex, originId, createRelation);
738
739                 return createRelation;
740         }
741
742         private Either<List<GraphRelation>, TitanOperationStatus> associateCompInstToRequirements(ComponentInstanceData componentInstanceData, NodeTypeEnum containerNodeType, NodeTypeEnum compInstNodeType) {
743                 log.trace("Starting to copy origin component requirements to its component instance");
744                 String compInstOriginId = componentInstanceData.getComponentInstDataDefinition().getComponentUid();
745                 List<GraphRelation> graphRelations = new ArrayList<>();
746
747                 // case of VFC / CP / VL
748                 if (compInstNodeType.equals(NodeTypeEnum.Resource)) {
749                         createRequirementRelationsFromAtomicResource(componentInstanceData, compInstOriginId, graphRelations);
750
751                 }
752                 // case of VF / Service / Product
753                 createCalculatedRequirementRelationsFromComponent(componentInstanceData, containerNodeType, compInstNodeType, graphRelations, compInstOriginId);
754
755                 log.trace("Finished to copy origin component requirements to its component instance, created {} new calculated requirement relations", graphRelations.size());
756                 return Either.left(graphRelations);
757         }
758
759         private TitanOperationStatus associateCompInstToRequirements(TitanVertex componentInstanceVertex, NodeTypeEnum containerNodeType, NodeTypeEnum compInstNodeType, String originId) {
760                 log.trace("Starting to copy origin component requirements to its component instance");
761                 TitanOperationStatus status = TitanOperationStatus.OK;
762                 // case of VFC / CP / VL
763                 if (compInstNodeType.equals(NodeTypeEnum.Resource)) {
764                         status = createRequirementRelationsFromAtomicResource(componentInstanceVertex, originId);
765                         if (!status.equals(TitanOperationStatus.OK)) {
766                                 log.debug("Failed create relation to requirement of origin {} error {}", originId, status);
767                                 return status;
768                         }
769                 }
770                 // case of VF / Service / Product
771                 status = createCalculatedRequirementRelationsFromComponent(componentInstanceVertex, containerNodeType, compInstNodeType, originId);
772
773                 log.trace("Finished to copy origin component requirements to its component instance with status {}", status);
774                 return status;
775         }
776
777         private void createRequirementRelationsFromAtomicResource(ComponentInstanceData componentInstanceData, String compInstOriginId, List<GraphRelation> graphRelations) {
778                 Map<String, RequirementDefinition> requirements = new HashMap<String, RequirementDefinition>();
779                 Set<String> caseInsensitiveReqNames = new HashSet<>();
780
781                 TitanOperationStatus status = requirementOperation.findAllRequirementsRecursively(compInstOriginId, requirements, caseInsensitiveReqNames);
782                 if (status != TitanOperationStatus.OK) {
783                         log.debug("Couldn't fetch requirements of component {}, error: {}", compInstOriginId, status);
784                 }
785
786                 log.trace("Found {} requirements for component {}, ", requirements.size(), compInstOriginId);
787                 for (Entry<String, RequirementDefinition> reqPair : requirements.entrySet()) {
788                         RequirementDefinition requirementDef = reqPair.getValue();
789                         RequirementData requirementData = new RequirementData();
790                         requirementData.setUniqueId(requirementDef.getUniqueId());
791
792                         log.trace("Creating calculated requirement relation from component instance {} to requirement {}", componentInstanceData.getUniqueId(), requirementDef.getUniqueId());
793                         Map<String, Object> props = new HashMap<String, Object>();
794                         props.put(GraphEdgePropertiesDictionary.NAME.getProperty(), reqPair.getKey());
795
796                         props.put(GraphEdgePropertiesDictionary.OWNER_ID.getProperty(), componentInstanceData.getUniqueId());
797                         if (requirementDef.getMinOccurrences() == null) {
798                                 props.put(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty(), RequirementDataDefinition.MIN_OCCURRENCES);
799                         } else {
800                                 props.put(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty(), requirementDef.getMinOccurrences());
801                         }
802                         if (requirementDef.getMaxOccurrences() == null) {
803                                 props.put(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty(), RequirementDataDefinition.MAX_DEFAULT_OCCURRENCES);
804                         } else {
805                                 props.put(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty(), requirementDef.getMaxOccurrences());
806                         }
807
808                         Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(componentInstanceData, requirementData, GraphEdgeLabels.CALCULATED_REQUIREMENT, props);
809                         if (createRelation.isRight()) {
810                                 TitanOperationStatus titanOperationStatus = createRelation.right().value();
811                                 log.debug("Failed to create calculated requirement from component instance {} to requirement {}, error: {}", componentInstanceData.getUniqueId(), requirementDef.getUniqueId(), titanOperationStatus);
812                         }
813                         graphRelations.add(createRelation.left().value());
814                 }
815         }
816
817         private TitanOperationStatus createRequirementRelationsFromAtomicResource(TitanVertex componentInstanceVertex, String compInstOriginId) {
818                 Map<String, RequirementDefinition> requirements = new HashMap<String, RequirementDefinition>();
819                 Set<String> caseInsensitiveReqNames = new HashSet<>();
820
821                 TitanOperationStatus status = requirementOperation.findAllRequirementsRecursively(compInstOriginId, requirements, caseInsensitiveReqNames);
822                 if (status != TitanOperationStatus.OK && status != TitanOperationStatus.NOT_FOUND) {
823                         log.debug("Couldn't fetch requirements of component {}, error: {}", compInstOriginId, status);
824                         return status;
825                 }
826
827                 String compoInstId = (String) titanGenericDao.getProperty(componentInstanceVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty());
828                 log.trace("Found {} requirements for component {}, ", requirements.size(), compInstOriginId);
829                 for (Entry<String, RequirementDefinition> reqPair : requirements.entrySet()) {
830                         RequirementDefinition requirementDef = reqPair.getValue();
831                         RequirementData requirementData = new RequirementData();
832                         requirementData.setUniqueId(requirementDef.getUniqueId());
833
834                         log.trace("Creating calculated requirement relation from component instance {} to requirement {}", compoInstId, requirementDef.getUniqueId());
835                         Map<String, Object> props = new HashMap<String, Object>();
836                         props.put(GraphEdgePropertiesDictionary.NAME.getProperty(), reqPair.getKey());
837
838                         props.put(GraphEdgePropertiesDictionary.OWNER_ID.getProperty(), compoInstId);
839                         if (requirementDef.getMinOccurrences() == null) {
840                                 props.put(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty(), RequirementDataDefinition.MIN_OCCURRENCES);
841                         } else {
842                                 props.put(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty(), requirementDef.getMinOccurrences());
843                         }
844                         if (requirementDef.getMaxOccurrences() == null) {
845                                 props.put(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty(), RequirementDataDefinition.MAX_DEFAULT_OCCURRENCES);
846                         } else {
847                                 props.put(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty(), requirementDef.getMaxOccurrences());
848                         }
849
850                         TitanOperationStatus createRelation = titanGenericDao.createEdge(componentInstanceVertex, requirementData, GraphEdgeLabels.CALCULATED_REQUIREMENT, props);
851                         if (!createRelation.equals(TitanOperationStatus.OK)) {
852                                 log.debug("Failed to create calculated requirement from component instance {} to requirement {}, error: {}", compoInstId, requirementDef.getUniqueId(), createRelation);
853                                 return createRelation;
854                         }
855                 }
856                 return TitanOperationStatus.OK;
857         }
858
859         private Either<List<GraphRelation>, TitanOperationStatus> associateCompInstToCapabilities(ComponentInstanceData componentInstanceData, NodeTypeEnum containerNodeType, NodeTypeEnum compInstNodeType) {
860
861                 log.trace("Starting to copy origin component capabilities to its component instance");
862                 List<GraphRelation> graphRelations = new ArrayList<>();
863
864                 String compInstOriginId = componentInstanceData.getComponentInstDataDefinition().getComponentUid();
865
866                 // case of VFC / CP / VL
867                 if (compInstNodeType.equals(NodeTypeEnum.Resource)) {
868                         createCaculatedRelationsFromAtomicResource(componentInstanceData, graphRelations, compInstOriginId);
869                 }
870
871                 // case of VF / Service / Product
872                 createCalculatedCapabilityRelationsFromComponent(componentInstanceData, containerNodeType, compInstNodeType, graphRelations, compInstOriginId);
873
874                 log.trace("Finished to copy origin component capabilities to its component instance, created {} new calculated capability relations", graphRelations.size());
875                 return Either.left(graphRelations);
876         }
877
878         private TitanOperationStatus associateCompInstToCapabilities(TitanVertex componentInstanceVertex, NodeTypeEnum containerNodeType, NodeTypeEnum compInstNodeType, String originId) {
879
880                 log.trace("Starting to copy origin component capabilities to its component instance");
881                 TitanOperationStatus status = TitanOperationStatus.OK;
882
883                 // case of VFC / CP / VL
884                 if (compInstNodeType.equals(NodeTypeEnum.Resource)) {
885                         status = createCaculatedRelationsFromAtomicResource(componentInstanceVertex, originId);
886                         if (!status.equals(TitanOperationStatus.OK)) {
887                                 return status;
888                         }
889                 }
890
891                 // case of VF / Service / Product
892                 status = createCalculatedCapabilityRelationsFromComponent(componentInstanceVertex, containerNodeType, compInstNodeType, originId);
893
894                 return status;
895         }
896
897         private void createCalculatedRequirementRelationsFromComponent(ComponentInstanceData componentInstanceData, NodeTypeEnum containerNodeType, NodeTypeEnum compInstNodeType, List<GraphRelation> graphRelations, String compInstOriginId) {
898
899                 Either<ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>>, TitanOperationStatus> componentInstancesOfComponent = getComponentInstancesOfComponent(compInstOriginId, containerNodeType, compInstNodeType);
900                 if (componentInstancesOfComponent.isLeft() && !componentInstancesOfComponent.left().value().left.isEmpty()) {
901                         List<ComponentInstance> componentInstances = componentInstancesOfComponent.left().value().left;
902                         for (ComponentInstance componentInstance : componentInstances) {
903                                 Either<List<ImmutablePair<RequirementData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(containerNodeType), componentInstance.getUniqueId(),
904                                                 GraphEdgeLabels.CALCULATED_REQUIREMENT, NodeTypeEnum.Requirement, RequirementData.class);
905
906                                 if (childrenNodes.isLeft() && !childrenNodes.left().value().isEmpty()) {
907                                         List<ImmutablePair<RequirementData, GraphEdge>> list = childrenNodes.left().value();
908                                         for (ImmutablePair<RequirementData, GraphEdge> calculatedReq : list) {
909
910                                                 GraphEdge edge = calculatedReq.right;
911                                                 Map<String, Object> properties = edge.getProperties();
912                                                 String source = null;
913                                                 String occurrences = RequirementDataDefinition.MAX_DEFAULT_OCCURRENCES;
914                                                 String minOccurrences = RequirementDataDefinition.MIN_OCCURRENCES;
915
916                                                 if (properties != null && properties.containsKey(GraphEdgePropertiesDictionary.SOURCE.getProperty())) {
917                                                         source = (String) properties.get(GraphEdgePropertiesDictionary.SOURCE.getProperty());
918                                                 }
919                                                 if (properties != null && properties.containsKey(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty())) {
920                                                         occurrences = (String) properties.get(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty());
921                                                 }
922                                                 if (properties != null && properties.containsKey(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty())) {
923                                                         minOccurrences = (String) properties.get(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty());
924                                                 }
925
926                                                 String capabilityName = (String) properties.get(GraphEdgePropertiesDictionary.NAME.getProperty());
927                                                 Either<GraphRelation, TitanOperationStatus> createRelation = createCalculatedRequirementEdge(componentInstanceData, source, capabilityName, calculatedReq.left, componentInstance, occurrences, minOccurrences);
928                                                 if (createRelation.isLeft()) {
929                                                         graphRelations.add(createRelation.left().value());
930                                                 }
931                                         }
932                                 }
933                         }
934                 }
935         }
936
937         private TitanOperationStatus createCalculatedRequirementRelationsFromComponent(TitanVertex componentInstanceVertex, NodeTypeEnum containerNodeType, NodeTypeEnum compInstNodeType, String compInstOriginId) {
938
939                 Either<ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>>, TitanOperationStatus> componentInstancesOfComponent = getComponentInstancesOfComponent(compInstOriginId, containerNodeType, compInstNodeType);
940                 if (componentInstancesOfComponent.isLeft() && !componentInstancesOfComponent.left().value().left.isEmpty()) {
941                         List<ComponentInstance> componentInstances = componentInstancesOfComponent.left().value().left;
942                         for (ComponentInstance componentInstance : componentInstances) {
943
944                                 Either<List<ImmutablePair<TitanVertex, Edge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenVertecies(UniqueIdBuilder.getKeyByNodeType(containerNodeType), componentInstance.getUniqueId(),
945                                                 GraphEdgeLabels.CALCULATED_REQUIREMENT);
946
947                                 if (childrenNodes.isLeft() && !childrenNodes.left().value().isEmpty()) {
948                                         List<ImmutablePair<TitanVertex, Edge>> list = childrenNodes.left().value();
949                                         for (ImmutablePair<TitanVertex, Edge> calculatedReq : list) {
950
951                                                 Edge edge = calculatedReq.right;
952                                                 Map<String, Object> properties = titanGenericDao.getProperties(edge);
953                                                 String source = null;
954                                                 String occurrences = RequirementDataDefinition.MAX_DEFAULT_OCCURRENCES;
955                                                 String minOccurrences = RequirementDataDefinition.MIN_OCCURRENCES;
956
957                                                 if (properties != null && properties.containsKey(GraphEdgePropertiesDictionary.SOURCE.getProperty())) {
958                                                         source = (String) properties.get(GraphEdgePropertiesDictionary.SOURCE.getProperty());
959                                                 }
960                                                 if (properties != null && properties.containsKey(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty())) {
961                                                         occurrences = (String) properties.get(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty());
962                                                 }
963                                                 if (properties != null && properties.containsKey(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty())) {
964                                                         minOccurrences = (String) properties.get(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty());
965                                                 }
966
967                                                 String capabilityName = (String) properties.get(GraphEdgePropertiesDictionary.NAME.getProperty());
968                                                 TitanOperationStatus createRelation = createCalculatedRequirementEdge(componentInstanceVertex, source, capabilityName, calculatedReq.left, componentInstance, occurrences, minOccurrences);
969                                                 if (!createRelation.equals(TitanOperationStatus.OK)) {
970                                                         log.debug("Failed to create calculated requirement edge, status ", createRelation);
971                                                         return createRelation;
972                                                 }
973                                         }
974                                 }
975                         }
976                 }
977                 return TitanOperationStatus.OK;
978         }
979
980         private void createCalculatedCapabilityRelationsFromComponent(ComponentInstanceData componentInstanceData, NodeTypeEnum containerNodeType, NodeTypeEnum compInstNodeType, List<GraphRelation> graphRelations, String compInstOriginId) {
981
982                 Either<ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>>, TitanOperationStatus> componentInstancesOfComponent = getComponentInstancesOfComponent(compInstOriginId, containerNodeType, compInstNodeType);
983                 if (componentInstancesOfComponent.isLeft() && !componentInstancesOfComponent.left().value().left.isEmpty()) {
984                         List<ComponentInstance> componentInstances = componentInstancesOfComponent.left().value().left;
985                         for (ComponentInstance componentInstance : componentInstances) {
986                                 Either<List<ImmutablePair<CapabilityData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(compInstNodeType), componentInstance.getUniqueId(),
987                                                 GraphEdgeLabels.CALCULATED_CAPABILITY, NodeTypeEnum.Capability, CapabilityData.class);
988
989                                 if (childrenNodes.isLeft() && !childrenNodes.left().value().isEmpty()) {
990                                         List<ImmutablePair<CapabilityData, GraphEdge>> list = childrenNodes.left().value();
991                                         for (ImmutablePair<CapabilityData, GraphEdge> calculatedCap : list) {
992
993                                                 GraphEdge edge = calculatedCap.right;
994                                                 Map<String, Object> properties = edge.getProperties();
995                                                 String source = null;
996                                                 if (properties != null && properties.containsKey(GraphEdgePropertiesDictionary.SOURCE.getProperty())) {
997                                                         source = (String) properties.get(GraphEdgePropertiesDictionary.SOURCE.getProperty());
998                                                 }
999                                                 String minOccurrences = CapabilityDataDefinition.MIN_OCCURRENCES;
1000                                                 String occurrences = CapabilityDataDefinition.MAX_OCCURRENCES;
1001                                                 if (properties != null && properties.containsKey(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty())) {
1002                                                         minOccurrences = (String) properties.get(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty());
1003                                                 }
1004                                                 if (properties != null && properties.containsKey(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty())) {
1005                                                         occurrences = (String) properties.get(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty());
1006                                                 }
1007
1008                                                 String capabilityName = (String) properties.get(GraphEdgePropertiesDictionary.NAME.getProperty());
1009                                                 Either<GraphRelation, TitanOperationStatus> createRelation = createCalculatedCapabilityEdge(componentInstanceData, source, capabilityName, calculatedCap.left, componentInstance.getUniqueId(), minOccurrences, occurrences);
1010                                                 if (createRelation.isLeft()) {
1011                                                         graphRelations.add(createRelation.left().value());
1012                                                 }
1013                                         }
1014                                 }
1015                         }
1016                 }
1017         }
1018
1019         private TitanOperationStatus createCalculatedCapabilityRelationsFromComponent(TitanVertex componentInstanceVertex, NodeTypeEnum containerNodeType, NodeTypeEnum compInstNodeType, String compInstOriginId) {
1020
1021                 Either<ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>>, TitanOperationStatus> componentInstancesOfComponent = getComponentInstancesOfComponent(compInstOriginId, containerNodeType, compInstNodeType);
1022                 if (componentInstancesOfComponent.isLeft() && !componentInstancesOfComponent.left().value().left.isEmpty()) {
1023                         List<ComponentInstance> componentInstances = componentInstancesOfComponent.left().value().left;
1024                         for (ComponentInstance componentInstance : componentInstances) {
1025                                 Either<List<ImmutablePair<TitanVertex, Edge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenVertecies(UniqueIdBuilder.getKeyByNodeType(compInstNodeType), componentInstance.getUniqueId(),
1026                                                 GraphEdgeLabels.CALCULATED_CAPABILITY);
1027
1028                                 if (childrenNodes.isLeft() && !childrenNodes.left().value().isEmpty()) {
1029                                         List<ImmutablePair<TitanVertex, Edge>> list = childrenNodes.left().value();
1030                                         for (ImmutablePair<TitanVertex, Edge> calculatedCap : list) {
1031
1032                                                 Edge edge = calculatedCap.right;
1033                                                 Map<String, Object> properties = titanGenericDao.getProperties(edge);
1034                                                 String source = null;
1035                                                 if (properties != null && properties.containsKey(GraphEdgePropertiesDictionary.SOURCE.getProperty())) {
1036                                                         source = (String) properties.get(GraphEdgePropertiesDictionary.SOURCE.getProperty());
1037                                                 }
1038                                                 String minOccurrences = CapabilityDataDefinition.MIN_OCCURRENCES;
1039                                                 String occurrences = CapabilityDataDefinition.MAX_OCCURRENCES;
1040                                                 if (properties != null && properties.containsKey(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty())) {
1041                                                         minOccurrences = (String) properties.get(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty());
1042                                                 }
1043                                                 if (properties != null && properties.containsKey(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty())) {
1044                                                         occurrences = (String) properties.get(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty());
1045                                                 }
1046
1047                                                 String capabilityName = (String) properties.get(GraphEdgePropertiesDictionary.NAME.getProperty());
1048                                                 TitanOperationStatus createRelation = createCalculatedCapabilityEdge(componentInstanceVertex, source, capabilityName, calculatedCap.left, componentInstance.getUniqueId(), minOccurrences, occurrences);
1049                                                 if (!createRelation.equals(TitanOperationStatus.OK)) {
1050                                                         return createRelation;
1051                                                 }
1052                                         }
1053                                 }
1054                         }
1055                 }
1056                 return TitanOperationStatus.OK;
1057         }
1058
1059         private void createCaculatedRelationsFromAtomicResource(ComponentInstanceData componentInstanceData, List<GraphRelation> graphRelations, String compInstOriginId) {
1060
1061                 Map<String, CapabilityDefinition> capabilities = new HashMap<String, CapabilityDefinition>();
1062                 Set<String> caseInsensitiveCapNames = new HashSet<>();
1063                 TitanOperationStatus getAllCapabilities = capabilityOperation.getAllCapabilitiesRecusive(NodeTypeEnum.Resource, compInstOriginId, true, capabilities, caseInsensitiveCapNames, true);
1064
1065                 if (!getAllCapabilities.equals(TitanOperationStatus.OK)) {
1066                         if (getAllCapabilities != TitanOperationStatus.NOT_FOUND) {
1067                                 log.debug("Couldn't fetch capabilities of component {}, error: {}", compInstOriginId, getAllCapabilities);
1068                                 return;
1069                         }
1070                 }
1071                 log.trace("Found {} capabilities for component {}, ", capabilities.size(), compInstOriginId);
1072                 for (Entry<String, CapabilityDefinition> capPair : capabilities.entrySet()) {
1073                         CapabilityDefinition capabilityData = capPair.getValue();
1074                         log.trace("Creating calculated capability relation from component instance {} to capability {}", componentInstanceData.getUniqueId(), capabilityData.getUniqueId());
1075                         CapabilityData capabilityDataNode = new CapabilityData();
1076                         capabilityDataNode.setUniqueId(capabilityData.getUniqueId());
1077                         String minOccurrences = CapabilityDataDefinition.MIN_OCCURRENCES;
1078                         String occurrences = CapabilityDataDefinition.MAX_OCCURRENCES;
1079                         if (capabilityData.getMinOccurrences() != null) {
1080                                 minOccurrences = capabilityData.getMinOccurrences();
1081                         }
1082                         if (capabilityData.getMinOccurrences() != null) {
1083                                 occurrences = capabilityData.getMaxOccurrences();
1084                         }
1085
1086                         Either<GraphRelation, TitanOperationStatus> createRelation = createCalculatedCapabilityEdge(componentInstanceData, compInstOriginId, capPair.getKey(), capabilityDataNode, componentInstanceData.getUniqueId(), minOccurrences, occurrences);
1087                         graphRelations.add(createRelation.left().value());
1088                 }
1089         }
1090
1091         private TitanOperationStatus createCaculatedRelationsFromAtomicResource(TitanVertex componentInstanceVertex, String compInstOriginId) {
1092
1093                 Map<String, CapabilityDefinition> capabilities = new HashMap<String, CapabilityDefinition>();
1094                 Set<String> caseInsensitiveCapNames = new HashSet<>();
1095                 TitanOperationStatus getAllCapabilities = capabilityOperation.getAllCapabilitiesRecusive(NodeTypeEnum.Resource, compInstOriginId, true, capabilities, caseInsensitiveCapNames, true);
1096
1097                 if (!getAllCapabilities.equals(TitanOperationStatus.OK)) {
1098                         if (getAllCapabilities != TitanOperationStatus.NOT_FOUND) {
1099                                 log.debug("Couldn't fetch capabilities of component {}, error: {}", compInstOriginId, getAllCapabilities);
1100                         }
1101                 }
1102                 log.trace("Found {} capabilities for component {}, ", capabilities.size(), compInstOriginId);
1103                 String compoInstId = (String) titanGenericDao.getProperty(componentInstanceVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty());
1104
1105                 for (Entry<String, CapabilityDefinition> capPair : capabilities.entrySet()) {
1106                         CapabilityDefinition capabilityData = capPair.getValue();
1107                         log.trace("Creating calculated capability relation from component instance {} to capability {}", compoInstId, capabilityData.getUniqueId());
1108                         CapabilityData capabilityDataNode = new CapabilityData();
1109                         capabilityDataNode.setUniqueId(capabilityData.getUniqueId());
1110                         String minOccurrences = CapabilityDataDefinition.MIN_OCCURRENCES;
1111                         String occurrences = CapabilityDataDefinition.MAX_OCCURRENCES;
1112                         if (capabilityData.getMinOccurrences() != null) {
1113                                 minOccurrences = capabilityData.getMinOccurrences();
1114                         }
1115                         if (capabilityData.getMinOccurrences() != null) {
1116                                 occurrences = capabilityData.getMaxOccurrences();
1117                         }
1118
1119                         TitanOperationStatus createRelation = createCalculatedCapabilityEdge(componentInstanceVertex, compInstOriginId, capPair.getKey(), capabilityDataNode, compoInstId, minOccurrences, occurrences);
1120                         if (!createRelation.equals(TitanOperationStatus.OK)) {
1121                                 return createRelation;
1122                         }
1123                 }
1124                 return TitanOperationStatus.OK;
1125         }
1126
1127         private Either<GraphRelation, TitanOperationStatus> createCalculatedCapabilityEdge(ComponentInstanceData componentInstanceData, String compInstOriginId, String capabilityName, CapabilityData capabilityDataNode, String componentInstanceId,
1128                         String minOccurrences, String occurrences) {
1129                 Map<String, Object> props = prepareEdgeCapabiltyProperites(compInstOriginId, capabilityName, componentInstanceId, minOccurrences, occurrences);
1130
1131                 Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(componentInstanceData, capabilityDataNode, GraphEdgeLabels.CALCULATED_CAPABILITY, props);
1132                 if (createRelation.isRight()) {
1133                         TitanOperationStatus titanOperationStatus = createRelation.right().value();
1134                         log.debug("Failed to create calculated capability from component instance {} to capability {}, error: {}", componentInstanceData.getUniqueId(), capabilityDataNode.getUniqueId(), titanOperationStatus);
1135                         return Either.right(titanOperationStatus);
1136                 }
1137                 return createRelation;
1138         }
1139
1140         private TitanOperationStatus createCalculatedCapabilityEdge(TitanVertex componentInstanceVertex, String compInstOriginId, String capabilityName, CapabilityData capabilityDataNode, String componentInstanceId, String minOccurrences,
1141                         String occurrences) {
1142                 Map<String, Object> props = prepareEdgeCapabiltyProperites(compInstOriginId, capabilityName, componentInstanceId, minOccurrences, occurrences);
1143
1144                 TitanOperationStatus createRelation = titanGenericDao.createEdge(componentInstanceVertex, capabilityDataNode, GraphEdgeLabels.CALCULATED_CAPABILITY, props);
1145                 if (!createRelation.equals(TitanOperationStatus.OK)) {
1146                         log.debug("Failed to create calculated capability from component instance {} to capability {}, error: {}", componentInstanceId, capabilityDataNode.getUniqueId(), createRelation);
1147                 }
1148                 return createRelation;
1149         }
1150
1151         private TitanOperationStatus createCalculatedCapabilityEdge(TitanVertex componentInstanceVertex, String compInstOriginId, String capabilityName, TitanVertex capabilityDataVertex, String componentInstanceId, String minOccurrences,
1152                         String occurrences) {
1153                 Map<String, Object> props = prepareEdgeCapabiltyProperites(compInstOriginId, capabilityName, componentInstanceId, minOccurrences, occurrences);
1154
1155                 TitanOperationStatus createRelation = titanGenericDao.createEdge(componentInstanceVertex, capabilityDataVertex, GraphEdgeLabels.CALCULATED_CAPABILITY, props);
1156                 if (!createRelation.equals(TitanOperationStatus.OK)) {
1157                         log.debug("Failed to create calculated capability from component instance {} to capability {}, error: {}", componentInstanceId, capabilityName, createRelation);
1158                 }
1159                 return createRelation;
1160         }
1161
1162         private Map<String, Object> prepareEdgeCapabiltyProperites(String compInstOriginId, String capabilityName, String componentInstanceId, String minOccurrences, String occurrences) {
1163                 Map<String, Object> props = new HashMap<String, Object>();
1164                 if (capabilityName != null)
1165                         props.put(GraphEdgePropertiesDictionary.NAME.getProperty(), capabilityName);
1166                 if (compInstOriginId != null)
1167                         props.put(GraphEdgePropertiesDictionary.SOURCE.getProperty(), compInstOriginId);
1168                 if (componentInstanceId != null) {
1169                         props.put(GraphEdgePropertiesDictionary.OWNER_ID.getProperty(), componentInstanceId);
1170                 }
1171                 props.put(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty(), minOccurrences);
1172                 props.put(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty(), occurrences);
1173                 return props;
1174         }
1175
1176         private Either<GraphRelation, TitanOperationStatus> createCalculatedRequirementEdge(ComponentInstanceData componentInstanceData, String compInstOriginId, String capabilityName, RequirementData requirementData, ComponentInstance componentInstance,
1177                         String occurrences, String minOccurrences) {
1178                 Map<String, Object> props = new HashMap<String, Object>();
1179                 if (capabilityName != null)
1180                         props.put(GraphEdgePropertiesDictionary.NAME.getProperty(), capabilityName);
1181                 if (compInstOriginId != null)
1182                         props.put(GraphEdgePropertiesDictionary.SOURCE.getProperty(), compInstOriginId);
1183                 if (componentInstance != null) {
1184                         props.put(GraphEdgePropertiesDictionary.OWNER_ID.getProperty(), componentInstance.getUniqueId());
1185                 }
1186                 props.put(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty(), occurrences);
1187                 props.put(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty(), minOccurrences);
1188
1189                 Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(componentInstanceData, requirementData, GraphEdgeLabels.CALCULATED_REQUIREMENT, props);
1190                 if (createRelation.isRight()) {
1191                         TitanOperationStatus titanOperationStatus = createRelation.right().value();
1192                         log.debug("Failed to create calculated requirement from component instance {} to requirement {}, error: {}", componentInstanceData.getUniqueId(), requirementData.getUniqueId(), titanOperationStatus);
1193                         return Either.right(titanOperationStatus);
1194                 }
1195                 return createRelation;
1196         }
1197
1198         private TitanOperationStatus createCalculatedRequirementEdge(TitanVertex componentInstanceVertex, String compInstOriginId, String capabilityName, TitanVertex requirementVertex, ComponentInstance componentInstance, String occurrences,
1199                         String minOccurrences) {
1200                 Map<String, Object> props = new HashMap<String, Object>();
1201                 if (capabilityName != null)
1202                         props.put(GraphEdgePropertiesDictionary.NAME.getProperty(), capabilityName);
1203                 if (compInstOriginId != null)
1204                         props.put(GraphEdgePropertiesDictionary.SOURCE.getProperty(), compInstOriginId);
1205                 if (componentInstance != null) {
1206                         props.put(GraphEdgePropertiesDictionary.OWNER_ID.getProperty(), componentInstance.getUniqueId());
1207                 }
1208                 props.put(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty(), occurrences);
1209                 props.put(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty(), minOccurrences);
1210
1211                 TitanOperationStatus createRelation = titanGenericDao.createEdge(componentInstanceVertex, requirementVertex, GraphEdgeLabels.CALCULATED_REQUIREMENT, props);
1212                 if (!createRelation.equals(TitanOperationStatus.OK)) {
1213                         log.debug("Failed to create calculated requirement from component instance {} to requirement {}, error: {}", componentInstance.getUniqueId(), capabilityName, createRelation);
1214                         return createRelation;
1215                 }
1216                 return createRelation;
1217         }
1218
1219         /**
1220          * Make a relation between service to resource instance.
1221          * 
1222          * @param containerCompIdData
1223          * @param componentInstanceData
1224          * @param logicalName
1225          * @return
1226          */
1227         private Either<GraphRelation, TitanOperationStatus> associateContainerCompToComponentInstance(UniqueIdData containerCompIdData, ComponentInstanceData componentInstanceData, String logicalName) {
1228                 Map<String, Object> properties = new HashMap<String, Object>();
1229
1230                 properties.put(GraphPropertiesDictionary.NAME.getProperty(), logicalName);
1231                 Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(containerCompIdData, componentInstanceData, GraphEdgeLabels.RESOURCE_INST, properties);
1232
1233                 log.debug("After associating container component {} to resource instance {} with logical name {}. Status is {}", containerCompIdData.getUniqueId(), componentInstanceData.getUniqueId(), logicalName, createRelation);
1234
1235                 return createRelation;
1236         }
1237
1238         private TitanOperationStatus associateContainerCompToComponentInstance(TitanVertex containerCompVertex, TitanVertex componentInstanceVertex, String logicalName) {
1239                 Map<String, Object> properties = new HashMap<String, Object>();
1240
1241                 properties.put(GraphPropertiesDictionary.NAME.getProperty(), logicalName);
1242                 TitanOperationStatus createRelation = titanGenericDao.createEdge(containerCompVertex, componentInstanceVertex, GraphEdgeLabels.RESOURCE_INST, properties);
1243
1244                 return createRelation;
1245         }
1246
1247         @Override
1248         public String createComponentInstLogicalName(String instanceNumber, String componentInstanceName) {
1249
1250                 String logicalName = buildComponentInstanceLogicalName(instanceNumber, componentInstanceName);
1251
1252                 return logicalName;
1253         }
1254
1255         private String buildComponentInstanceLogicalName(String instanceNumber, String lastToken) {
1256                 return lastToken + " " + (instanceNumber == null ? 0 : instanceNumber);
1257         }
1258
1259         private ComponentInstanceData buildComponentInstanceData(ComponentInstance resourceInstance, String componentId, String logicalName) {
1260
1261                 String ciOriginComponentUid = resourceInstance.getComponentUid();
1262
1263                 ComponentInstanceDataDefinition dataDefinition = new ComponentInstanceDataDefinition(resourceInstance);
1264
1265                 Long creationDate = resourceInstance.getCreationTime();
1266                 if (creationDate == null) {
1267                         creationDate = System.currentTimeMillis();
1268                 }
1269                 dataDefinition.setCreationTime(creationDate);
1270                 dataDefinition.setModificationTime(creationDate);
1271                 // dataDefinition.setResourceUid(resourceUid);
1272                 // String replacmentlogicalName = logicalName.replaceAll(" ",
1273                 // "_").toLowerCase();
1274                 dataDefinition.setName(logicalName);
1275                 if (dataDefinition.getNormalizedName() == null)
1276                         dataDefinition.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(logicalName));
1277                 dataDefinition.setUniqueId(UniqueIdBuilder.buildResourceInstanceUniuqeId(componentId, ciOriginComponentUid, dataDefinition.getNormalizedName()));
1278
1279                 ComponentInstanceData resourceInstanceData = new ComponentInstanceData(dataDefinition);
1280
1281                 return resourceInstanceData;
1282         }
1283
1284         public Either<ComponentInstance, TitanOperationStatus> removeComponentInstanceFromComponent(NodeTypeEnum containerNodeType, String containerComponentId, String componentInstanceUid) {
1285
1286                 log.debug("Going to delete component instance {} under component {}", componentInstanceUid, containerComponentId);
1287
1288                 Either<ComponentInstanceData, TitanOperationStatus> node = findResourceInstance(componentInstanceUid);
1289
1290                 if (node.isRight()) {
1291                         TitanOperationStatus status = node.right().value();
1292                         BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "Remove Component Instance");
1293                         BeEcompErrorManager.getInstance().logBeDaoSystemError("Remove Component Instance");
1294                         log.debug("Failed to delete component instance {}. status is {}", componentInstanceUid, status);
1295                         return Either.right(status);
1296                 }
1297
1298                 TitanOperationStatus isComponentInstOfComponent = verifyResourceInstanceUnderComponent(containerNodeType, containerComponentId, componentInstanceUid);
1299                 if (isComponentInstOfComponent != TitanOperationStatus.OK) {
1300                         return Either.right(isComponentInstOfComponent);
1301                 }
1302
1303                 TitanOperationStatus status = deleteOutgoingRelationships(containerNodeType, containerComponentId, componentInstanceUid);
1304                 if (status != TitanOperationStatus.OK) {
1305                         return Either.right(status);
1306                 }
1307                 status = deleteIncomingRelationships(containerNodeType, containerComponentId, componentInstanceUid);
1308                 if (status != TitanOperationStatus.OK) {
1309                         return Either.right(status);
1310                 }
1311
1312                 // delete associated properties
1313                 status = deleteAssociatedProperties(componentInstanceUid);
1314                 if (status != TitanOperationStatus.OK) {
1315                         return Either.right(status);
1316                 }
1317                 // delete associated properties
1318                 status = deleteAssociatedAttributes(componentInstanceUid);
1319                 if (status != TitanOperationStatus.OK) {
1320                         return Either.right(status);
1321                 }
1322
1323                 // delete associated artifacts
1324                 status = deleteAssociatedArtifacts(componentInstanceUid);
1325                 if (status != TitanOperationStatus.OK) {
1326                         return Either.right(status);
1327                 }
1328
1329                 // delete associated capability instances
1330                 if (containerNodeType.equals(NodeTypeEnum.Resource)) {
1331                         status = deleteAssociatedCapabilityInstances(componentInstanceUid);
1332                         if (status != TitanOperationStatus.OK) {
1333                                 return Either.right(status);
1334                         }
1335                 }
1336
1337                 // delete associated properties
1338                 status = deleteAssociatedGroupInstances(componentInstanceUid);
1339                 if (status != TitanOperationStatus.OK) {
1340                         return Either.right(status);
1341                 }
1342
1343                 Either<ComponentInstanceData, TitanOperationStatus> deleteRI = titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), componentInstanceUid, ComponentInstanceData.class);
1344
1345                 if (deleteRI.isRight()) {
1346                         TitanOperationStatus deleteRiStatus = deleteRI.right().value();
1347                         log.error("Failed to delete resource instance {}. status is {}", componentInstanceUid, deleteRiStatus);
1348                         return Either.right(deleteRiStatus);
1349                 }
1350
1351                 ComponentInstanceData deletedResourceInst = deleteRI.left().value();
1352
1353                 ComponentInstance resourceInstance = new ComponentInstance(deletedResourceInst.getComponentInstDataDefinition());
1354
1355                 return Either.left(resourceInstance);
1356         }
1357
1358         private TitanOperationStatus deleteAssociatedGroupInstances(String componentInstanceUid) {
1359
1360                 return this.groupInstanceOperation.deleteAllGroupInstances(componentInstanceUid);
1361         }
1362
1363         private TitanOperationStatus deleteAssociatedCapabilityInstances(String resourceInstanceId) {
1364                 TitanOperationStatus status = TitanOperationStatus.OK;
1365
1366                 log.debug("Before deleting all capability instances of component istance {}.", resourceInstanceId);
1367                 Either<List<ImmutablePair<CapabilityInstData, GraphEdge>>, TitanOperationStatus> getCapabilityInstancesRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceId,
1368                                 GraphEdgeLabels.CAPABILITY_INST, NodeTypeEnum.CapabilityInst, CapabilityInstData.class);
1369
1370                 if (getCapabilityInstancesRes.isRight() && !getCapabilityInstancesRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
1371                         status = getCapabilityInstancesRes.right().value();
1372                         log.debug("Failed to retrieve capability Instances of resource instance {}. Status is {}", resourceInstanceId, status);
1373                 }
1374                 if (getCapabilityInstancesRes.isLeft()) {
1375                         for (ImmutablePair<CapabilityInstData, GraphEdge> capabilityInstancePair : getCapabilityInstancesRes.left().value()) {
1376                                 Either<CapabilityInstData, TitanOperationStatus> deleteCababilityInstanceRes = capabilityInstanceOperation.deleteCapabilityInstanceFromResourceInstance(resourceInstanceId, capabilityInstancePair.getLeft().getUniqueId());
1377                                 if (deleteCababilityInstanceRes.isRight()) {
1378                                         status = deleteCababilityInstanceRes.right().value();
1379                                 }
1380                         }
1381                 }
1382                 log.debug("After deleting all capability instances of component istance {}. Status is {}", resourceInstanceId, status);
1383                 return status;
1384         }
1385
1386         private TitanOperationStatus deleteAssociatedArtifacts(String resourceInstanceUid) {
1387
1388                 Either<List<ImmutablePair<ArtifactData, GraphEdge>>, TitanOperationStatus> artifactRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceUid, GraphEdgeLabels.ARTIFACT_REF,
1389                                 NodeTypeEnum.ArtifactRef, ArtifactData.class);
1390
1391                 if (artifactRes.isRight()) {
1392                         TitanOperationStatus status = artifactRes.right().value();
1393                         if (status != TitanOperationStatus.NOT_FOUND) {
1394                                 log.error("Failed to find artifacts of resource instance {}. status is {}", resourceInstanceUid, status);
1395                                 return status;
1396                         }
1397                 } else {
1398
1399                         List<ImmutablePair<ArtifactData, GraphEdge>> artifactPairs = artifactRes.left().value();
1400                         for (ImmutablePair<ArtifactData, GraphEdge> pair : artifactPairs) {
1401                                 String uniqueId = (String) pair.left.getUniqueId();
1402                                 Either<ArtifactData, TitanOperationStatus> removeArifactFromGraph = artifactOperation.removeArtifactOnGraph(resourceInstanceUid, uniqueId, NodeTypeEnum.ResourceInstance, true);
1403                                 if (removeArifactFromGraph.isRight()) {
1404                                         TitanOperationStatus status = removeArifactFromGraph.right().value();
1405                                         log.error("Failed to delete artifact of resource instance {}. status is {}", resourceInstanceUid, status);
1406                                         return status;
1407                                 }
1408
1409                         }
1410                 }
1411
1412                 return TitanOperationStatus.OK;
1413
1414         }
1415
1416         private TitanOperationStatus deleteAssociatedProperties(String resourceInstanceUid) {
1417                 final GraphEdgeLabels edgeConectingToRI = GraphEdgeLabels.PROPERTY_VALUE;
1418                 final NodeTypeEnum elementTypeToDelete = NodeTypeEnum.PropertyValue;
1419                 return deleteAssociatedRIElements(elementTypeToDelete, edgeConectingToRI, resourceInstanceUid, () -> PropertyValueData.class);
1420
1421         }
1422
1423         private TitanOperationStatus deleteAssociatedAttributes(String resourceInstanceUid) {
1424                 final GraphEdgeLabels edgeConectingToRI = GraphEdgeLabels.ATTRIBUTE_VALUE;
1425                 final NodeTypeEnum elementTypeToDelete = NodeTypeEnum.AttributeValue;
1426                 return deleteAssociatedRIElements(elementTypeToDelete, edgeConectingToRI, resourceInstanceUid, () -> AttributeValueData.class);
1427         }
1428
1429         private <T extends GraphNode> TitanOperationStatus deleteAssociatedRIElements(NodeTypeEnum elementTypeToDelete, GraphEdgeLabels edgeConectingToRI, String resourceInstanceUid, Supplier<Class<T>> classGen) {
1430
1431                 Either<List<ImmutablePair<T, GraphEdge>>, TitanOperationStatus> elementsNodesRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceUid, edgeConectingToRI, elementTypeToDelete,
1432                                 classGen.get());
1433
1434                 if (elementsNodesRes.isRight()) {
1435                         TitanOperationStatus status = elementsNodesRes.right().value();
1436                         if (status != TitanOperationStatus.NOT_FOUND) {
1437                                 BeEcompErrorManager.getInstance().logInternalFlowError("deleteAssociatedRIElements", "Failed to find the elements of resource instance " + resourceInstanceUid + ". status is " + status, ErrorSeverity.ERROR);
1438                                 return status;
1439                         }
1440                 } else {
1441
1442                         List<ImmutablePair<T, GraphEdge>> relationshipNodes = elementsNodesRes.left().value();
1443                         if (relationshipNodes != null) {
1444                                 for (ImmutablePair<T, GraphEdge> immutablePair : relationshipNodes) {
1445                                         T elementValueDataData = immutablePair.getKey();
1446                                         Either<T, TitanOperationStatus> deleteNode = titanGenericDao.deleteNode(elementValueDataData, classGen.get());
1447                                         if (deleteNode.isRight()) {
1448                                                 TitanOperationStatus status = deleteNode.right().value();
1449                                                 BeEcompErrorManager.getInstance().logInternalFlowError("deleteAssociatedRIElements", "Failed to delete element value node " + elementValueDataData + ". status is " + status, ErrorSeverity.ERROR);
1450                                                 return status;
1451                                         }
1452                                 }
1453                         }
1454
1455                 }
1456
1457                 return TitanOperationStatus.OK;
1458         }
1459
1460         /**
1461          * delete all relationship instance nodes which has an outgoing edge to a given resource instance
1462          * 
1463          * @param resourceInstanceUid
1464          * @return
1465          */
1466         private TitanOperationStatus deleteIncomingRelationships(NodeTypeEnum componentType, String componentId, String resourceInstanceUid) {
1467
1468                 Either<List<RequirementCapabilityRelDef>, TitanOperationStatus> relationsForTarget = getRelationsForTarget(resourceInstanceUid);
1469                 if (relationsForTarget.isRight()) {
1470                         TitanOperationStatus status = relationsForTarget.right().value();
1471                         if (status != TitanOperationStatus.NOT_FOUND) {
1472                                 log.error("Failed to find the relationships of resource instance {}. status is {}", resourceInstanceUid, status);
1473                                 return status;
1474                         }
1475                 } else {
1476                         List<RequirementCapabilityRelDef> relList = relationsForTarget.left().value();
1477                         for (RequirementCapabilityRelDef relation : relList) {
1478                                 Either<RequirementCapabilityRelDef, StorageOperationStatus> dissociateResourceInstances = dissociateResourceInstances(componentId, componentType, relation, true);
1479                                 if (dissociateResourceInstances.isRight()) {
1480                                         log.error("failed to diassociate component instance {} and component instance {} under component {}. error is {}", relation.getFromNode(), relation.getToNode(), componentId);
1481                                         return TitanOperationStatus.GENERAL_ERROR;
1482                                 }
1483                         }
1484                 }
1485                 return TitanOperationStatus.OK;
1486         }
1487
1488         /**
1489          * delete all relationship instance nodes which has an incoming edge from a given resource instance
1490          * 
1491          * @param resourceInstanceUid
1492          * @return
1493          */
1494         private TitanOperationStatus deleteOutgoingRelationships(NodeTypeEnum componentType, String componentId, String resourceInstanceUid) {
1495
1496                 Either<List<RequirementCapabilityRelDef>, TitanOperationStatus> relationsForSource = getRelationsForSource(resourceInstanceUid);
1497                 if (relationsForSource.isRight()) {
1498                         TitanOperationStatus status = relationsForSource.right().value();
1499                         if (status != TitanOperationStatus.NOT_FOUND) {
1500                                 log.error("Failed to find the relationships of resource instance {}. status is {}", resourceInstanceUid, status);
1501                                 return status;
1502                         }
1503                 } else {
1504                         List<RequirementCapabilityRelDef> relList = relationsForSource.left().value();
1505                         for (RequirementCapabilityRelDef relation : relList) {
1506                                 Either<RequirementCapabilityRelDef, StorageOperationStatus> dissociateResourceInstances = dissociateResourceInstances(componentId, componentType, relation, true);
1507                                 if (dissociateResourceInstances.isRight()) {
1508                                         log.error("failed to diassociate component instance {} and component instance {} under component {}. error is {}", relation.getFromNode(), relation.getToNode(), componentId);
1509                                         return TitanOperationStatus.GENERAL_ERROR;
1510                                 }
1511                         }
1512                 }
1513                 return TitanOperationStatus.OK;
1514         }
1515
1516         /**
1517          * delete relationship instance nodes
1518          * 
1519          * @param relationshipNodes
1520          * @return
1521          */
1522         private TitanOperationStatus deleteRelationshipNodes(List<ImmutablePair<RelationshipInstData, GraphEdge>> relationshipNodes) {
1523
1524                 if (relationshipNodes != null) {
1525                         for (ImmutablePair<RelationshipInstData, GraphEdge> immutablePair : relationshipNodes) {
1526                                 RelationshipInstData relationshipTypeImplData = immutablePair.getKey();
1527                                 Either<RelationshipInstData, TitanOperationStatus> deleteNode = titanGenericDao.deleteNode(relationshipTypeImplData, RelationshipInstData.class);
1528                                 if (deleteNode.isRight()) {
1529                                         TitanOperationStatus status = deleteNode.right().value();
1530                                         log.error("Failed to delete relationship node {}. status is {}", relationshipTypeImplData, status);
1531                                         return status;
1532                                 }
1533                         }
1534                 }
1535
1536                 return TitanOperationStatus.OK;
1537         }
1538
1539         public Either<List<RelationshipInstData>, TitanOperationStatus> disconnectResourcesInService(String componentId, NodeTypeEnum nodeType, RequirementCapabilityRelDef requirementDef) {
1540
1541                 if (requirementDef.getRelationships() == null) {
1542                         log.debug("No relation pair in request [ {} ]", requirementDef);
1543                         return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
1544                 }
1545
1546                 String fromResInstanceUid = requirementDef.getFromNode();
1547                 String toResInstanceUid = requirementDef.getToNode();
1548
1549                 // DE191707
1550                 TitanOperationStatus isResourceInstOfService = verifyResourceInstanceUnderComponent(nodeType, componentId, fromResInstanceUid);
1551                 if (isResourceInstOfService != TitanOperationStatus.OK) {
1552                         return Either.right(isResourceInstOfService);
1553                 }
1554                 isResourceInstOfService = verifyResourceInstanceUnderComponent(nodeType, componentId, toResInstanceUid);
1555                 if (isResourceInstOfService != TitanOperationStatus.OK) {
1556                         return Either.right(isResourceInstOfService);
1557                 }
1558
1559                 List<RequirementAndRelationshipPair> relationPairList = requirementDef.getRelationships();
1560
1561                 Either<TitanVertex, TitanOperationStatus> riFrom = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), fromResInstanceUid);
1562                 if (riFrom.isRight()) {
1563                         log.debug("Failed to fetch component instance {}. error {}", fromResInstanceUid, riFrom.right().value());
1564                         return Either.right(riFrom.right().value());
1565                 }
1566                 Iterator<Edge> edgeIter = riFrom.left().value().edges(Direction.OUT, GraphEdgeLabels.RELATIONSHIP_INST.getProperty());
1567                 if (edgeIter == null) {
1568                         log.debug("No edges with label {} for owner RI {}", GraphEdgeLabels.CALCULATED_REQUIREMENT_FULLFILLED.getProperty(), fromResInstanceUid);
1569                         return Either.right(TitanOperationStatus.NOT_FOUND);
1570                 }
1571                 List<RelationshipInstData> deletedRelations = new ArrayList<>();
1572                 Set<String> vertexToDelete = new HashSet<String>();
1573                 while (edgeIter.hasNext()) {
1574                         TitanEdge edge = (TitanEdge) edgeIter.next();
1575                         String name = (String) edge.property(GraphEdgePropertiesDictionary.NAME.getProperty()).value();
1576                         for (RequirementAndRelationshipPair relationPair : relationPairList) {
1577                                 if (relationPair.getRequirement().equals(name)) {
1578                                         TitanVertex inVertex = edge.inVertex();
1579                                         String requirementId = (String) titanGenericDao.getProperty(inVertex, GraphPropertiesDictionary.REQUIREMENT_ID.getProperty());
1580                                         String capabiltyId = (String) titanGenericDao.getProperty(inVertex, GraphPropertiesDictionary.CAPABILITY_ID.getProperty());
1581                                         String requirementOwnerId = (String) titanGenericDao.getProperty(inVertex, GraphPropertiesDictionary.REQUIREMENT_OWNER_ID.getProperty());
1582                                         String capabiltyOwnerId = (String) titanGenericDao.getProperty(inVertex, GraphPropertiesDictionary.CAPABILITY_OWNER_ID.getProperty());
1583                                         String relationVertexId = (String) titanGenericDao.getProperty(inVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty());
1584
1585                                         // verify vs requirement id and owner ids. ( for
1586                                         // requirements with same name)
1587                                         if (requirementId.equals(relationPair.getRequirementUid()) && capabiltyId.equals(relationPair.getCapabilityUid()) && requirementOwnerId.equals(relationPair.getRequirementOwnerId())
1588                                                         && capabiltyOwnerId.equals(relationPair.getCapabilityOwnerId())) {
1589                                                 vertexToDelete.add(relationVertexId);
1590                                         }
1591                                 }
1592                         }
1593                 }
1594                 log.debug("relation node with ids: {} are going to be deleted", vertexToDelete);
1595                 for (String relationVertexId : vertexToDelete) {
1596                         // remove relation vertex
1597                         Either<RelationshipInstData, TitanOperationStatus> relationNode = titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.RelationshipInst), relationVertexId, RelationshipInstData.class);
1598                         if (relationNode.isRight()) {
1599                                 log.debug("Failed to delete relation node with id {}. error {}", relationVertexId, relationNode.right().value());
1600                                 return Either.right(relationNode.right().value());
1601                         }
1602                         RelationshipInstData deletedRelation = relationNode.left().value();
1603                         deletedRelations.add(deletedRelation);
1604                 }
1605                 if (deletedRelations.size() > 0) {
1606                         return Either.left(deletedRelations);
1607                 }
1608                 return Either.right(TitanOperationStatus.NOT_FOUND);
1609         }
1610
1611         @Override
1612         public Either<RequirementCapabilityRelDef, StorageOperationStatus> dissociateResourceInstances(String componentId, NodeTypeEnum nodeType, RequirementCapabilityRelDef requirementDef, boolean inTransaction) {
1613
1614                 String fromResInstanceUid = requirementDef.getFromNode();
1615                 String toResInstanceUid = requirementDef.getToNode();
1616                 String requirement = requirementDef.getRelationships().get(0).getRequirement();
1617                 Either<RequirementCapabilityRelDef, StorageOperationStatus> result = null;
1618                 try {
1619
1620                         Either<List<RelationshipInstData>, TitanOperationStatus> dissociateRes = disconnectResourcesInService(componentId, nodeType, requirementDef);
1621                         if (dissociateRes.isRight()) {
1622                                 TitanOperationStatus status = dissociateRes.right().value();
1623                                 log.error("Failed to dissociate resource instance {} from resource instance {} in service {}. status is {}", fromResInstanceUid, toResInstanceUid, componentId, status);
1624                                 BeEcompErrorManager.getInstance().logBeDaoSystemError("dissociateComponentInstances");
1625                                 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
1626                                 return result;
1627                         }
1628                         StorageOperationStatus updateCalculatedCapReqResult = updateCalculatedCapReq(requirementDef, false);
1629                         if (!updateCalculatedCapReqResult.equals(StorageOperationStatus.OK)) {
1630                                 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "dissociateComponentInstances");
1631                                 BeEcompErrorManager.getInstance().logBeDaoSystemError("dissociateComponentInstances");
1632                                 log.debug("Failed to dissociate component instances. {}. status is {}", requirementDef, updateCalculatedCapReqResult);
1633                                 result = Either.right(updateCalculatedCapReqResult);
1634                                 return result;
1635                         }
1636
1637                         StorageOperationStatus status;
1638                         status = updateCustomizationUUID(requirementDef.getFromNode());
1639                         if (status != StorageOperationStatus.OK) {
1640                                 result = Either.right(status);
1641                                 return result;
1642                         }
1643                         status = updateCustomizationUUID(requirementDef.getToNode());
1644                         if (status != StorageOperationStatus.OK) {
1645                                 result = Either.right(status);
1646                                 return result;
1647                         }
1648
1649                         List<RelationshipInstData> relationshipInstData = dissociateRes.left().value();
1650                         RequirementCapabilityRelDef capabilityRelDef = buildCapabilityResult(fromResInstanceUid, toResInstanceUid, requirement, relationshipInstData);
1651
1652                         result = Either.left(capabilityRelDef);
1653
1654                         return result;
1655
1656                 } finally {
1657                         if (false == inTransaction) {
1658                                 commitOrRollback(result);
1659                         }
1660                 }
1661
1662         }
1663
1664         private StorageOperationStatus updateCalculatedCapReq(RequirementCapabilityRelDef capabilityRelDef, boolean associate) {
1665                 GraphEdgeLabels requirmentNewLabel = associate ? GraphEdgeLabels.CALCULATED_REQUIREMENT_FULLFILLED : GraphEdgeLabels.CALCULATED_REQUIREMENT;
1666
1667                 GraphEdgeLabels requirmentCurrentLabel = associate ? GraphEdgeLabels.CALCULATED_REQUIREMENT : GraphEdgeLabels.CALCULATED_REQUIREMENT_FULLFILLED;
1668
1669                 GraphEdgeLabels capabilityNewLabel = associate ? GraphEdgeLabels.CALCULATED_CAPABILITY_FULLFILLED : GraphEdgeLabels.CALCULATED_CAPABILITY;
1670
1671                 GraphEdgeLabels capabilityCurrentLabel = associate ? GraphEdgeLabels.CALCULATED_CAPABILITY : GraphEdgeLabels.CALCULATED_CAPABILITY_FULLFILLED;
1672
1673                 List<RequirementAndRelationshipPair> relationships = capabilityRelDef.getRelationships();
1674                 for (RequirementAndRelationshipPair pair : relationships) {
1675                         StorageOperationStatus status = updateRequirementEdges(requirmentNewLabel, requirmentCurrentLabel, pair, capabilityRelDef.getFromNode());
1676                         if (!status.equals(StorageOperationStatus.OK)) {
1677                                 return status;
1678                         }
1679                         status = updateCapabiltyEdges(capabilityNewLabel, capabilityCurrentLabel, pair, capabilityRelDef.getToNode());
1680                         if (!status.equals(StorageOperationStatus.OK)) {
1681                                 return status;
1682                         }
1683                 }
1684                 return StorageOperationStatus.OK;
1685         }
1686
1687         private StorageOperationStatus updateRequirementEdges(GraphEdgeLabels requirmentNewLabel, GraphEdgeLabels requirmentCurrentLabel, RequirementAndRelationshipPair pair, String requirementOwnerId) {
1688                 Either<TitanVertex, TitanOperationStatus> reqOwnerRI = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), requirementOwnerId);
1689                 if (reqOwnerRI.isRight()) {
1690                         log.debug("Failed to fetch requirment Owner by Id {}  error {}", requirementOwnerId, reqOwnerRI.right().value());
1691                         return DaoStatusConverter.convertTitanStatusToStorageStatus(reqOwnerRI.right().value());
1692                 }
1693                 Iterator<Edge> edgeIter = reqOwnerRI.left().value().edges(Direction.OUT, requirmentCurrentLabel.name(), requirmentNewLabel.name());
1694                 if (edgeIter == null) {
1695                         log.debug("No edges with label {} for owner RI {}", requirmentCurrentLabel, requirementOwnerId);
1696                         return StorageOperationStatus.GENERAL_ERROR;
1697                 }
1698                 boolean associate = requirmentNewLabel.equals(GraphEdgeLabels.CALCULATED_REQUIREMENT_FULLFILLED) ? true : false;
1699                 while (edgeIter.hasNext()) {
1700                         TitanEdge edge = (TitanEdge) edgeIter.next();
1701                         String name = (String) edge.property(GraphEdgePropertiesDictionary.NAME.getProperty()).value();
1702                         if (pair.getRequirement().equals(name)) {
1703                                 TitanVertex reqVertex = edge.inVertex();
1704                                 String requirementId = (String) titanGenericDao.getProperty(reqVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty());
1705                                 // verify vs requirement id . ( for requirements with same name)
1706                                 if (requirementId.equals(pair.getRequirementUid())) {
1707                                         String ownerIdOnEdge = (String) edge.value(GraphEdgePropertiesDictionary.OWNER_ID.getProperty());
1708                                         if (ownerIdOnEdge.equals(pair.getRequirementOwnerId())) {
1709                                                 String requiredOccurrences = (String) titanGenericDao.getProperty(edge, GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty());
1710                                                 String leftOccurrences = (String) titanGenericDao.getProperty(edge, GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty());
1711
1712                                                 String requiredOccurrencesNew = "0";
1713                                                 String leftOccurrencesNew = RequirementDataDefinition.MAX_DEFAULT_OCCURRENCES;
1714                                                 if (requiredOccurrences != null) {
1715                                                         Integer iOccurrences = Integer.parseInt(requiredOccurrences);
1716                                                         if (associate) {
1717                                                                 if (iOccurrences > 0) {
1718                                                                         iOccurrences--;
1719                                                                         requiredOccurrencesNew = iOccurrences.toString();
1720                                                                 }
1721                                                         } else {
1722                                                                 String reqMinOccurrences = (String) titanGenericDao.getProperty(reqVertex, GraphPropertiesDictionary.MIN_OCCURRENCES.getProperty());
1723                                                                 if (reqMinOccurrences == null) {
1724                                                                         reqMinOccurrences = RequirementDataDefinition.MIN_OCCURRENCES;
1725                                                                 }
1726                                                                 if (Integer.parseInt(reqMinOccurrences) > iOccurrences) {
1727                                                                         iOccurrences++;
1728                                                                         requiredOccurrencesNew = iOccurrences.toString();
1729                                                                 }
1730                                                         }
1731                                                 }
1732                                                 Map<String, Object> properties = titanGenericDao.getProperties(edge);
1733                                                 properties.put(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty(), requiredOccurrencesNew);
1734
1735                                                 if (leftOccurrences != null && !leftOccurrences.equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
1736                                                         Integer iOccurrences = Integer.parseInt(leftOccurrences);
1737                                                         if (associate) {
1738                                                                 if (iOccurrences > 0) {
1739                                                                         iOccurrences--;
1740                                                                 }
1741                                                         } else {
1742                                                                 iOccurrences++;
1743                                                         }
1744                                                         leftOccurrencesNew = iOccurrences.toString();
1745                                                         properties.put(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty(), leftOccurrencesNew);
1746                                                         if ((associate && iOccurrences == 0) || (!associate && iOccurrences == 1)) {
1747                                                                 // move edge to full filled state
1748                                                                 TitanVertex outVertex = edge.outVertex();
1749                                                                 TitanEdge newEdge = outVertex.addEdge(requirmentNewLabel.getProperty(), reqVertex);
1750                                                                 titanGenericDao.setProperties(newEdge, properties);
1751                                                                 edge.remove();
1752                                                         } else {
1753                                                                 titanGenericDao.setProperties(edge, properties);
1754                                                         }
1755                                                 } else {
1756                                                         leftOccurrencesNew = leftOccurrences;
1757                                                         properties.put(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty(), leftOccurrencesNew);
1758                                                         titanGenericDao.setProperties(edge, properties);
1759                                                 }
1760                                                 break;
1761                                         }
1762                                 }
1763                         }
1764                 }
1765                 return StorageOperationStatus.OK;
1766
1767         }
1768
1769         private StorageOperationStatus updateCapabiltyEdges(GraphEdgeLabels capabiltyNewLabel, GraphEdgeLabels capabiltyCurrentLabel, RequirementAndRelationshipPair pair, String capabiltyOwnerId) {
1770                 Either<TitanVertex, TitanOperationStatus> capOwnerRI = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), capabiltyOwnerId);
1771                 if (capOwnerRI.isRight()) {
1772                         log.debug("Failed to fetch requirment Owner by Id {}. error {}", capabiltyOwnerId, capOwnerRI.right().value());
1773                         return DaoStatusConverter.convertTitanStatusToStorageStatus(capOwnerRI.right().value());
1774                 }
1775                 Iterator<Edge> edgeIter = capOwnerRI.left().value().edges(Direction.OUT, capabiltyCurrentLabel.name(), capabiltyNewLabel.name());
1776                 if (edgeIter == null) {
1777                         log.debug("No edges with label {} for owner RI {}", capabiltyCurrentLabel, capabiltyOwnerId);
1778                         return StorageOperationStatus.GENERAL_ERROR;
1779                 }
1780                 boolean associate = capabiltyNewLabel.equals(GraphEdgeLabels.CALCULATED_CAPABILITY_FULLFILLED) ? true : false;
1781
1782                 while (edgeIter.hasNext()) {
1783                         TitanEdge edge = (TitanEdge) edgeIter.next();
1784                         TitanVertex capVertex = edge.inVertex();
1785                         // edge.property(GraphEdgePropertiesDictionary.NAME.getProperty()).value();
1786
1787                         String capabiltyId = (String) titanGenericDao.getProperty(capVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty());
1788                         // verify vs capability id . ( for capabilty with same name)
1789                         if (capabiltyId.equals(pair.getCapabilityUid())) {
1790                                 String ownerIdOnEdge = (String) titanGenericDao.getProperty(edge, GraphEdgePropertiesDictionary.OWNER_ID.getProperty());
1791                                 if (ownerIdOnEdge.equals(pair.getCapabilityOwnerId())) {
1792
1793                                         String requiredOccurrences = (String) titanGenericDao.getProperty(edge, GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty());
1794                                         String leftOccurrences = (String) titanGenericDao.getProperty(edge, GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty());
1795
1796                                         String requiredOccurrencesNew = "0";
1797                                         String leftOccurrencesNew = CapabilityDataDefinition.MAX_OCCURRENCES;
1798                                         if (requiredOccurrences != null) {
1799                                                 Integer iOccurrences = Integer.parseInt(requiredOccurrences);
1800                                                 if (associate) {
1801                                                         if (iOccurrences > 0) {
1802                                                                 iOccurrences--;
1803                                                                 requiredOccurrencesNew = iOccurrences.toString();
1804                                                         }
1805                                                 } else {
1806                                                         String reqMinOccurrences = (String) titanGenericDao.getProperty(capVertex, GraphPropertiesDictionary.MIN_OCCURRENCES.getProperty());
1807                                                         if (reqMinOccurrences == null) {
1808                                                                 reqMinOccurrences = CapabilityDataDefinition.MIN_OCCURRENCES;
1809                                                         }
1810                                                         if (Integer.parseInt(reqMinOccurrences) > iOccurrences) {
1811                                                                 iOccurrences++;
1812                                                                 requiredOccurrencesNew = iOccurrences.toString();
1813                                                         }
1814                                                 }
1815                                         }
1816                                         Map<String, Object> properties = titanGenericDao.getProperties(edge);
1817                                         properties.put(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty(), requiredOccurrencesNew);
1818
1819                                         if (leftOccurrences != null && !leftOccurrences.equals(CapabilityDataDefinition.MAX_OCCURRENCES)) {
1820                                                 Integer iOccurrences = Integer.parseInt(leftOccurrences);
1821                                                 if (associate) {
1822                                                         if (iOccurrences > 0) {
1823                                                                 iOccurrences--;
1824                                                         }
1825                                                 } else {
1826                                                         iOccurrences++;
1827                                                 }
1828                                                 leftOccurrencesNew = iOccurrences.toString();
1829                                                 properties.put(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty(), leftOccurrencesNew);
1830                                                 if ((associate && iOccurrences == 0) || (!associate && iOccurrences == 1)) {
1831                                                         // move edge to full filled state
1832                                                         TitanVertex outVertex = edge.outVertex();
1833                                                         TitanEdge newEdge = outVertex.addEdge(capabiltyNewLabel.getProperty(), capVertex);
1834                                                         titanGenericDao.setProperties(newEdge, properties);
1835                                                         edge.remove();
1836                                                 } else {
1837                                                         titanGenericDao.setProperties(edge, properties);
1838                                                 }
1839                                         } else {
1840                                                 properties.put(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty(), leftOccurrencesNew);
1841                                                 titanGenericDao.setProperties(edge, properties);
1842                                         }
1843                                         break;
1844                                 }
1845                         }
1846                 }
1847                 return StorageOperationStatus.OK;
1848         }
1849
1850         @Override
1851         public Either<RequirementCapabilityRelDef, StorageOperationStatus> dissociateResourceInstances(String serviceId, NodeTypeEnum nodeType, RequirementCapabilityRelDef requirementDef) {
1852
1853                 return dissociateResourceInstances(serviceId, nodeType, requirementDef, false);
1854         }
1855
1856         private RequirementCapabilityRelDef buildCapabilityResult(String fromResInstanceUid, String toResInstanceUid, String requirement, List<RelationshipInstData> relationshipInstDataList) {
1857
1858                 RequirementCapabilityRelDef capabilityRelDef = new RequirementCapabilityRelDef();
1859                 capabilityRelDef.setFromNode(fromResInstanceUid);
1860                 capabilityRelDef.setToNode(toResInstanceUid);
1861                 List<RequirementAndRelationshipPair> relationships = new ArrayList<RequirementAndRelationshipPair>();
1862                 for (RelationshipInstData relationshipInstData : relationshipInstDataList) {
1863                         RelationshipImpl relationshipImpl = new RelationshipImpl();
1864                         relationshipImpl.setType(relationshipInstData.getType());
1865                         RequirementAndRelationshipPair reqRel = new RequirementAndRelationshipPair(requirement, relationshipImpl);
1866                         capabilityRelDef.setRelationships(relationships);
1867                         reqRel.setCapabilityOwnerId(relationshipInstData.getCapabilityOwnerId());
1868                         reqRel.setCapabilityUid(relationshipInstData.getCapabiltyId());
1869                         reqRel.setRequirementOwnerId(relationshipInstData.getRequirementOwnerId());
1870                         reqRel.setRequirementUid(relationshipInstData.getRequirementId());
1871                         relationships.add(reqRel);
1872                 }
1873                 return capabilityRelDef;
1874
1875         }
1876
1877         public Either<RelationshipInstData, TitanOperationStatus> connectResourcesInService(String componentId, NodeTypeEnum nodeType, String fromResInstanceUid, String toResInstanceUid, RequirementAndRelationshipPair relationPair) {
1878                 String relationship = null;
1879                 String requirement = relationPair.getRequirement();
1880                 if (relationPair.getRelationship() != null) {
1881                         relationship = relationPair.getRelationship().getType();
1882                 }
1883
1884                 log.debug("Going to associate resource instance {} to resource instance {} under component {}. Requirement is {}.", fromResInstanceUid, toResInstanceUid, componentId, requirement);
1885
1886                 Either<ComponentInstanceData, TitanOperationStatus> fromResourceInstDataRes = findMandatoryResourceInstData(fromResInstanceUid);
1887                 if (fromResourceInstDataRes.isRight()) {
1888                         TitanOperationStatus status = fromResourceInstDataRes.right().value();
1889                         log.error("Failed to find resource instance {}. status is {}", fromResInstanceUid, status);
1890                         return Either.right(status);
1891                 }
1892                 ComponentInstanceData fromCI = fromResourceInstDataRes.left().value();
1893                 ComponentInstanceData fromResourceInstanceData = fromCI;
1894                 Either<ComponentInstanceData, TitanOperationStatus> toResourceInstDataRes = findMandatoryResourceInstData(toResInstanceUid);
1895                 if (toResourceInstDataRes.isRight()) {
1896                         TitanOperationStatus status = toResourceInstDataRes.right().value();
1897                         log.error("Failed to find resource instance {}. status is {}", toResInstanceUid, status);
1898                         return Either.right(status);
1899                 }
1900                 ComponentInstanceData toCI = toResourceInstDataRes.left().value();
1901                 ComponentInstanceData toResourceInstanceData = toCI;
1902                 // THE component NodeTypeEnum should be sent
1903                 TitanOperationStatus isResourceInstOfService = verifyResourceInstanceUnderComponent(nodeType, componentId, fromResInstanceUid);
1904                 if (isResourceInstOfService != TitanOperationStatus.OK) {
1905                         return Either.right(isResourceInstOfService);
1906                 }
1907                 isResourceInstOfService = verifyResourceInstanceUnderComponent(nodeType, componentId, toResInstanceUid);
1908                 if (isResourceInstOfService != TitanOperationStatus.OK) {
1909                         return Either.right(isResourceInstOfService);
1910                 }
1911
1912                 Either<ImmutablePair<RelationshipTypeData, String>, TitanOperationStatus> isValidRes = validateRequirementVsCapability(fromResourceInstanceData, toResourceInstanceData, requirement, relationship, relationPair);
1913                 if (isValidRes.isRight()) {
1914                         TitanOperationStatus status = isValidRes.right().value();
1915                         log.error("Failed to validate requirement {} between resource instance {} to resource instance {}. status is {}", requirement, fromResInstanceUid, toResInstanceUid, status);
1916                         return Either.right(status);
1917                 }
1918
1919                 RelationshipTypeData relationshipTypeData = isValidRes.left().value().getKey();
1920                 String capabilityName = isValidRes.left().value().getValue();
1921                 RelationshipInstData relationshipInstData = buildRelationshipInstData(fromResInstanceUid, requirement, relationshipTypeData, relationPair);
1922                 Either<RelationshipInstData, TitanOperationStatus> createNode = createRelationshipInstData(fromCI, relationshipInstData, relationshipTypeData, requirement);
1923
1924                 if (createNode.isRight()) {
1925                         return Either.right(createNode.right().value());
1926                 }
1927                 RelationshipInstData createdRelInstData = createNode.left().value();
1928                 Either<GraphRelation, TitanOperationStatus> associateResInst = associateRelationshipInstToTarget(toCI, requirement, capabilityName, createdRelInstData);
1929
1930                 if (associateResInst.isRight()) {
1931                         TitanOperationStatus status = associateResInst.right().value();
1932                         log.error("Failed to associate relationship instance {} to target node {}. status is {}", createdRelInstData.getUniqueId(), toResInstanceUid, status);
1933                         return Either.right(status);
1934                 }
1935
1936                 return Either.left(createNode.left().value());
1937         }
1938
1939         private TitanOperationStatus verifyResourceInstanceUnderComponent(NodeTypeEnum containerNodeType, String containerComponentId, String resInstanceUid) {
1940
1941                 Either<ImmutablePair<ComponentMetadataData, GraphEdge>, TitanOperationStatus> parentNode = titanGenericDao.getParentNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resInstanceUid, GraphEdgeLabels.RESOURCE_INST,
1942                                 containerNodeType, ComponentMetadataData.class);
1943
1944                 if (parentNode.isRight()) {
1945                         TitanOperationStatus status = parentNode.right().value();
1946                         log.error("Failed to find the service associated to the resource instance {}. status is {}", resInstanceUid, status);
1947                         return status;
1948                 }
1949
1950                 ImmutablePair<ComponentMetadataData, GraphEdge> componentsRes = parentNode.left().value();
1951                 ComponentMetadataData componentMetadataData = componentsRes.getKey();
1952                 String uniqueId = (String) componentMetadataData.getUniqueId();
1953
1954                 if (containerComponentId.equals(uniqueId)) {
1955                         return TitanOperationStatus.OK;
1956                 } else {
1957                         BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeIncorrectServiceError, "Resource Instance - verifyResourceInstanceUnderComponent", containerComponentId);
1958                         BeEcompErrorManager.getInstance().logBeIncorrectComponentError("Resource Instance - verifyResourceInstanceUnderComponent", containerNodeType.getName(), containerComponentId);
1959                         log.debug("The provided component id {} is not equal to the component ({}) which associated to resource instance {}", containerComponentId, uniqueId, resInstanceUid);
1960                         return TitanOperationStatus.INVALID_ID;
1961                 }
1962
1963         }
1964
1965         /**
1966          * find the resource instance node in graph.
1967          * 
1968          * @param resInstanceUid
1969          * @return
1970          */
1971         private Either<ComponentInstanceData, TitanOperationStatus> findMandatoryResourceInstData(String resInstanceUid) {
1972                 Either<ComponentInstanceData, TitanOperationStatus> resStatus = findResourceInstance(resInstanceUid);
1973                 if (resStatus.isRight()) {
1974                         TitanOperationStatus status = resStatus.right().value();
1975                         if (status == TitanOperationStatus.NOT_FOUND) {
1976                                 return Either.right(TitanOperationStatus.INVALID_ID);
1977                         }
1978                         return Either.right(status);
1979                 }
1980                 ComponentInstanceData riData = resStatus.left().value();
1981                 return Either.left(riData);
1982         }
1983
1984         /**
1985          * associate relationship instance node to the target resource instance node.
1986          * 
1987          * @param toResInstance
1988          * @param requirement
1989          * @param relInstData
1990          * @return
1991          */
1992         private Either<GraphRelation, TitanOperationStatus> associateRelationshipInstToTarget(ComponentInstanceData toResInstance, String requirement, String capabilityName, RelationshipInstData relInstData) {
1993
1994                 Map<String, Object> props = new HashMap<String, Object>();
1995                 props.put(GraphPropertiesDictionary.NAME.getProperty(), capabilityName);
1996                 Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(relInstData, toResInstance, GraphEdgeLabels.CAPABILITY_NODE, props);
1997                 log.debug("After creatingrelation between relationship instance {} to target node {}", relInstData.getUniqueId(), toResInstance.getUniqueId());
1998
1999                 return createRelation;
2000
2001         }
2002
2003         /**
2004          * create reslationship instance node and associate the reosurce instance node to it.
2005          * 
2006          * @param resInstance
2007          * @param relationshipInstData
2008          * @param relationshipTypeData
2009          * @param requirementName
2010          * @return
2011          */
2012         private Either<RelationshipInstData, TitanOperationStatus> createRelationshipInstData(ComponentInstanceData resInstance, RelationshipInstData relationshipInstData, RelationshipTypeData relationshipTypeData, String requirementName) {
2013
2014                 Either<RelationshipInstData, TitanOperationStatus> createNode = titanGenericDao.createNode(relationshipInstData, RelationshipInstData.class);
2015                 if (createNode.isRight()) {
2016                         TitanOperationStatus status = createNode.right().value();
2017                         log.error("Failed to create relationship instance node in graph. status is {}", status);
2018                         return Either.right(status);
2019                 }
2020
2021                 RelationshipInstData createdRelationshipInst = createNode.left().value();
2022
2023                 Map<String, Object> properties = new HashMap<String, Object>();
2024                 properties.put("name", requirementName);
2025                 Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(resInstance, createdRelationshipInst, GraphEdgeLabels.RELATIONSHIP_INST, properties);
2026                 if (createRelation.isRight()) {
2027                         TitanOperationStatus status = createRelation.right().value();
2028                         log.error("Failed to associate resource instance {} to relationship instance {}. status is {}", resInstance.getUniqueIdKey(), createdRelationshipInst.getUniqueId(), status);
2029                         return Either.right(status);
2030                 }
2031
2032                 return Either.left(createdRelationshipInst);
2033         }
2034
2035         /**
2036          * check whether we can associate resource instances for a given requirement.
2037          * 
2038          * 1. check the source resource instance contains the requirement
2039          * 
2040          * 2. check the target resource instance contains a capability with the same name as the requirement
2041          * 
2042          * @param fromResInstance
2043          * @param toResInstance
2044          * @param requirement
2045          * @param relationship
2046          * @param relationPair
2047          * @return
2048          */
2049         private Either<ImmutablePair<RelationshipTypeData, String>, TitanOperationStatus> validateRequirementVsCapability(ComponentInstanceData fromResInstance, ComponentInstanceData toResInstance, String requirement, String relationship,
2050                         RequirementAndRelationshipPair relationPair) {
2051
2052                 String fromResourceUid = fromResInstance.getComponentInstDataDefinition().getComponentUid();
2053
2054                 String toResourceUid = toResInstance.getComponentInstDataDefinition().getComponentUid();
2055                 Either<CapabilityDefinition, StorageOperationStatus> capabilityDefinitionE = capabilityOperation.getCapability(relationPair.getCapabilityUid(), true);
2056                 if (capabilityDefinitionE.isRight()) {
2057                         log.error("The capability cannot be found {}", relationPair.getCapabilityUid());
2058                         return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
2059                 }
2060                 Either<RequirementDefinition, TitanOperationStatus> requirementDefinitionE = requirementOperation.getRequirement(relationPair.getRequirementUid());
2061                 if (requirementDefinitionE.isRight()) {
2062                         log.error("The requirement   cannot be found {}", relationPair.getRequirementUid());
2063                         return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
2064                 }
2065                 RequirementDefinition requirementDefinition = requirementDefinitionE.left().value();
2066                 String fetchedRequirementRelationship = requirementDefinition.getRelationship();
2067
2068                 String fetchedRequirementCapability = requirementDefinition.getCapability();
2069                 // String fetchedRequirementNodeName = requirementDefinition.getNode();
2070
2071                 TitanOperationStatus status = validateAvailableRequirement(fromResInstance, relationPair);
2072                 if (!status.equals(TitanOperationStatus.OK)) {
2073                         log.error("The requirement isn't available, status {}", status);
2074                         return Either.right(status);
2075                 }
2076                 status = validateAvailableCapabilty(toResInstance, relationPair);
2077                 if (!status.equals(TitanOperationStatus.OK)) {
2078                         log.error("The capabilty isn't available, status {}", status);
2079                         return Either.right(status);
2080                 }
2081                 Either<ComponentInstanceData, TitanOperationStatus> originCapabilty = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), relationPair.getCapabilityOwnerId(), ComponentInstanceData.class);
2082                 if (originCapabilty.isRight()) {
2083                         log.error("Failed to fetch the origin resource for capabilty resource instance with id {}, error {}", relationPair.getCapabilityOwnerId(), originCapabilty.right().value());
2084                         return Either.right(originCapabilty.right().value());
2085                 }
2086                 // String originCapabId =
2087                 // originCapabilty.left().value().getComponentInstDataDefinition().getComponentUid();
2088
2089                 // List<String> capabilitySources = new ArrayList<>();
2090                 // TitanOperationStatus capabiltySourcesResult =
2091                 // resourceOperation.fillResourceDerivedListFromGraph(originCapabId,
2092                 // capabilitySources);
2093                 // if (!TitanOperationStatus.OK.equals(capabiltySourcesResult)) {
2094                 // log.error("Failed to fill capabilty cources for resource with id " +
2095                 // originCapabId + " , error " + capabiltySourcesResult);
2096                 // return Either.right(originCapabilty.right().value());
2097                 // }
2098                 CapabilityDefinition capabilityDefinition = capabilityDefinitionE.left().value();
2099                 String capabilityName = requirement;
2100
2101                 log.debug("The capability {} of resource {} appropriates to requirement {} on resource {}", capabilityDefinition, toResourceUid, requirement, fromResourceUid);
2102                 String capabilityType = capabilityDefinition.getType();
2103
2104                 if (false == fetchedRequirementCapability.equals(capabilityType)) {
2105                         log.error("The capability type in the requirement ({}) does not equal to the capability on the resource {} ({})", fetchedRequirementCapability, toResourceUid, capabilityType);
2106                         return Either.right(TitanOperationStatus.MATCH_NOT_FOUND);
2107                 }
2108
2109                 // if (fetchedRequirementNodeName != null &&
2110                 // !capabilitySources.contains(fetchedRequirementNodeName)) {
2111                 // log.error("The target resource instance " + toResourceUid + " is not
2112                 // of type " + fetchedRequirementNodeName);
2113                 // return Either.right(TitanOperationStatus.MATCH_NOT_FOUND);
2114                 // }
2115
2116                 RelationshipTypeData relationshipTypeData = new RelationshipTypeData();
2117                 relationshipTypeData.getRelationshipTypeDataDefinition().setType(fetchedRequirementRelationship);
2118
2119                 ImmutablePair<RelationshipTypeData, String> result = new ImmutablePair<RelationshipTypeData, String>(relationshipTypeData, capabilityName);
2120                 return Either.left(result);
2121         }
2122
2123         private TitanOperationStatus validateAvailableRequirement(ComponentInstanceData fromResInstance, RequirementAndRelationshipPair relationPair) {
2124                 Either<TitanVertex, TitanOperationStatus> fromRi = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), fromResInstance.getUniqueId());
2125                 if (fromRi.isRight()) {
2126                         log.debug("Failed to fetch component instance {}  error {}", fromResInstance.getUniqueId(), fromRi.right().value());
2127                         return fromRi.right().value();
2128                 }
2129                 Iterator<Edge> edgeIter = fromRi.left().value().edges(Direction.OUT, GraphEdgeLabels.CALCULATED_REQUIREMENT.name());
2130                 if (edgeIter == null || !edgeIter.hasNext()) {
2131                         log.debug("No available CALCULATED_REQUIREMENT edges. All full filled for RI {}", fromResInstance.getUniqueId());
2132                         return TitanOperationStatus.MATCH_NOT_FOUND;
2133                 }
2134                 boolean exist = false;
2135                 while (edgeIter.hasNext()) {
2136                         Edge edge = edgeIter.next();
2137                         TitanVertex reqVertex = (TitanVertex) edge.inVertex();
2138                         String reqId = (String) titanGenericDao.getProperty(reqVertex, UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Requirement));
2139                         if (reqId.equals(relationPair.getRequirementUid())) {
2140                                 String ownerIdOnEdge = (String) edge.value(GraphEdgePropertiesDictionary.OWNER_ID.getProperty());
2141                                 if (ownerIdOnEdge.equals(relationPair.getRequirementOwnerId())) {
2142                                         String leftOccurrences = (String) titanGenericDao.getProperty(edge, GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty());
2143                                         if (leftOccurrences != null && !leftOccurrences.equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
2144                                                 Integer leftIntValue = Integer.parseInt(leftOccurrences);
2145                                                 if (leftIntValue > 0) {
2146                                                         exist = true;
2147                                                 }
2148                                         } else {
2149                                                 exist = true;
2150                                         }
2151                                         break;
2152                                 }
2153                         }
2154                 }
2155                 return exist ? TitanOperationStatus.OK : TitanOperationStatus.MATCH_NOT_FOUND;
2156         }
2157
2158         private TitanOperationStatus validateAvailableCapabilty(ComponentInstanceData toResInstance, RequirementAndRelationshipPair relationPair) {
2159                 Either<TitanVertex, TitanOperationStatus> fromRi = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), toResInstance.getUniqueId());
2160                 if (fromRi.isRight()) {
2161                         log.debug("Failed to fetch component instance {}. error {}", toResInstance.getUniqueId(), fromRi.right().value());
2162                         return fromRi.right().value();
2163                 }
2164                 Iterator<Edge> edgeIter = fromRi.left().value().edges(Direction.OUT, GraphEdgeLabels.CALCULATED_CAPABILITY.name());
2165                 if (edgeIter == null || !edgeIter.hasNext()) {
2166                         log.debug("No available CALCULATED_CAPABILITY edges. All full filled for RI {}", toResInstance.getUniqueId());
2167                         return TitanOperationStatus.MATCH_NOT_FOUND;
2168                 }
2169                 boolean exist = false;
2170                 while (edgeIter.hasNext()) {
2171                         Edge edge = edgeIter.next();
2172                         TitanVertex reqVertex = (TitanVertex) edge.inVertex();
2173                         String capId = (String) titanGenericDao.getProperty(reqVertex, UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Capability));
2174                         if (capId.equals(relationPair.getCapabilityUid())) {
2175                                 String ownerIdOnEdge = (String) edge.value(GraphEdgePropertiesDictionary.OWNER_ID.getProperty());
2176                                 if (ownerIdOnEdge.equals(relationPair.getCapabilityOwnerId())) {
2177                                         String leftOccurrences = (String) titanGenericDao.getProperty(edge, GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty());
2178                                         if (leftOccurrences != null && !leftOccurrences.equals(CapabilityDataDefinition.MAX_OCCURRENCES)) {
2179                                                 Integer leftIntValue = Integer.parseInt(leftOccurrences);
2180                                                 if (leftIntValue > 0) {
2181                                                         exist = true;
2182                                                 }
2183                                         } else {
2184                                                 exist = true;
2185                                         }
2186                                         break;
2187                                 }
2188                         }
2189                 }
2190                 return exist ? TitanOperationStatus.OK : TitanOperationStatus.NOT_FOUND;
2191         }
2192
2193         private List<ImmutablePair<String, CapabilityDefinition>> findCapabilityOfType(Map<String, CapabilityDefinition> capabilities, String fetchedRequirementCapability) {
2194
2195                 List<ImmutablePair<String, CapabilityDefinition>> result = new ArrayList<ImmutablePair<String, CapabilityDefinition>>();
2196
2197                 if (capabilities == null) {
2198                         return null;
2199                 }
2200
2201                 for (Entry<String, CapabilityDefinition> entry : capabilities.entrySet()) {
2202                         CapabilityDefinition capabilityDefinition = entry.getValue();
2203                         String type = capabilityDefinition.getType();
2204                         if (fetchedRequirementCapability.equals(type)) {
2205                                 ImmutablePair<String, CapabilityDefinition> pair = new ImmutablePair<String, CapabilityDefinition>(entry.getKey(), capabilityDefinition);
2206                                 result.add(pair);
2207                         }
2208                 }
2209
2210                 return result;
2211         }
2212
2213         protected TitanOperationStatus validateTheTargetResourceInstance(String fetchedRequirementNodeName, String resourceUid) {
2214
2215                 if (fetchedRequirementNodeName == null) {
2216                         return TitanOperationStatus.OK;
2217                 }
2218
2219                 List<ResourceMetadataData> resourcesPathList = new ArrayList<ResourceMetadataData>();
2220                 TitanOperationStatus status = resourceOperation.findResourcesPathRecursively(resourceUid, resourcesPathList);
2221                 if (status != TitanOperationStatus.OK) {
2222                         log.error("Failed to find the parent list of resource {}. status is {}", resourceUid, status);
2223                         return status;
2224                 }
2225
2226                 boolean found = false;
2227                 if (resourcesPathList != null) {
2228                         for (ResourceMetadataData resourceData : resourcesPathList) {
2229                                 String resourceName = resourceData.getMetadataDataDefinition().getName();
2230                                 if (fetchedRequirementNodeName.equals(resourceName)) {
2231                                         found = true;
2232                                         log.debug("The resource {} is of type {}", resourceData.getUniqueId(), fetchedRequirementNodeName);
2233                                         break;
2234                                 }
2235                         }
2236                 }
2237
2238                 if (true == found) {
2239                         return TitanOperationStatus.OK;
2240                 } else {
2241                         return TitanOperationStatus.MATCH_NOT_FOUND;
2242                 }
2243
2244         }
2245
2246         private RelationshipInstData buildRelationshipInstData(String fromResInstanceUid, String requirement, RelationshipTypeData relationshipTypeData, RequirementAndRelationshipPair relationPair) {
2247
2248                 RelationshipInstData relationshipInstData = new RelationshipInstData();
2249                 relationshipInstData.setUniqueId(UniqueIdBuilder.buildRelationsipInstInstanceUid(fromResInstanceUid, requirement));
2250                 String type = null;
2251                 if (relationshipTypeData != null) {
2252                         type = relationshipTypeData.getRelationshipTypeDataDefinition().getType();
2253                 }
2254
2255                 relationshipInstData.setType(type);
2256                 Long creationDate = System.currentTimeMillis();
2257                 relationshipInstData.setCreationTime(creationDate);
2258                 relationshipInstData.setModificationTime(creationDate);
2259                 relationshipInstData.setCapabilityOwnerId(relationPair.getCapabilityOwnerId());
2260                 relationshipInstData.setRequirementOwnerId(relationPair.getRequirementOwnerId());
2261                 relationshipInstData.setCapabiltyId(relationPair.getCapabilityUid());
2262                 relationshipInstData.setRequirementId(relationPair.getRequirementUid());
2263
2264                 return relationshipInstData;
2265         }
2266
2267         private Either<ComponentInstanceData, TitanOperationStatus> findResourceInstance(String resInstanceUid) {
2268
2269                 Either<ComponentInstanceData, TitanOperationStatus> node = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resInstanceUid, ComponentInstanceData.class);
2270
2271                 return node;
2272
2273         }
2274
2275         @Override
2276         public Either<ComponentInstance, StorageOperationStatus> updateResourceInstance(String serviceId, NodeTypeEnum nodeType, String resourceInstanceUid, ComponentInstance resourceInstance, boolean inTransaction) {
2277
2278                 Either<ComponentInstance, StorageOperationStatus> result = null;
2279                 try {
2280
2281                         Either<ComponentInstance, TitanOperationStatus> updateRes = updateResourceInstanceInService(serviceId, resourceInstanceUid, resourceInstance);
2282
2283                         if (updateRes.isRight()) {
2284                                 TitanOperationStatus status = updateRes.right().value();
2285                                 log.error("Failed to update resource instance {}. status is {}", resourceInstanceUid, status);
2286                                 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
2287                                 return result;
2288                         }
2289
2290                         ComponentInstance value = updateRes.left().value();
2291
2292                         result = Either.left(value);
2293
2294                         return result;
2295
2296                 } finally {
2297                         if (false == inTransaction) {
2298                                 commitOrRollback(result);
2299                         }
2300                 }
2301
2302         }
2303
2304         /**
2305          * prepare new resource instance object for update
2306          * 
2307          * @param resourceInstance
2308          * @param currentInst
2309          * @return
2310          */
2311         private ComponentInstance normalizeResourceInstanceForUpdate(ComponentInstance resourceInstance, ComponentInstanceData currentInst) {
2312
2313                 ComponentInstance instance = new ComponentInstance();
2314                 instance.setUniqueId((String) currentInst.getUniqueId());
2315                 Long modificationTime = resourceInstance.getModificationTime();
2316                 if (modificationTime == null) {
2317                         modificationTime = System.currentTimeMillis();
2318                 }
2319                 instance.setModificationTime(modificationTime);
2320                 instance.setPosX(resourceInstance.getPosX());
2321                 instance.setPosY(resourceInstance.getPosY());
2322                 instance.setDescription(resourceInstance.getDescription());
2323                 instance.setName(resourceInstance.getName());
2324                 instance.setNormalizedName(resourceInstance.getNormalizedName());
2325                 instance.setPropertyValueCounter(resourceInstance.getPropertyValueCounter());
2326                 instance.setAttributeValueCounter(resourceInstance.getAttributeValueCounter());
2327                 instance.setInputValueCounter(resourceInstance.getInputValueCounter());
2328
2329                 boolean isNeedGenerate = isNeedGenerateCustomizationUUID(resourceInstance, currentInst);
2330                 if (isNeedGenerate) {
2331                         generateCustomizationUUID(instance);
2332                 } else {
2333                         instance.setCustomizationUUID(resourceInstance.getCustomizationUUID());
2334                 }
2335                 return instance;
2336         }
2337
2338         private boolean isNeedGenerateCustomizationUUID(ComponentInstance resourceInstance, ComponentInstanceData currentInst) {
2339                 return !currentInst.getComponentInstDataDefinition().getName().equals(resourceInstance.getName());
2340         }
2341
2342         private void printDiff(ComponentInstanceData currentInst, ComponentInstance resourceInstance) {
2343
2344                 log.debug("The current Resource Instance details are : {}", currentInst);
2345                 log.debug("The received Resource Instance details for update are :{}", resourceInstance);
2346
2347         }
2348
2349         @Override
2350         public Either<ComponentInstance, StorageOperationStatus> updateResourceInstance(String serviceId, NodeTypeEnum nodeType, String resourceInstanceName, ComponentInstance resourceInstance) {
2351
2352                 return updateResourceInstance(serviceId, nodeType, resourceInstanceName, resourceInstance, false);
2353         }
2354
2355         public Either<ComponentInstance, TitanOperationStatus> updateResourceInstanceInService(String serviceId, String resourceInstanceUid, ComponentInstance resourceInstance) {
2356
2357                 log.trace("Going to update resource instance {}. Properies are {}", resourceInstanceUid, resourceInstance);
2358                 Either<ComponentInstanceData, TitanOperationStatus> findInstRes = findResourceInstance(resourceInstanceUid);
2359                 if (findInstRes.isRight()) {
2360                         TitanOperationStatus status = findInstRes.right().value();
2361                         log.error("Failed to find resource instance {}. status is {}", resourceInstanceUid, status);
2362                         return Either.right(status);
2363                 }
2364
2365                 ComponentInstanceData currentInst = findInstRes.left().value();
2366                 if (log.isDebugEnabled()) {
2367                         printDiff(currentInst, resourceInstance);
2368                 }
2369
2370                 ComponentInstance resourceInstanceForUpdate = normalizeResourceInstanceForUpdate(resourceInstance, currentInst);
2371
2372                 ComponentInstanceData resourceInstanceData = new ComponentInstanceData(resourceInstanceForUpdate);
2373
2374                 Either<ComponentInstanceData, TitanOperationStatus> updateNodeRes = titanGenericDao.updateNode(resourceInstanceData, ComponentInstanceData.class);
2375                 if (updateNodeRes.isRight()) {
2376                         TitanOperationStatus status = updateNodeRes.right().value();
2377                         log.error("Failed to update resource instance {}. status is {}", resourceInstanceUid, status);
2378                         return Either.right(status);
2379                 }
2380
2381                 ComponentInstanceData value = updateNodeRes.left().value();
2382
2383                 ComponentInstance instance = new ComponentInstance(value.getComponentInstDataDefinition());
2384
2385                 return Either.left(instance);
2386
2387         }
2388
2389         @Override
2390         public Either<ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>>, StorageOperationStatus> getAllComponentInstances(String componentId, NodeTypeEnum containerNodeType, NodeTypeEnum compInstNodeType, boolean inTransaction) {
2391
2392                 Either<ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>>, StorageOperationStatus> result = null;
2393
2394                 try {
2395
2396                         Either<ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>>, TitanOperationStatus> resInstancesOfService = getComponentInstancesOfComponent(componentId, containerNodeType, compInstNodeType);
2397
2398                         log.trace("After fetching resource instances of component {}. result is {}", componentId, resInstancesOfService);
2399                         if (resInstancesOfService.isRight()) {
2400                                 TitanOperationStatus status = resInstancesOfService.right().value();
2401                                 if (status != TitanOperationStatus.NOT_FOUND) {
2402                                         log.error("Failed to find resource instances of service {}. status is {}", componentId, status);
2403                                 }
2404                                 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
2405                                 return result;
2406                         }
2407
2408                         ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>> immutablePair = resInstancesOfService.left().value();
2409                         List<ComponentInstance> nodes = immutablePair.getKey();
2410                         if (nodes == null || nodes.isEmpty()) {
2411                                 return Either.right(StorageOperationStatus.NOT_FOUND);
2412                         }
2413
2414                         result = Either.left(immutablePair);
2415                         return result;
2416                 } finally {
2417                         if (false == inTransaction) {
2418                                 commitOrRollback(result);
2419                         }
2420                 }
2421         }
2422
2423         @Override
2424         public Either<Boolean, StorageOperationStatus> isComponentInstanceNameExist(String parentComponentId, NodeTypeEnum nodeType, String compInstId, String componentInstName) {
2425
2426                 Either<Boolean, StorageOperationStatus> result = null;
2427                 Either<Boolean, TitanOperationStatus> updateRes = isComponentInstanceNameExistOnGraph(parentComponentId, nodeType, compInstId, componentInstName);
2428
2429                 if (updateRes.isRight()) {
2430                         TitanOperationStatus status = updateRes.right().value();
2431                         log.error("Failed to find component instance name {}. status is {}", componentInstName, status);
2432                         result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
2433                         return result;
2434                 }
2435
2436                 Boolean value = updateRes.left().value();
2437
2438                 result = Either.left(value);
2439
2440                 return result;
2441
2442         }
2443
2444         private Either<Boolean, TitanOperationStatus> isComponentInstanceNameExistOnGraph(String parentComponentId, NodeTypeEnum parentNodeType, String compInstId, String componentInstName) {
2445
2446                 Either<TitanGraph, TitanOperationStatus> graphRes = titanGenericDao.getGraph();
2447                 if (graphRes.isRight()) {
2448                         log.debug("Failed to retrieve graph. status is {}", graphRes);
2449                         return Either.right(graphRes.right().value());
2450                 }
2451
2452                 TitanGraph titanGraph = graphRes.left().value();
2453                 Iterable<TitanVertex> vertices = titanGraph.query().has(UniqueIdBuilder.getKeyByNodeType(parentNodeType), parentComponentId).vertices();
2454                 if (vertices == null || false == vertices.iterator().hasNext()) {
2455                         return Either.right(TitanOperationStatus.INVALID_ID);
2456                 }
2457
2458                 TitanVertex serviceVertex = vertices.iterator().next();
2459                 TitanVertexQuery query = serviceVertex.query();
2460                 query = query.labels(GraphEdgeLabels.RESOURCE_INST.getProperty());
2461                 Iterable<Vertex> verts = query.vertices();
2462                 if (verts == null) {
2463                         log.debug("No edges in graph for criteria");
2464                         return Either.right(TitanOperationStatus.NOT_FOUND);
2465                 }
2466                 Iterator<Vertex> vIter = verts.iterator();
2467                 while (vIter.hasNext()) {
2468                         Vertex vert = vIter.next();
2469                         String resInstName = vert.value(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty());
2470                         if (resInstName.equals(componentInstName)) {
2471                                 if (compInstId != null) {// will be null if we got here from
2472                                                                                         // create
2473                                         // Update case - skipping if this is the same component
2474                                         // instance we are updating, that is allowing
2475                                         // update of the unchanged name on a component instance.
2476                                         // This is needed to support position only update, since
2477                                         // name should
2478                                         // always be passed in update, and in position case, the
2479                                         // name will be unchanged.
2480                                         String uniqueId = vert.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
2481                                         if (uniqueId.equals(compInstId)) {
2482                                                 continue;
2483                                         }
2484                                 }
2485                                 return Either.left(Boolean.TRUE);
2486                         }
2487                 }
2488                 return Either.left(Boolean.FALSE);
2489         }
2490
2491         /**
2492          * find resource instances and the relationships between the relationships of a given resource
2493          * 
2494          * @param componentId
2495          * @return
2496          */
2497         public Either<ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>>, TitanOperationStatus> getComponentInstancesOfComponent(String componentId, NodeTypeEnum containerNodeType, NodeTypeEnum compInstNodeType) {
2498
2499                 if (log.isDebugEnabled())
2500                         log.debug("Going to fetch all resource instances under component {}", componentId);
2501
2502                 Either<ComponentMetadataData, TitanOperationStatus> componentRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(containerNodeType), componentId, ComponentMetadataData.class);
2503                 if (componentRes.isRight()) {
2504                         TitanOperationStatus status = componentRes.right().value();
2505                         log.error("Failed to find component {}. status is {}", componentId, status);
2506                         return Either.right(status);
2507                 }
2508
2509                 Either<List<ImmutablePair<ComponentInstanceData, GraphEdge>>, TitanOperationStatus> resourceInstancesRes = getAllComponentInstanceFromGraph(componentId, containerNodeType, true);
2510                 if (resourceInstancesRes.isRight()) {
2511                         TitanOperationStatus status = resourceInstancesRes.right().value();
2512                         log.debug("Resource instance was found under component {}. status is {}", componentId, status);
2513                         return Either.right(status);
2514                 }
2515
2516                 List<ComponentInstance> resourcesResult = new ArrayList<ComponentInstance>();
2517                 List<RequirementCapabilityRelDef> requirementsResult = new ArrayList<RequirementCapabilityRelDef>();
2518
2519                 List<ImmutablePair<ComponentInstanceData, GraphEdge>> resourceInstances = resourceInstancesRes.left().value();
2520                 if (resourceInstances != null && false == resourceInstances.isEmpty()) {
2521                         Map<String, Map<String, CapabilityDefinition>> compInstCapabilities = new HashMap<String, Map<String, CapabilityDefinition>>();
2522                         Map<String, Map<String, RequirementDefinition>> compInstReq = new HashMap<String, Map<String, RequirementDefinition>>();
2523                         Map<String, Map<String, ArtifactDefinition>> compInstDeploymentArtifacts = new HashMap<String, Map<String, ArtifactDefinition>>();
2524                         Map<String, Map<String, ArtifactDefinition>> compInstInformationalArtifacts = new HashMap<String, Map<String, ArtifactDefinition>>();
2525                         Map<String, Component> compInstOriginsMap = new HashMap<String, Component>();
2526
2527                         for (ImmutablePair<ComponentInstanceData, GraphEdge> immutablePair : resourceInstances) {
2528
2529                                 ComponentInstanceData resourceInstanceData = immutablePair.getKey();
2530                                 if (log.isDebugEnabled())
2531                                         log.debug("Going to fetch the relationships of resource instance {}", resourceInstanceData);
2532
2533                                 ComponentInstance resourceInstance = new ComponentInstance(resourceInstanceData.getComponentInstDataDefinition());
2534
2535                                 TitanOperationStatus status = getFullComponentInstance(compInstCapabilities, compInstReq, compInstDeploymentArtifacts, compInstOriginsMap, resourceInstance, compInstNodeType, compInstInformationalArtifacts);
2536                                 if (status != TitanOperationStatus.OK) {
2537                                         return Either.right(status);
2538                                 }
2539                                 resourcesResult.add(resourceInstance);
2540
2541                                 Either<List<ImmutablePair<RelationshipInstData, GraphEdge>>, TitanOperationStatus> relationshipsRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance),
2542                                                 (String) resourceInstanceData.getUniqueId(), GraphEdgeLabels.RELATIONSHIP_INST, NodeTypeEnum.RelationshipInst, RelationshipInstData.class);
2543
2544                                 if (relationshipsRes.isRight()) {
2545                                         status = relationshipsRes.right().value();
2546                                         log.debug("After fetching all reslationships of resource instance {} under component {} . status is {}", resourceInstanceData.getUniqueId(), componentId, status);
2547                                         if (status == TitanOperationStatus.NOT_FOUND) {
2548                                                 continue;
2549                                         } else {
2550                                                 log.error("Failed to find relationhips of resource instance {} under component {}. status is {}", resourceInstanceData.getUniqueId(), componentId, status);
2551                                                 return Either.right(status);
2552                                         }
2553                                 }
2554
2555                                 String sourceResourceUid = (String) resourceInstanceData.getUniqueId();
2556
2557                                 Map<String, List<ImmutablePair<String, RelationshipInstData>>> targetNodeToRelationship = new HashMap<String, List<ImmutablePair<String, RelationshipInstData>>>();
2558
2559                                 List<ImmutablePair<RelationshipInstData, GraphEdge>> relationshipsImpl = relationshipsRes.left().value();
2560                                 status = populateTargetAndRelationsForGivenSource(targetNodeToRelationship, relationshipsImpl);
2561
2562                                 if (status != TitanOperationStatus.OK) {
2563                                         return Either.right(status);
2564                                 }
2565
2566                                 if (targetNodeToRelationship.isEmpty()) {
2567                                         log.error("No target found for relationship instances of resource instance {}", resourceInstanceData.getUniqueId());
2568                                         return Either.right(TitanOperationStatus.INVALID_ELEMENT);
2569                                 }
2570
2571                                 buildRelationsForSource(requirementsResult, sourceResourceUid, targetNodeToRelationship);
2572
2573                         }
2574
2575                         return Either.left(new ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>>(resourcesResult, requirementsResult));
2576                 } else {
2577                         return Either.right(TitanOperationStatus.NOT_FOUND);
2578                 }
2579
2580         }
2581
2582         private Either<List<RequirementCapabilityRelDef>, TitanOperationStatus> getRelationsForSource(String resourceInstanceUid) {
2583                 Either<List<ImmutablePair<RelationshipInstData, GraphEdge>>, TitanOperationStatus> relationshipsRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceUid,
2584                                 GraphEdgeLabels.RELATIONSHIP_INST, NodeTypeEnum.RelationshipInst, RelationshipInstData.class);
2585
2586                 TitanOperationStatus status;
2587                 List<RequirementCapabilityRelDef> requirementsResult = new ArrayList<RequirementCapabilityRelDef>();
2588
2589                 if (relationshipsRes.isRight()) {
2590                         status = relationshipsRes.right().value();
2591                         log.debug("After fetching all reslationships of resource instance {}. status is {}", resourceInstanceUid, status);
2592                         if (status == TitanOperationStatus.NOT_FOUND) {
2593                                 return Either.left(requirementsResult);
2594                         } else {
2595                                 log.error("Failed to find relationhips of resource instance {}. status is {}", resourceInstanceUid, status);
2596                                 return Either.right(status);
2597                         }
2598                 }
2599
2600                 Map<String, List<ImmutablePair<String, RelationshipInstData>>> targetNodeToRelationship = new HashMap<String, List<ImmutablePair<String, RelationshipInstData>>>();
2601
2602                 List<ImmutablePair<RelationshipInstData, GraphEdge>> relationshipsImpl = relationshipsRes.left().value();
2603                 status = populateTargetAndRelationsForGivenSource(targetNodeToRelationship, relationshipsImpl);
2604
2605                 if (status != TitanOperationStatus.OK) {
2606                         return Either.right(status);
2607                 }
2608
2609                 if (targetNodeToRelationship.isEmpty()) {
2610                         log.error("No target found for relationship instances of resource instance {}", resourceInstanceUid);
2611                         return Either.right(TitanOperationStatus.INVALID_ELEMENT);
2612                 }
2613
2614                 buildRelationsForSource(requirementsResult, resourceInstanceUid, targetNodeToRelationship);
2615                 return Either.left(requirementsResult);
2616         }
2617
2618         private Either<List<RequirementCapabilityRelDef>, TitanOperationStatus> getRelationsForTarget(String resourceInstanceUid) {
2619
2620                 TitanOperationStatus status;
2621
2622                 Either<List<ImmutablePair<RelationshipInstData, GraphEdge>>, TitanOperationStatus> relationshipsRes = titanGenericDao.getParentNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceUid,
2623                                 GraphEdgeLabels.CAPABILITY_NODE, NodeTypeEnum.RelationshipInst, RelationshipInstData.class);
2624
2625                 List<RequirementCapabilityRelDef> requirementsResult = new ArrayList<RequirementCapabilityRelDef>();
2626
2627                 if (relationshipsRes.isRight()) {
2628                         status = relationshipsRes.right().value();
2629                         log.debug("After fetching all reslationships of resource instance {}. status is {}", resourceInstanceUid, status);
2630                         if (status == TitanOperationStatus.NOT_FOUND) {
2631                                 return Either.left(requirementsResult);
2632                         } else {
2633                                 log.error("Failed to find relationhips of resource instance {}. status is {}", resourceInstanceUid, status);
2634                                 return Either.right(status);
2635                         }
2636                 }
2637
2638                 Map<String, List<ImmutablePair<String, RelationshipInstData>>> sourceNodeToRelationship = new HashMap<String, List<ImmutablePair<String, RelationshipInstData>>>();
2639
2640                 List<ImmutablePair<RelationshipInstData, GraphEdge>> relationshipsImpl = relationshipsRes.left().value();
2641                 status = populateSourceAndRelationsForGivenTarget(sourceNodeToRelationship, relationshipsImpl);
2642
2643                 if (status != TitanOperationStatus.OK) {
2644                         return Either.right(status);
2645                 }
2646
2647                 if (sourceNodeToRelationship.isEmpty()) {
2648                         log.error("No target found for relationship instances of resource instance {}", resourceInstanceUid);
2649                         return Either.right(TitanOperationStatus.INVALID_ELEMENT);
2650                 }
2651
2652                 buildRelationsForTarget(requirementsResult, resourceInstanceUid, sourceNodeToRelationship);
2653                 return Either.left(requirementsResult);
2654         }
2655
2656         @Override
2657         public Either<ComponentInstance, StorageOperationStatus> getFullComponentInstance(ComponentInstance componentInstance, NodeTypeEnum compInstNodeType) {
2658                 Map<String, Map<String, CapabilityDefinition>> compInstCapabilities = new HashMap<String, Map<String, CapabilityDefinition>>();
2659                 Map<String, Map<String, RequirementDefinition>> compInstReq = new HashMap<String, Map<String, RequirementDefinition>>();
2660                 Map<String, Map<String, ArtifactDefinition>> compInstDeploymentArtifacts = new HashMap<String, Map<String, ArtifactDefinition>>();
2661                 Map<String, Map<String, ArtifactDefinition>> compInstInformationalArtifacts = new HashMap<String, Map<String, ArtifactDefinition>>();
2662                 Map<String, Component> compInstOrigins = new HashMap<String, Component>();
2663
2664                 TitanOperationStatus fullResourceInstance = getFullComponentInstance(compInstCapabilities, compInstReq, compInstDeploymentArtifacts, compInstOrigins, componentInstance, compInstNodeType, compInstInformationalArtifacts);
2665                 if (!fullResourceInstance.equals(TitanOperationStatus.OK)) {
2666                         log.debug("failed to get full data of resource instance. error: {}", fullResourceInstance);
2667                         return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(fullResourceInstance));
2668                 }
2669                 return Either.left(componentInstance);
2670         }
2671
2672         private TitanOperationStatus getFullComponentInstance(Map<String, Map<String, CapabilityDefinition>> compInstCapabilities, Map<String, Map<String, RequirementDefinition>> compInstReq,
2673                         Map<String, Map<String, ArtifactDefinition>> compInstDeploymentArtifacts, Map<String, Component> compInstOrigins, ComponentInstance compInst, NodeTypeEnum compInstNodeType,
2674                         Map<String, Map<String, ArtifactDefinition>> compInstInformationalArtifacts) {
2675                 Component component = null;
2676                 ComponentOperation componentOperation = getComponentOperation(compInstNodeType);
2677                 String componentUid = compInst.getComponentUid();
2678                 if (compInstOrigins.containsKey(componentUid)) {
2679                         component = compInstOrigins.get(componentUid);
2680                 } else {
2681                         Either<Component, StorageOperationStatus> metadataComponent = componentOperation.getMetadataComponent(componentUid, true);
2682                         if (metadataComponent.isRight()) {
2683                                 log.debug("Failed to fetch the origin component for component instance, origin Id {}, error: {}", componentUid, metadataComponent.right().value());
2684                                 return TitanOperationStatus.GENERAL_ERROR;
2685                         }
2686                         component = metadataComponent.left().value();
2687                         compInstOrigins.put(componentUid, component);
2688
2689                 }
2690                 String icon = component.getIcon();
2691                 if (log.isDebugEnabled())
2692                         log.debug("Fetch the resource instance icon from the resource itself. icon = {}", icon);
2693                 compInst.setIcon(icon);
2694                 String componentName = component.getName();
2695                 compInst.setComponentName(componentName);
2696                 compInst.setComponentVersion(component.getVersion());
2697                 if (component.getComponentType() == ComponentTypeEnum.RESOURCE) {
2698                         compInst.setToscaComponentName(((Resource) component).getToscaResourceName());
2699                 }
2700
2701                 List<ComponentInstance> componentInstances = new ArrayList<>();
2702                 List<String> derivedFromList = new ArrayList<String>();
2703
2704                 // For VFC/VL/CP
2705                 if (compInstNodeType == NodeTypeEnum.Resource && ((Resource) component).getResourceType() != ResourceTypeEnum.VF) {
2706                         resourceOperation.fillResourceDerivedListFromGraph(component.getUniqueId(), derivedFromList);
2707                 } else {
2708                         // Getting component instances that the origin component of this
2709                         // component instance is their container, so we can use the logic of
2710                         // getting req/cap from them
2711                         // and fill this component instance with those req/cap
2712                         Either<List<ImmutablePair<ComponentInstanceData, GraphEdge>>, TitanOperationStatus> allComponentInstanceFromGraph = getAllComponentInstanceFromGraph(componentUid, compInstNodeType, true);
2713                         if (allComponentInstanceFromGraph.isRight() && allComponentInstanceFromGraph.right().value() != TitanOperationStatus.NOT_FOUND) {
2714                                 log.debug("Couldn't fetch component instances for component {} of type {}", componentUid, compInstNodeType);
2715                                 return allComponentInstanceFromGraph.right().value();
2716                         }
2717                         List<ImmutablePair<ComponentInstanceData, GraphEdge>> allCIs = allComponentInstanceFromGraph.isLeft() ? allComponentInstanceFromGraph.left().value() : new ArrayList<>();
2718                         for (ImmutablePair<ComponentInstanceData, GraphEdge> entry : allCIs) {
2719                                 componentInstances.add(new ComponentInstance(entry.left.getComponentInstDataDefinition()));
2720                         }
2721                         component.setComponentInstances(componentInstances);
2722                 }
2723
2724                 StorageOperationStatus capStatus = setCompInstCapabilitiesFromGraph(compInstCapabilities, component, compInstNodeType, compInst, derivedFromList);
2725                 if (capStatus != StorageOperationStatus.OK) {
2726                         log.debug("Failed to find capability of resource {}. status is {}", componentName, capStatus);
2727
2728                 }
2729                 capStatus = setCompInstRequirementsFromGraph(compInstReq, component, compInstNodeType, compInst);
2730                 if (capStatus != StorageOperationStatus.OK) {
2731                         log.debug("Failed to find requirements of resource {}. status is {}", componentName, capStatus);
2732
2733                 }
2734
2735                 capStatus = setCompInstDeploymentArtifactsFromGraph(compInstDeploymentArtifacts, componentUid, compInst);
2736                 if (capStatus != StorageOperationStatus.OK) {
2737                         log.debug("Failed to find resource deployment artifacts of resource {}. status is {}", componentName, capStatus);
2738
2739                 }
2740
2741                 capStatus = setCompInstInformationalArtifactsResourceFromGraph(compInstInformationalArtifacts, componentUid, compInst);
2742                 if (capStatus != StorageOperationStatus.OK) {
2743                         log.debug("Failed to find resource deployment artifacts of resource {}. status is {}", componentName, capStatus);
2744
2745                 }
2746
2747                 capStatus = setCompInstDeploymentArtifactsFromGraph(compInst);
2748                 if (capStatus != StorageOperationStatus.OK) {
2749                         log.debug("Failed to find resource deployment artifacts of resource instance {} . status is {}", compInst.getName(), capStatus);
2750                 }
2751                 
2752                 capStatus = setCompInstInformationaltArtifactsFromGraph(compInst);
2753                 if (capStatus != StorageOperationStatus.OK) {
2754                         log.debug("Failed to find resource informational artifacts of resource instance {} . status is {}", compInst.getName(), capStatus);
2755                 }
2756
2757                 capStatus = setGroupInstFromGraph(compInst);
2758                 if (capStatus != StorageOperationStatus.OK) {
2759                         log.debug("Failed to find resource groups of resource instance {} . status is {}", compInst.getName(), capStatus);
2760                 }
2761                 return TitanOperationStatus.OK;
2762         }
2763
2764         private StorageOperationStatus setCompInstInformationaltArtifactsFromGraph(ComponentInstance resourceInstance) {
2765                 Map<String, ArtifactDefinition> informationalArtifacts = null;
2766                 if (resourceInstance.getArtifacts() == null) {
2767                         informationalArtifacts = new HashMap<String, ArtifactDefinition>();
2768                 } else {
2769                         informationalArtifacts = new HashMap<String, ArtifactDefinition>(resourceInstance.getArtifacts());
2770                 }
2771
2772                 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> result = artifactOperation.getArtifacts(resourceInstance.getUniqueId(), NodeTypeEnum.ResourceInstance, true, ArtifactGroupTypeEnum.INFORMATIONAL.getType());
2773                 if (result.isRight()) {
2774                         StorageOperationStatus status = result.right().value();
2775                         if (status != StorageOperationStatus.NOT_FOUND) {
2776                                 return status;
2777                         }
2778                 } else {
2779                         informationalArtifacts.putAll(result.left().value());                   
2780                 }
2781                 
2782                 resourceInstance.setArtifacts(informationalArtifacts);
2783                 return StorageOperationStatus.OK;
2784         }
2785
2786         private StorageOperationStatus setGroupInstFromGraph(ComponentInstance compInst) {
2787                 List<GroupInstance> groupInstances = null;
2788
2789                 Either<List<GroupInstance>, StorageOperationStatus> result = groupInstanceOperation.getAllGroupInstances(compInst.getUniqueId(), NodeTypeEnum.ResourceInstance);
2790                 if (result.isRight()) {
2791                         StorageOperationStatus status = result.right().value();
2792                         if (status != StorageOperationStatus.NOT_FOUND) {
2793                                 return status;
2794                         } else {
2795
2796                                 return StorageOperationStatus.OK;
2797                         }
2798                 }
2799
2800                 groupInstances = result.left().value();
2801                 compInst.setGroupInstances(groupInstances);
2802
2803                 return StorageOperationStatus.OK;
2804         }
2805
2806         private StorageOperationStatus setCompInstInformationalArtifactsResourceFromGraph(Map<String, Map<String, ArtifactDefinition>> resourcesInformationalArtifacts, String componentUid, ComponentInstance resourceInstance) {
2807
2808                 if (resourcesInformationalArtifacts.containsKey(componentUid)) {
2809                         resourceInstance.setArtifacts(resourcesInformationalArtifacts.get(componentUid));
2810                         return StorageOperationStatus.OK;
2811                 }
2812
2813                 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> result = artifactOperation.getArtifacts(componentUid, NodeTypeEnum.Resource, true, ArtifactGroupTypeEnum.INFORMATIONAL.getType());
2814                 if (result.isRight()) {
2815                         StorageOperationStatus status = result.right().value();
2816                         if (status != StorageOperationStatus.NOT_FOUND) {
2817                                 return status;
2818                         } else {
2819                                 return StorageOperationStatus.OK;
2820                         }
2821                 }
2822                 Map<String, ArtifactDefinition> artifacts = result.left().value();
2823                 if (!artifacts.isEmpty()) {
2824                         Map<String, ArtifactDefinition> tempArtifacts = new HashMap<>(artifacts);
2825                         for (Entry<String, ArtifactDefinition> artifact : artifacts.entrySet()) {
2826                                 if (!artifact.getValue().checkEsIdExist()) {
2827                                         tempArtifacts.remove(artifact.getKey());
2828                                 }
2829                         }
2830                         resourceInstance.setArtifacts(tempArtifacts);
2831                         resourcesInformationalArtifacts.put(componentUid, tempArtifacts);
2832                 }
2833
2834                 return StorageOperationStatus.OK;
2835
2836         }
2837
2838         protected StorageOperationStatus setCompInstDeploymentArtifactsFromGraph(ComponentInstance resourceInstance) {
2839
2840                 Map<String, ArtifactDefinition> deploymentArtifacts = null;
2841                 if (resourceInstance.getDeploymentArtifacts() == null) {
2842                         deploymentArtifacts = new HashMap<String, ArtifactDefinition>();
2843                 } else {
2844                         deploymentArtifacts = new HashMap<String, ArtifactDefinition>(resourceInstance.getDeploymentArtifacts());
2845                 }
2846
2847                 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> result = artifactOperation.getArtifacts(resourceInstance.getUniqueId(), NodeTypeEnum.ResourceInstance, true, ArtifactGroupTypeEnum.DEPLOYMENT.getType());
2848                 if (result.isRight()) {
2849                         StorageOperationStatus status = result.right().value();
2850                         if (status != StorageOperationStatus.NOT_FOUND) {
2851                                 return status;
2852                         } else {
2853                                 resourceInstance.setDeploymentArtifacts(deploymentArtifacts);
2854                                 return StorageOperationStatus.OK;
2855                         }
2856                 }
2857
2858                 Map<String, ArtifactDefinition> artifacts = result.left().value();
2859                 if ((artifacts != null) && !artifacts.isEmpty()) {
2860                         for (ArtifactDefinition artifact : artifacts.values()) {
2861                                 if (artifact.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())) {
2862                                         Either<List<HeatParameterDefinition>, StorageOperationStatus> heatParamsForEnv = artifactOperation.getHeatParamsForEnv(artifact);
2863                                         if (heatParamsForEnv.isRight()) {
2864                                                 log.debug("failed to get heat parameters values for heat artifact {}", artifact.getUniqueId());
2865                                                 return heatParamsForEnv.right().value();
2866                                         } else {
2867                                                 artifact.setListHeatParameters(heatParamsForEnv.left().value());
2868                                         }
2869                                 }
2870                         }
2871
2872                         // add resource instance artifacts to the artifacts inherited from
2873                         // resource
2874                         deploymentArtifacts.putAll(artifacts);
2875                         resourceInstance.setDeploymentArtifacts(deploymentArtifacts);
2876                 }
2877
2878                 return StorageOperationStatus.OK;
2879
2880         }
2881
2882         private Either<List<ImmutablePair<ComponentInstanceData, GraphEdge>>, TitanOperationStatus> getAllComponentInstanceFromGraph(String componentId, NodeTypeEnum containerNodeType, boolean withEdges) {
2883                 if (log.isDebugEnabled())
2884                         log.debug("Going to fetch all resource instances nodes in graph associate to component {}", componentId);
2885                 Either<List<ImmutablePair<ComponentInstanceData, GraphEdge>>, TitanOperationStatus> resourceInstancesRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(containerNodeType), componentId, GraphEdgeLabels.RESOURCE_INST,
2886                                 NodeTypeEnum.ResourceInstance, ComponentInstanceData.class, withEdges);
2887                 if (log.isDebugEnabled())
2888                         log.debug("After fetching all component instances under component {}", componentId);
2889
2890                 if (resourceInstancesRes.isLeft()) {
2891                         printAllResourceInstancesNames(resourceInstancesRes);
2892                 }
2893                 return resourceInstancesRes;
2894         }
2895
2896         private void printAllResourceInstancesNames(Either<List<ImmutablePair<ComponentInstanceData, GraphEdge>>, TitanOperationStatus> resourceInstancesRes) {
2897                 if (log.isTraceEnabled()) {
2898                         StringBuilder builder = new StringBuilder();
2899                         builder.append("Result is ");
2900                         List<ImmutablePair<ComponentInstanceData, GraphEdge>> listResData = resourceInstancesRes.left().value();
2901                         for (ImmutablePair<ComponentInstanceData, GraphEdge> resInstPair : listResData) {
2902                                 ComponentInstanceData resdata = resInstPair.getLeft();
2903                                 builder.append(resdata.getName()).append(", ");
2904                         }
2905                         log.trace(builder.toString());
2906                 }
2907         }
2908
2909         private TitanOperationStatus populateTargetAndRelationsForGivenSource(Map<String, List<ImmutablePair<String, RelationshipInstData>>> targetNodeToRelationship, List<ImmutablePair<RelationshipInstData, GraphEdge>> relationshipsImpl) {
2910                 if (relationshipsImpl != null && false == relationshipsImpl.isEmpty()) {
2911                         for (ImmutablePair<RelationshipInstData, GraphEdge> pair : relationshipsImpl) {
2912                                 RelationshipInstData relationshipInstData = pair.getKey();
2913
2914                                 GraphEdge requirementEdge = pair.getValue();
2915                                 String requirementName = (String) requirementEdge.getProperties().get(GraphPropertiesDictionary.NAME.getProperty());
2916
2917                                 Either<ImmutablePair<ComponentInstanceData, GraphEdge>, TitanOperationStatus> targetNodeRes = titanGenericDao.getChild(relationshipInstData.getUniqueIdKey(), relationshipInstData.getUniqueId(), GraphEdgeLabels.CAPABILITY_NODE,
2918                                                 NodeTypeEnum.ResourceInstance, ComponentInstanceData.class);
2919
2920                                 if (targetNodeRes.isRight()) {
2921                                         TitanOperationStatus status = targetNodeRes.right().value();
2922                                         log.error("Failed to find the target node of relationship inst {}. status is {}", relationshipInstData, status);
2923                                         return status;
2924                                 }
2925
2926                                 addRelationshipInstToTargetMap(targetNodeToRelationship, relationshipInstData, requirementName, targetNodeRes);
2927
2928                         }
2929                 }
2930
2931                 return TitanOperationStatus.OK;
2932         }
2933
2934         private TitanOperationStatus populateSourceAndRelationsForGivenTarget(Map<String, List<ImmutablePair<String, RelationshipInstData>>> sourceNodeToRelationship, List<ImmutablePair<RelationshipInstData, GraphEdge>> relationshipsImpl) {
2935                 if (relationshipsImpl != null && false == relationshipsImpl.isEmpty()) {
2936                         for (ImmutablePair<RelationshipInstData, GraphEdge> pair : relationshipsImpl) {
2937                                 RelationshipInstData relationshipInstData = pair.getKey();
2938
2939                                 GraphEdge requirementEdge = pair.getValue();
2940                                 String requirementName = (String) requirementEdge.getProperties().get(GraphPropertiesDictionary.NAME.getProperty());
2941
2942                                 Either<ImmutablePair<ComponentInstanceData, GraphEdge>, TitanOperationStatus> sourceNodeRes = titanGenericDao.getParentNode(relationshipInstData.getUniqueIdKey(), relationshipInstData.getUniqueId(), GraphEdgeLabels.RELATIONSHIP_INST,
2943                                                 NodeTypeEnum.ResourceInstance, ComponentInstanceData.class);
2944
2945                                 if (sourceNodeRes.isRight()) {
2946                                         TitanOperationStatus status = sourceNodeRes.right().value();
2947                                         log.error("Failed to find the source node of relationship inst {}. status is {}", relationshipInstData, status);
2948                                         return status;
2949                                 }
2950
2951                                 addRelationshipInstToTargetMap(sourceNodeToRelationship, relationshipInstData, requirementName, sourceNodeRes);
2952
2953                         }
2954                 }
2955
2956                 return TitanOperationStatus.OK;
2957         }
2958
2959         private void buildRelationsForSource(List<RequirementCapabilityRelDef> requirementsResult, String sourceResourceUid, Map<String, List<ImmutablePair<String, RelationshipInstData>>> targetNodeToRelationship) {
2960                 for (Entry<String, List<ImmutablePair<String, RelationshipInstData>>> targetToRel : targetNodeToRelationship.entrySet()) {
2961                         RequirementCapabilityRelDef requirementCapabilityRelDef = new RequirementCapabilityRelDef();
2962                         requirementCapabilityRelDef.setFromNode(sourceResourceUid);
2963                         String targetUid = targetToRel.getKey();
2964                         requirementCapabilityRelDef.setToNode(targetUid);
2965
2966                         List<RequirementAndRelationshipPair> relationships = new ArrayList<RequirementAndRelationshipPair>();
2967
2968                         populateRelationships(targetToRel, relationships);
2969                         requirementCapabilityRelDef.setRelationships(relationships);
2970
2971                         requirementsResult.add(requirementCapabilityRelDef);
2972                 }
2973         }
2974
2975         private void buildRelationsForTarget(List<RequirementCapabilityRelDef> requirementsResult, String targetResourceUid, Map<String, List<ImmutablePair<String, RelationshipInstData>>> sourceNodeToRelationship) {
2976                 for (Entry<String, List<ImmutablePair<String, RelationshipInstData>>> sourceToRel : sourceNodeToRelationship.entrySet()) {
2977                         RequirementCapabilityRelDef requirementCapabilityRelDef = new RequirementCapabilityRelDef();
2978                         requirementCapabilityRelDef.setToNode(targetResourceUid);
2979                         String sourceUid = sourceToRel.getKey();
2980                         requirementCapabilityRelDef.setFromNode(sourceUid);
2981                         List<RequirementAndRelationshipPair> relationships = new ArrayList<RequirementAndRelationshipPair>();
2982
2983                         populateRelationships(sourceToRel, relationships);
2984                         requirementCapabilityRelDef.setRelationships(relationships);
2985
2986                         requirementsResult.add(requirementCapabilityRelDef);
2987                 }
2988         }
2989
2990         private void addRelationshipInstToTargetMap(Map<String, List<ImmutablePair<String, RelationshipInstData>>> targetNodeToRelationship, RelationshipInstData relationshipInstData, String requirementName,
2991                         Either<ImmutablePair<ComponentInstanceData, GraphEdge>, TitanOperationStatus> targetNodeRes) {
2992
2993                 ImmutablePair<ComponentInstanceData, GraphEdge> targetResourcePair = targetNodeRes.left().value();
2994                 ComponentInstanceData targetResourceData = targetResourcePair.getKey();
2995
2996                 GraphEdge edge = targetResourcePair.right;
2997                 if (edge.getEdgeType().equals(GraphEdgeLabels.RELATIONSHIP_INST)) {
2998                         requirementName = (String) edge.getProperties().get(GraphEdgePropertiesDictionary.NAME.getProperty());
2999                 }
3000
3001                 String targetResourceUid = (String) targetResourceData.getUniqueId();
3002                 List<ImmutablePair<String, RelationshipInstData>> requirementRelationshipPair = targetNodeToRelationship.get(targetResourceUid);
3003                 if (requirementRelationshipPair == null) {
3004                         requirementRelationshipPair = new ArrayList<ImmutablePair<String, RelationshipInstData>>();
3005                         targetNodeToRelationship.put(targetResourceUid, requirementRelationshipPair);
3006                 }
3007                 ImmutablePair<String, RelationshipInstData> reqRelationshipPair = new ImmutablePair<String, RelationshipInstData>(requirementName, relationshipInstData);
3008                 requirementRelationshipPair.add(reqRelationshipPair);
3009         }
3010
3011         private void populateRelationships(Entry<String, List<ImmutablePair<String, RelationshipInstData>>> targetToRel, List<RequirementAndRelationshipPair> relationships) {
3012
3013                 List<ImmutablePair<String, RelationshipInstData>> values = targetToRel.getValue();
3014                 for (ImmutablePair<String, RelationshipInstData> value : values) {
3015                         String reqName = value.getKey();
3016                         RelationshipInstData relationshipInstData = value.getValue();
3017                         RelationshipImpl relationshipImpl = new RelationshipImpl();
3018                         relationshipImpl.setType(relationshipInstData.getType());
3019                         RequirementAndRelationshipPair pair = new RequirementAndRelationshipPair(reqName, relationshipImpl);
3020                         pair.setCapabilityOwnerId(relationshipInstData.getCapabilityOwnerId());
3021                         pair.setCapabilityUid(relationshipInstData.getCapabiltyId());
3022                         pair.setRequirementOwnerId(relationshipInstData.getRequirementOwnerId());
3023                         pair.setRequirementUid(relationshipInstData.getRequirementId());
3024                         pair.setId(relationshipInstData.getUniqueId());
3025                         relationships.add(pair);
3026                 }
3027         }
3028
3029         /**
3030          * FOR TEST ONLY
3031          * 
3032          * @param resourceOperation
3033          */
3034         public void setResourceOperation(ResourceOperation resourceOperation) {
3035                 this.resourceOperation = resourceOperation;
3036         }
3037
3038         @Override
3039         public Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances(String componentId, NodeTypeEnum nodeType, RequirementCapabilityRelDef relation, boolean inTransaction, boolean isClone) {
3040
3041                 Either<RequirementCapabilityRelDef, StorageOperationStatus> result = null;
3042                 try {
3043                         Either<RequirementCapabilityRelDef, TitanOperationStatus> multiRequirements = associateResourceInstancesMultiRequirements(componentId, nodeType, relation, isClone);
3044                         if (multiRequirements.isRight()) {
3045                                 TitanOperationStatus status = multiRequirements.right().value();
3046                                 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "associateComponentInstances");
3047                                 BeEcompErrorManager.getInstance().logBeDaoSystemError("associateComponentInstances");
3048                                 log.debug("Failed to associate component instances {}. status is {}", relation, status);
3049                                 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
3050                                 return result;
3051                         }
3052                         StorageOperationStatus updateCalculatedCapReqResult = updateCalculatedCapReq(relation, true);
3053                         if (!updateCalculatedCapReqResult.equals(StorageOperationStatus.OK)) {
3054                                 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "associateComponentInstances");
3055                                 BeEcompErrorManager.getInstance().logBeDaoSystemError("associateComponentInstances");
3056                                 log.debug("Failed to associate component instances. {}. status is {}", relation, updateCalculatedCapReqResult);
3057                                 result = Either.right(updateCalculatedCapReqResult);
3058                                 return result;
3059                         }
3060                         result = Either.left(multiRequirements.left().value());
3061
3062                         return result;
3063
3064                 } finally {
3065                         if (false == inTransaction) {
3066                                 commitOrRollback(result);
3067                         }
3068                 }
3069         }
3070
3071         private Either<RequirementCapabilityRelDef, TitanOperationStatus> associateResourceInstancesMultiRequirements(String componentId, NodeTypeEnum nodeType, RequirementCapabilityRelDef relation, boolean isClone) {
3072
3073                 String fromNode = relation.getFromNode();
3074                 String toNode = relation.getToNode();
3075                 List<RequirementAndRelationshipPair> relationships = relation.getRelationships();
3076                 if (relationships == null || relationships.isEmpty()) {
3077                         BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedAddingResourceInstanceError, "AssociateResourceInstances - missing relationship", fromNode, componentId);
3078                         BeEcompErrorManager.getInstance().logBeFailedAddingResourceInstanceError("AssociateResourceInstances - missing relationship", fromNode, componentId);
3079                         log.debug("No requirement definition sent in order to set the relation between {} to {}", fromNode, toNode);
3080                         return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
3081                 }
3082
3083                 List<RequirementAndRelationshipPair> relationshipsResult = new ArrayList<RequirementAndRelationshipPair>();
3084                 for (RequirementAndRelationshipPair immutablePair : relationships) {
3085                         String requirement = immutablePair.getRequirement();
3086
3087                         Either<RelationshipInstData, TitanOperationStatus> associateRes = connectResourcesInService(componentId, nodeType, fromNode, toNode, immutablePair);
3088
3089                         if (associateRes.isRight()) {
3090                                 TitanOperationStatus status = associateRes.right().value();
3091                                 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedAddingResourceInstanceError, "AssociateResourceInstances", fromNode, componentId);
3092                                 BeEcompErrorManager.getInstance().logBeFailedAddingResourceInstanceError("AssociateResourceInstances - missing relationship", fromNode, componentId);
3093                                 log.debug("Failed to associate resource instance {} to resource instance {}. status is {}", fromNode, toNode, status);
3094                                 return Either.right(status);
3095                         }
3096
3097                         RelationshipInstData relationshipInstData = associateRes.left().value();
3098                         RelationshipImpl relationshipImplResult = new RelationshipImpl();
3099                         relationshipImplResult.setType(relationshipInstData.getType());
3100                         RequirementAndRelationshipPair requirementAndRelationshipPair = new RequirementAndRelationshipPair(requirement, relationshipImplResult);
3101                         requirementAndRelationshipPair.setCapability(immutablePair.getCapability());
3102                         requirementAndRelationshipPair.setCapabilityOwnerId(relationshipInstData.getCapabilityOwnerId());
3103                         requirementAndRelationshipPair.setRequirementOwnerId(relationshipInstData.getRequirementOwnerId());
3104                         requirementAndRelationshipPair.setCapabilityUid(immutablePair.getCapabilityUid());
3105                         requirementAndRelationshipPair.setRequirementUid(immutablePair.getRequirementUid());
3106                         relationshipsResult.add(requirementAndRelationshipPair);
3107                         if (!isClone) {
3108                                 log.trace("update customization UUID for from CI {} and to CI {}", relation.getFromNode(), relation.getToNode());
3109                                 StorageOperationStatus status;
3110                                 status = updateCustomizationUUID(relation.getFromNode());
3111                                 if (status != StorageOperationStatus.OK) {
3112                                         return Either.right(TitanOperationStatus.GENERAL_ERROR);
3113                                 }
3114                                 status = updateCustomizationUUID(relation.getToNode());
3115                                 if (status != StorageOperationStatus.OK) {
3116                                         return Either.right(TitanOperationStatus.GENERAL_ERROR);
3117                                 }
3118                         }
3119
3120                 }
3121
3122                 RequirementCapabilityRelDef capabilityRelDef = new RequirementCapabilityRelDef();
3123                 capabilityRelDef.setFromNode(fromNode);
3124                 capabilityRelDef.setToNode(toNode);
3125                 capabilityRelDef.setRelationships(relationshipsResult);
3126
3127                 return Either.left(capabilityRelDef);
3128         }
3129
3130         @Override
3131         public Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances(String componentId, NodeTypeEnum nodeType, RequirementCapabilityRelDef relation) {
3132                 return associateResourceInstances(componentId, nodeType, relation, false, false);
3133         }
3134
3135         @Override
3136         public Either<List<ComponentInstance>, StorageOperationStatus> deleteAllComponentInstances(String containerComponentId, NodeTypeEnum containerNodeType, boolean inTransaction) {
3137
3138                 Either<List<ComponentInstance>, StorageOperationStatus> result = null;
3139                 try {
3140                         Either<List<ComponentInstance>, TitanOperationStatus> multiRequirements = deleteAllComponentInstancesInternal(containerComponentId, containerNodeType);
3141                         if (multiRequirements.isRight()) {
3142                                 TitanOperationStatus status = multiRequirements.right().value();
3143                                 if (multiRequirements.right().value() != TitanOperationStatus.NOT_FOUND) {
3144                                         BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "deleteAllResourceInstances - missing relationship");
3145                                         BeEcompErrorManager.getInstance().logBeSystemError("deleteAllResourceInstances - missing relationship");
3146                                 }
3147                                 log.debug("Failed to delete resource instances of service {}. status is {}", containerComponentId, status);
3148                                 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
3149                                 return result;
3150
3151                         }
3152
3153                         result = Either.left(multiRequirements.left().value());
3154
3155                         return result;
3156
3157                 } finally {
3158                         if (false == inTransaction) {
3159                                 commitOrRollback(result);
3160                         }
3161                 }
3162
3163         }
3164
3165         @Override
3166         public Either<List<ComponentInstance>, StorageOperationStatus> deleteAllComponentInstances(String containerComponentId, NodeTypeEnum nodeType) {
3167                 return deleteAllComponentInstances(containerComponentId, nodeType, false);
3168         }
3169
3170         public Either<List<ComponentInstance>, TitanOperationStatus> deleteAllComponentInstancesInternal(String componentId, NodeTypeEnum nodeType) {
3171
3172                 log.debug("Going to delete all resource instances and their relatioships from service {}", componentId);
3173
3174                 Either<List<ImmutablePair<ComponentInstanceData, GraphEdge>>, TitanOperationStatus> resourceInstancesRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId, GraphEdgeLabels.RESOURCE_INST,
3175                                 NodeTypeEnum.ResourceInstance, ComponentInstanceData.class);
3176
3177                 if (resourceInstancesRes.isRight()) {
3178                         TitanOperationStatus status = resourceInstancesRes.right().value();
3179                         log.debug("After fetching all resource instances of service {}. status is {}", componentId, status);
3180                         return Either.right(status);
3181                 }
3182
3183                 List<ComponentInstance> result = new ArrayList<ComponentInstance>();
3184                 List<ImmutablePair<ComponentInstanceData, GraphEdge>> listOfResInstances = resourceInstancesRes.left().value();
3185                 for (ImmutablePair<ComponentInstanceData, GraphEdge> resInstance : listOfResInstances) {
3186                         ComponentInstanceData resourceInstanceData = resInstance.getKey();
3187                         String resourceInstUid = resourceInstanceData.getUniqueId();
3188                         Either<ComponentInstance, TitanOperationStatus> removeResourceInstanceRes = removeComponentInstanceFromComponent(nodeType, componentId, resourceInstUid);
3189                         log.debug("After removing resource instance {}. Result is {}", resourceInstUid, removeResourceInstanceRes);
3190                         if (removeResourceInstanceRes.isRight()) {
3191                                 TitanOperationStatus status = removeResourceInstanceRes.right().value();
3192                                 log.error("After removing resource instance {}. status is {}", resourceInstUid, status);
3193                                 return Either.right(status);
3194                         }
3195                         ComponentInstance resourceInstance = removeResourceInstanceRes.left().value();
3196                         result.add(resourceInstance);
3197                 }
3198
3199                 log.debug("The following resource instances was deleted from service {} : {}", componentId, result);
3200
3201                 return Either.left(result);
3202         }
3203
3204         public Either<ImmutablePair<List<ComponentInstance>, Map<String, String>>, StorageOperationStatus> cloneAllComponentInstancesFromContainerComponent(String componentIdFrom, Component component, NodeTypeEnum containerNodeType,
3205                         NodeTypeEnum compInstNodeType, LifecycleStateEnum targetLifecycle, Map<String, List<ComponentInstanceInput>> inputsValuesMap) {
3206
3207                 List<ComponentInstance> list = new ArrayList<ComponentInstance>();
3208                 Map<String, String> oldCompInstToNew = new HashMap<>();
3209
3210                 ImmutablePair<List<ComponentInstance>, Map<String, String>> result = new ImmutablePair<List<ComponentInstance>, Map<String, String>>(list, oldCompInstToNew);
3211
3212                 Either<ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>>, StorageOperationStatus> allResourceInstances = getAllComponentInstances(componentIdFrom, containerNodeType, compInstNodeType, true);
3213
3214                 if (allResourceInstances.isRight()) {
3215                         StorageOperationStatus status = allResourceInstances.right().value();
3216                         if (status.equals(StorageOperationStatus.NOT_FOUND)) {
3217
3218                                 return Either.left(result);
3219                         } else {
3220                                 log.error("failed to get all resource instances for service {}. status={}", componentIdFrom, status);
3221                                 return Either.right(status);
3222                         }
3223                 }
3224
3225                 List<ComponentInstance> riList = allResourceInstances.left().value().left;
3226                 Map<String, ComponentInstance> riMapper = new HashMap<>();
3227                 int instanceNumber = 0;
3228                 for (ComponentInstance ri : riList) {
3229                         instanceNumber++;
3230                         String origRiUniqueID = ri.getUniqueId();
3231                         Either<ComponentInstance, StorageOperationStatus> createResourceInstance = createComponentInstance(component.getUniqueId(), containerNodeType, String.valueOf(instanceNumber), false, ri, compInstNodeType, true, true);
3232                         if (createResourceInstance.isRight()) {
3233                                 StorageOperationStatus status = createResourceInstance.right().value();
3234                                 log.error("failed to clone resource instance {}. status ={}", origRiUniqueID, status);
3235                                 return Either.right(status);
3236                         }
3237                         ComponentInstance createdInstance = createResourceInstance.left().value();
3238                         riMapper.put(origRiUniqueID, createdInstance);
3239                         StorageOperationStatus associateArtifactsToResource = cloneResourceInstanceArtifacts(createdInstance, ri, targetLifecycle);
3240                         if (associateArtifactsToResource != StorageOperationStatus.OK) {
3241                                 log.debug("failed to clone resource instance {} artifacts. error {} ", ri.getNormalizedName(), associateArtifactsToResource.name());
3242                                 return Either.right(associateArtifactsToResource);
3243                         }
3244
3245                         StorageOperationStatus associatePropertyValuesToResource = cloneResourceInstancePropertyValues(createdInstance, ri);
3246                         if (associatePropertyValuesToResource != StorageOperationStatus.OK) {
3247                                 log.debug("failed to clone resource instance {} property values. error {} ", ri.getNormalizedName(), associatePropertyValuesToResource.name());
3248                                 return Either.right(associatePropertyValuesToResource);
3249                         }
3250
3251                         StorageOperationStatus associateAttributeValuesToResource = cloneResourceInstanceAttributeValues(createdInstance, ri);
3252                         if (associateAttributeValuesToResource != StorageOperationStatus.OK) {
3253                                 log.debug("failed to clone resource instance {} attribute values. error {} ", ri.getNormalizedName(), associateAttributeValuesToResource.name());
3254                                 return Either.right(associateAttributeValuesToResource);
3255                         }
3256
3257                         StorageOperationStatus associateInputValuesToResource = cloneResourceInstanceInputsValues(createdInstance, ri, component, inputsValuesMap);
3258                         if (associateInputValuesToResource != StorageOperationStatus.OK) {
3259                                 log.debug("failed to clone resource instance {} property values. error {} ", ri.getNormalizedName(), associatePropertyValuesToResource.name());
3260                                 return Either.right(associatePropertyValuesToResource);
3261                         }
3262
3263                         list.add(createdInstance);
3264                         oldCompInstToNew.put(origRiUniqueID, createdInstance.getUniqueId());
3265                 }
3266
3267                 List<RequirementCapabilityRelDef> relationsList = allResourceInstances.left().value().right;
3268                 for (RequirementCapabilityRelDef relation : relationsList) {
3269                         String origFrom = relation.getFromNode();
3270                         String origTo = relation.getToNode();
3271                         relation.setFromNode(riMapper.get(origFrom).getUniqueId());
3272                         relation.setToNode(riMapper.get(origTo).getUniqueId());
3273                         List<RequirementAndRelationshipPair> relationships = relation.getRelationships();
3274                         for (RequirementAndRelationshipPair pair : relationships) {
3275                                 // for all atomic resource instances need to update to relevant
3276                                 // new ri ids
3277                                 String capOwnerId = pair.getCapabilityOwnerId();
3278                                 String reqOwnerId = pair.getRequirementOwnerId();
3279                                 if (isAtomicComponentInstance(riMapper.get(origFrom))) {
3280                                         reqOwnerId = riMapper.get(reqOwnerId).getUniqueId();
3281                                 }
3282                                 if (isAtomicComponentInstance(riMapper.get(origTo))) {
3283                                         capOwnerId = riMapper.get(capOwnerId).getUniqueId();
3284                                 }
3285                                 pair.setRequirementOwnerId(reqOwnerId);
3286                                 pair.setCapabilityOwnerId(capOwnerId);
3287                         }
3288
3289                         Either<RequirementCapabilityRelDef, StorageOperationStatus> associateInstances = associateResourceInstances(component.getUniqueId(), containerNodeType, relation, true, true);
3290                         if (associateInstances.isRight()) {
3291                                 StorageOperationStatus status = associateInstances.right().value();
3292                                 log.error("failed to assosiate resource instance {} and resource instance {}. status ={}", relation.getFromNode(), relation.getToNode(), status);
3293                                 return Either.right(status);
3294                         }
3295                 }
3296
3297                 return Either.left(result);
3298         }
3299
3300         public Either<ImmutablePair<List<ComponentInstance>, Map<String, String>>, StorageOperationStatus> cloneAllComponentInstancesFromContainerComponent(String componentIdFrom, String componentIdTo, NodeTypeEnum containerNodeType,
3301                         NodeTypeEnum compInstNodeType, LifecycleStateEnum targetLifecycle, TitanVertex metadataVertex, Resource prevResource, Resource newResource, Map<String, List<ComponentInstanceProperty>> inputsPropMap) {
3302
3303                 List<ComponentInstance> list = new ArrayList<ComponentInstance>();
3304                 Map<String, String> oldCompInstToNew = new HashMap<>();
3305
3306                 ImmutablePair<List<ComponentInstance>, Map<String, String>> result = new ImmutablePair<List<ComponentInstance>, Map<String, String>>(list, oldCompInstToNew);
3307
3308                 List<ComponentInstance> riList = prevResource.getComponentInstances();
3309                 Map<String, ComponentInstance> riMapper = new HashMap<>();
3310                 int instanceNumber = 0;
3311                 long timeProperties = 0;
3312                 if (riList != null) {
3313                         for (ComponentInstance ri : riList) {
3314                                 instanceNumber++;
3315                                 String origRiUniqueID = ri.getUniqueId();
3316                                 Either<TitanVertex, StorageOperationStatus> createResourceInstance = createComponentInstance(componentIdTo, containerNodeType, String.valueOf(instanceNumber), false, ri, compInstNodeType, true, true, metadataVertex);
3317                                 if (createResourceInstance.isRight()) {
3318                                         StorageOperationStatus status = createResourceInstance.right().value();
3319                                         log.error("failed to clone resource instance {}. status ={}", origRiUniqueID, status);
3320                                         return Either.right(status);
3321                                 }
3322                                 TitanVertex createdInstance = createResourceInstance.left().value();
3323                                 String createdInstanceId = (String) titanGenericDao.getProperty(createdInstance, GraphPropertiesDictionary.UNIQUE_ID.getProperty());
3324
3325                                 StorageOperationStatus associateArtifactsToResource = cloneResourceInstanceArtifacts(createdInstance, ri, targetLifecycle);
3326                                 if (associateArtifactsToResource != StorageOperationStatus.OK) {
3327                                         log.debug("failed to clone resource instance {} artifacts. error {} ", ri.getNormalizedName(), associateArtifactsToResource.name());
3328                                         return Either.right(associateArtifactsToResource);
3329                                 }
3330
3331                                 long start = System.currentTimeMillis();
3332                                 StorageOperationStatus associatePropertyValuesToResource = cloneResourceInstancePropertyValues(createdInstance, ri, inputsPropMap, newResource);
3333                                 if (associatePropertyValuesToResource != StorageOperationStatus.OK) {
3334                                         log.debug("failed to clone resource instance {} property values. error {} ", ri.getNormalizedName(), associatePropertyValuesToResource.name());
3335                                         return Either.right(associatePropertyValuesToResource);
3336                                 }
3337                                 long end = System.currentTimeMillis();
3338                                 timeProperties += (end - start);
3339
3340                                 StorageOperationStatus associateAttributeValuesToResource = cloneResourceInstanceAttributeValues(createdInstance, ri, createdInstanceId);
3341                                 if (associateAttributeValuesToResource != StorageOperationStatus.OK) {
3342                                         log.debug("failed to clone resource instance {} attribute values. error {} ", ri.getNormalizedName(), associateAttributeValuesToResource.name());
3343                                         return Either.right(associateAttributeValuesToResource);
3344                                 }
3345
3346                                 StorageOperationStatus associateInputValuesToResource = cloneResourceInstanceInputsValues(createdInstance, ri, createdInstanceId, newResource, null);
3347                                 if (associateInputValuesToResource != StorageOperationStatus.OK) {
3348                                         log.debug("failed to clone resource instance {} property values. error {} ", ri.getNormalizedName(), associatePropertyValuesToResource.name());
3349                                         return Either.right(associatePropertyValuesToResource);
3350                                 }
3351                                 Map<String, Object> properties = titanGenericDao.getProperties(createdInstance);
3352                                 ComponentInstanceData createdComponentInstance = GraphElementFactory.createElement(NodeTypeEnum.ResourceInstance.getName(), GraphElementTypeEnum.Node, properties, ComponentInstanceData.class);
3353                                 ComponentInstance createdResourceInstance = new ComponentInstance(createdComponentInstance.getComponentInstDataDefinition());
3354                                 riMapper.put(origRiUniqueID, createdResourceInstance);
3355
3356                                 list.add(createdResourceInstance);
3357                                 oldCompInstToNew.put(origRiUniqueID, createdResourceInstance.getUniqueId());
3358                         }
3359                 }
3360                 log.info("*********** total properties in ms {}", timeProperties);
3361
3362                 // List<RequirementCapabilityRelDef> relationsList =
3363                 // instanceRelationPair.right;
3364                 List<RequirementCapabilityRelDef> relationsList = prevResource.getComponentInstancesRelations();
3365                 if (relationsList != null) {
3366                         for (RequirementCapabilityRelDef relation : relationsList) {
3367                                 String origFrom = relation.getFromNode();
3368                                 String origTo = relation.getToNode();
3369                                 relation.setFromNode(riMapper.get(origFrom).getUniqueId());
3370                                 relation.setToNode(riMapper.get(origTo).getUniqueId());
3371                                 List<RequirementAndRelationshipPair> relationships = relation.getRelationships();
3372                                 for (RequirementAndRelationshipPair pair : relationships) {
3373                                         // for all atomic resource instances need to update to
3374                                         // relevant
3375                                         // new ri ids
3376                                         String capOwnerId = pair.getCapabilityOwnerId();
3377                                         String reqOwnerId = pair.getRequirementOwnerId();
3378                                         if (isAtomicComponentInstance(riMapper.get(origFrom))) {
3379                                                 reqOwnerId = riMapper.get(reqOwnerId).getUniqueId();
3380                                         }
3381                                         if (isAtomicComponentInstance(riMapper.get(origTo))) {
3382                                                 capOwnerId = riMapper.get(capOwnerId).getUniqueId();
3383                                         }
3384                                         pair.setRequirementOwnerId(reqOwnerId);
3385                                         pair.setCapabilityOwnerId(capOwnerId);
3386                                 }
3387
3388                                 Either<RequirementCapabilityRelDef, StorageOperationStatus> associateInstances = associateResourceInstances(componentIdTo, containerNodeType, relation, true, true);
3389                                 if (associateInstances.isRight()) {
3390                                         StorageOperationStatus status = associateInstances.right().value();
3391                                         log.error("failed to assosiate resource instance {} and resource instance {}. status ={}", relation.getFromNode(), relation.getToNode(), status);
3392                                         return Either.right(status);
3393                                 }
3394                         }
3395                 }
3396                 return Either.left(result);
3397         }
3398
3399         private boolean isAtomicComponentInstance(ComponentInstance componentInstance) {
3400                 OriginTypeEnum originType = componentInstance.getOriginType();
3401                 if (originType == OriginTypeEnum.VFC || originType == OriginTypeEnum.VFCMT || originType == OriginTypeEnum.VL || originType == OriginTypeEnum.CP) {
3402                         return true;
3403                 }
3404                 return false;
3405         }
3406
3407         private StorageOperationStatus cloneResourceInstanceArtifacts(ComponentInstance toResourceInstance, ComponentInstance fromResourceInstance, LifecycleStateEnum targetLifecycle) {
3408
3409                 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifactsOfRI = artifactOperation.getArtifacts(fromResourceInstance.getUniqueId(), NodeTypeEnum.ResourceInstance, true);
3410                 if (getArtifactsOfRI.isRight()) {
3411                         StorageOperationStatus status = getArtifactsOfRI.right().value();
3412                         if (status.equals(StorageOperationStatus.NOT_FOUND)) {
3413                                 status = StorageOperationStatus.OK;
3414                         }
3415                         return status;
3416                 }
3417
3418                 Map<String, ArtifactDefinition> artifacts = getArtifactsOfRI.left().value();
3419                 List<GroupInstance> groupInstancesFrom = fromResourceInstance.getGroupInstances();
3420                 List<GroupInstance> groupInstancesTo = toResourceInstance.getGroupInstances();
3421                 Map<String, List<String>> groupsInstanceArtifact = new HashMap<String, List<String>>();
3422                 for (Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
3423
3424                         ArtifactDefinition artifactDefinition = entry.getValue();
3425                         String generatedFromIdArtifactUid = artifactDefinition.getGeneratedFromId();
3426
3427                         // US687135 Do not Add VF_MODULES_METADATA when checking out
3428                         if (ArtifactTypeEnum.VF_MODULES_METADATA.getType().equals(artifactDefinition.getArtifactType())) {
3429                                 // The artifact of type VF_MODULES_METADATA should not be cloned
3430                                 // unless we are changing the state to certified.
3431                                 if (targetLifecycle != null && targetLifecycle != LifecycleStateEnum.CERTIFIED) {
3432                                         continue;
3433                                 }
3434                         }
3435                         Either<ArtifactDefinition, StorageOperationStatus> addArifactToResource = Either.left(artifactDefinition);
3436
3437                         addArifactToResource = artifactOperation.addArifactToComponent(artifactDefinition, toResourceInstance.getUniqueId(), NodeTypeEnum.ResourceInstance, false, true);
3438
3439                         if (addArifactToResource.isRight()) {
3440                                 return addArifactToResource.right().value();
3441                         }
3442
3443                         if (groupInstancesTo != null) {
3444                                 for (GroupInstance groupInstanceTo : groupInstancesTo) {
3445                                         Optional<String> op = groupInstanceTo.getArtifacts().stream().filter(p -> p.equals(generatedFromIdArtifactUid)).findAny();
3446                                         if (op.isPresent()) {
3447
3448                                                 List<String> artifactsUid = null;
3449                                                 if (groupsInstanceArtifact.containsKey(groupInstanceTo.getUniqueId())) {
3450                                                         artifactsUid = groupsInstanceArtifact.get(groupInstanceTo.getUniqueId());
3451                                                 } else {
3452                                                         artifactsUid = new ArrayList<String>();
3453                                                 }
3454                                                 artifactsUid.add(addArifactToResource.left().value().getUniqueId());
3455                                                 groupsInstanceArtifact.put(groupInstanceTo.getUniqueId(), artifactsUid);
3456                                                 break;
3457                                         }
3458                                 }
3459
3460                         }
3461                 }
3462                 if (groupsInstanceArtifact != null && !groupsInstanceArtifact.isEmpty()) {
3463                         for (Map.Entry<String, List<String>> groupArtifact : groupsInstanceArtifact.entrySet()) {
3464                                 groupInstanceOperation.associateArtifactsToGroupInstance(groupArtifact.getKey(), groupArtifact.getValue());
3465                         }
3466                 }
3467                 Either<List<GroupInstance>, StorageOperationStatus> groupInstanceStatus = groupInstanceOperation.getAllGroupInstances(toResourceInstance.getUniqueId(), NodeTypeEnum.ResourceInstance);
3468                 if (groupInstanceStatus.isRight()) {
3469                         log.debug("failed to get groupinstance for component inatance {}", toResourceInstance.getUniqueId());
3470                         return groupInstanceStatus.right().value();
3471                 }
3472                 toResourceInstance.setGroupInstances(groupInstanceStatus.left().value());
3473                 toResourceInstance.setDeploymentArtifacts(artifacts);
3474                 return StorageOperationStatus.OK;
3475         }
3476
3477         private StorageOperationStatus cloneResourceInstanceArtifacts(TitanVertex toResourceInstance, ComponentInstance fromResourceInstance, LifecycleStateEnum targetLifecycle) {
3478
3479                 Either<Map<String, TitanVertex>, StorageOperationStatus> getArtifactsOfRI = artifactOperation.getArtifactsVertecies(fromResourceInstance.getUniqueId(), NodeTypeEnum.ResourceInstance, true);
3480                 if (getArtifactsOfRI.isRight()) {
3481                         StorageOperationStatus status = getArtifactsOfRI.right().value();
3482                         if (status.equals(StorageOperationStatus.NOT_FOUND)) {
3483                                 status = StorageOperationStatus.OK;
3484                         }
3485                         return status;
3486                 }
3487
3488                 Map<String, TitanVertex> artifacts = getArtifactsOfRI.left().value();
3489                 for (Entry<String, TitanVertex> entry : artifacts.entrySet()) {
3490
3491                         TitanVertex artifactVertex = entry.getValue();
3492                         // US687135 Do not Add VF_MODULES_METADATA when checking out
3493                         String artifactType = (String) titanGenericDao.getProperty(artifactVertex, GraphPropertiesDictionary.ARTIFACT_TYPE.getProperty());
3494                         String label = (String) titanGenericDao.getProperty(artifactVertex, GraphPropertiesDictionary.ARTIFACT_LABEL.getProperty());
3495                         if (ArtifactTypeEnum.VF_MODULES_METADATA.getType().equals(artifactType)) {
3496                                 // The artifact of type VF_MODULES_METADATA should not be cloned
3497                                 // unless we are changing the state to certified.
3498                                 if (targetLifecycle != null && targetLifecycle != LifecycleStateEnum.CERTIFIED) {
3499                                         continue;
3500                                 }
3501                         }
3502
3503                         StorageOperationStatus addArifactToResource = artifactOperation.addArifactToComponent(artifactVertex, toResourceInstance, label);
3504
3505                         if (!addArifactToResource.equals(StorageOperationStatus.OK)) {
3506                                 return addArifactToResource;
3507                         }
3508                 }
3509                 // toResourceInstance.setDeploymentArtifacts(artifacts);
3510                 return StorageOperationStatus.OK;
3511         }
3512
3513         public Either<Integer, StorageOperationStatus> increaseAndGetResourceInstanceSpecificCounter(String resourceInstanceId, GraphPropertiesDictionary counterType, boolean inTransaction) {
3514
3515                 Either<Integer, StorageOperationStatus> result = null;
3516                 try {
3517
3518                         Either<TitanGraph, TitanOperationStatus> graphResult = titanGenericDao.getGraph();
3519                         if (graphResult.isRight()) {
3520                                 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graphResult.right().value()));
3521                                 return result;
3522                         }
3523                         Either<TitanVertex, TitanOperationStatus> vertexService = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceId);
3524                         if (vertexService.isRight()) {
3525                                 log.debug("failed to fetch vertex of resource instance for id = {}", resourceInstanceId);
3526                                 TitanOperationStatus status = vertexService.right().value();
3527                                 if (status == TitanOperationStatus.NOT_FOUND) {
3528                                         status = TitanOperationStatus.INVALID_ID;
3529                                 }
3530                                 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexService.right().value()));
3531                                 return result;
3532                         }
3533                         Vertex vertex = vertexService.left().value();
3534
3535                         VertexProperty<Object> vertexProperty = vertex.property(counterType.getProperty());
3536                         Integer counter = 0;
3537                         if (vertexProperty.isPresent()) {
3538                                 if (vertexProperty.value() != null) {
3539                                         counter = (Integer) vertexProperty.value();
3540                                 }
3541                         }
3542
3543                         counter++;
3544                         vertex.property(counterType.getProperty(), counter);
3545
3546                         result = Either.left(counter);
3547                         return result;
3548
3549                 } finally {
3550                         if (false == inTransaction) {
3551                                 if (result == null || result.isRight()) {
3552                                         log.error("increaseAndGetResourceInstanceSpecificCounter operation : Going to execute rollback on graph.");
3553                                         titanGenericDao.rollback();
3554                                 } else {
3555                                         log.debug("increaseAndGetResourceInstanceSpecificCounter operation : Going to execute commit on graph.");
3556                                         titanGenericDao.commit();
3557                                 }
3558                         }
3559                 }
3560
3561         }
3562
3563         public Either<Integer, StorageOperationStatus> increaseAndGetResourceInstanceSpecificCounter(TitanVertex resourceInstanceVertex, GraphPropertiesDictionary counterType) {
3564
3565                 Either<Integer, StorageOperationStatus> result = null;
3566
3567                 VertexProperty<Object> vertexProperty = resourceInstanceVertex.property(counterType.getProperty());
3568                 Integer counter = 0;
3569                 if (vertexProperty.isPresent()) {
3570                         if (vertexProperty.value() != null) {
3571                                 counter = (Integer) vertexProperty.value();
3572                         }
3573                 }
3574                 counter++;
3575                 resourceInstanceVertex.property(counterType.getProperty(), counter);
3576
3577                 result = Either.left(counter);
3578                 return result;
3579
3580         }
3581
3582         @Override
3583         public Either<List<String>, StorageOperationStatus> getAllComponentInstancesNames(String serviceId, NodeTypeEnum nodeType, boolean inTransaction) {
3584
3585                 Either<List<String>, StorageOperationStatus> result = null;
3586
3587                 try {
3588
3589                         Either<List<String>, TitanOperationStatus> resInstancesOfService = getComponentInstancesNameOfService(serviceId, nodeType);
3590
3591                         log.debug("After fetching resource instances of service {}. result is {}", serviceId, resInstancesOfService);
3592                         if (resInstancesOfService.isRight()) {
3593                                 TitanOperationStatus status = resInstancesOfService.right().value();
3594                                 if (status != TitanOperationStatus.NOT_FOUND) {
3595                                         log.error("Failed to find resource instances of service {}. status is {}", serviceId, status);
3596                                 }
3597                                 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
3598                                 return result;
3599                         }
3600
3601                         List<String> names = resInstancesOfService.left().value();
3602
3603                         if (names == null || names.isEmpty()) {
3604                                 return Either.right(StorageOperationStatus.NOT_FOUND);
3605                         }
3606
3607                         result = Either.left(names);
3608
3609                 } finally {
3610                         if (false == inTransaction) {
3611                                 commitOrRollback(result);
3612                         }
3613                 }
3614                 return result;
3615         }
3616
3617         private Either<List<String>, TitanOperationStatus> getComponentInstancesNameOfService(String serviceId, NodeTypeEnum nodeType) {
3618
3619                 List<String> resourcesInstanseName = new ArrayList<String>();
3620                 Either<List<ImmutablePair<ComponentInstanceData, GraphEdge>>, TitanOperationStatus> resourceInstancesRes = getAllComponentInstanceFromGraph(serviceId, nodeType, false);
3621                 if (resourceInstancesRes.isRight()) {
3622                         TitanOperationStatus status = resourceInstancesRes.right().value();
3623                         log.debug("Resource instance was found under service {}. status is {}", serviceId, status);
3624                         return Either.right(status);
3625                 }
3626
3627                 List<ImmutablePair<ComponentInstanceData, GraphEdge>> resourceInstances = resourceInstancesRes.left().value();
3628                 if (resourceInstances != null && false == resourceInstances.isEmpty()) {
3629
3630                         for (ImmutablePair<ComponentInstanceData, GraphEdge> immutablePair : resourceInstances) {
3631                                 ComponentInstanceData resourceInstanceData = immutablePair.getKey();
3632                                 log.debug("Going to fetch the relationships of resource instance {}", resourceInstanceData);
3633                                 resourcesInstanseName.add(resourceInstanceData.getComponentInstDataDefinition().getName());
3634
3635                         }
3636                 }
3637
3638                 return Either.left(resourcesInstanseName);
3639         }
3640
3641         @Override
3642         public Either<List<String>, StorageOperationStatus> getAllComponentInstancesNames(String componentId, NodeTypeEnum nodeType) {
3643
3644                 return getAllComponentInstancesNames(componentId, nodeType, false);
3645         }
3646
3647         @Override
3648         public Either<ComponentInstance, StorageOperationStatus> getResourceInstanceById(String resourceId) {
3649                 Either<ComponentInstanceData, TitanOperationStatus> resourceInstanceData = findResourceInstance(resourceId);
3650
3651                 if (resourceInstanceData.isRight()) {
3652                         return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resourceInstanceData.right().value()));
3653                 }
3654
3655                 return Either.left(new ComponentInstance(resourceInstanceData.left().value().getComponentInstDataDefinition()));
3656
3657         }
3658
3659         private StorageOperationStatus setCompInstDeploymentArtifactsFromGraph(Map<String, Map<String, ArtifactDefinition>> resourcesArtifacts, String uniqueId, ComponentInstance resourceInstance) {
3660
3661                 if (resourcesArtifacts.containsKey(uniqueId)) {
3662                         resourceInstance.setDeploymentArtifacts(resourcesArtifacts.get(uniqueId));
3663                         return StorageOperationStatus.OK;
3664                 }
3665
3666                 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> result = artifactOperation.getArtifacts(uniqueId, NodeTypeEnum.Resource, true, ArtifactGroupTypeEnum.DEPLOYMENT.getType());
3667                 if (result.isRight()) {
3668                         StorageOperationStatus status = result.right().value();
3669                         if (status != StorageOperationStatus.NOT_FOUND) {
3670                                 return status;
3671                         } else {
3672                                 return StorageOperationStatus.OK;
3673                         }
3674                 }
3675                 Map<String, ArtifactDefinition> artifacts = result.left().value();
3676                 if (!artifacts.isEmpty()) {
3677                         Map<String, ArtifactDefinition> tempArtifacts = new HashMap<String, ArtifactDefinition>(artifacts);
3678                         for (Entry<String, ArtifactDefinition> artifact : artifacts.entrySet()) {
3679                                 if (!artifact.getValue().checkEsIdExist()) {
3680                                         tempArtifacts.remove(artifact.getKey());
3681                                 }
3682                         }
3683                         resourceInstance.setDeploymentArtifacts(tempArtifacts);
3684                         resourcesArtifacts.put(uniqueId, tempArtifacts);
3685                 }
3686
3687                 return StorageOperationStatus.OK;
3688
3689         }
3690
3691         private StorageOperationStatus setCompInstCapabilitiesFromGraph(Map<String, Map<String, CapabilityDefinition>> resourcesCapabilities, Component component, NodeTypeEnum compInstType, ComponentInstance resourceInstance,
3692                         List<String> respourceDerivedList) {
3693
3694                 StorageOperationStatus status;
3695                 ComponentOperation componentOperation = getComponentOperation(compInstType);
3696                 Either<Map<String, List<CapabilityDefinition>>, TitanOperationStatus> eitherCapabilities = componentOperation.getCapabilities(component, compInstType, true);
3697                 if (eitherCapabilities.isLeft()) {
3698                         status = StorageOperationStatus.OK;
3699                         Map<String, List<CapabilityDefinition>> capabilities = eitherCapabilities.left().value();
3700                         if (capabilities != null && !capabilities.isEmpty()) {
3701                                 capabilities.forEach((type, list) -> {
3702                                         if (list != null && !list.isEmpty()) {
3703                                                 list.forEach((capability) -> {
3704                                                         // We want to set ownerId only for instances coming
3705                                                         // from atomic resources, otherwise we don't want
3706                                                         // to overwrite the existing ownerId of underlying
3707                                                         // component instances
3708                                                         if (isAtomicResource(component)) {
3709                                                                 capability.setOwnerId(resourceInstance.getUniqueId());
3710                                                                 capability.setOwnerName(resourceInstance.getName());
3711                                                                 capability.setCapabilitySources(respourceDerivedList);
3712                                                         }
3713                                                 });
3714                                         }
3715                                 });
3716                                 resourceInstance.setCapabilities(capabilities);
3717                         }
3718                 } else {
3719                         status = StorageOperationStatus.GENERAL_ERROR;
3720                 }
3721                 return status;
3722
3723         }
3724
3725         private StorageOperationStatus setCompInstRequirementsFromGraph(Map<String, Map<String, RequirementDefinition>> resourcesReq, Component component, NodeTypeEnum compInstType, ComponentInstance resourceInstance) {
3726                 StorageOperationStatus status;
3727                 ComponentOperation componentOperation = getComponentOperation(compInstType);
3728                 Either<Map<String, List<RequirementDefinition>>, TitanOperationStatus> eitherCapabilities = componentOperation.getRequirements(component, compInstType, true);
3729                 if (eitherCapabilities.isLeft()) {
3730                         status = StorageOperationStatus.OK;
3731                         Map<String, List<RequirementDefinition>> requirements = eitherCapabilities.left().value();
3732                         if (requirements != null && !requirements.isEmpty()) {
3733                                 // We want to set ownerId only for instances coming from atomic
3734                                 // resources, otherwise we don't want
3735                                 // to overwrite the existing ownerId of underlying component
3736                                 // instances
3737                                 if (isAtomicResource(component)) {
3738                                         requirements.forEach((type, list) -> {
3739                                                 if (list != null && !list.isEmpty()) {
3740                                                         list.forEach((requirement) -> {
3741                                                                 requirement.setOwnerId(resourceInstance.getUniqueId());
3742                                                                 requirement.setOwnerName(resourceInstance.getName());
3743                                                         });
3744                                                 }
3745                                         });
3746                                 }
3747                                 resourceInstance.setRequirements(requirements);
3748                         }
3749                 } else {
3750                         status = StorageOperationStatus.GENERAL_ERROR;
3751                 }
3752                 return status;
3753         }
3754
3755         @Override
3756         public Either<List<ImmutablePair<CapabilityData, GraphEdge>>, TitanOperationStatus> getCapabilities(ComponentInstance compInstance, NodeTypeEnum nodeTypeEnum) {
3757                 DataNodeCollector<CapabilityData> collector = () -> titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeTypeEnum), compInstance.getUniqueId(), GraphEdgeLabels.CALCULATED_CAPABILITY, NodeTypeEnum.Capability,
3758                                 CapabilityData.class);
3759
3760                 return getDataFromGraph(collector);
3761         }
3762
3763         @Override
3764         public Either<List<ImmutablePair<RequirementData, GraphEdge>>, TitanOperationStatus> getRequirements(ComponentInstance compInstance, NodeTypeEnum nodeTypeEnum) {
3765
3766                 DataNodeCollector<RequirementData> collector = () -> titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeTypeEnum), compInstance.getUniqueId(), GraphEdgeLabels.CALCULATED_REQUIREMENT, NodeTypeEnum.Requirement,
3767                                 RequirementData.class);
3768
3769                 return getDataFromGraph(collector);
3770
3771         }
3772
3773         @Override
3774         public Either<List<ImmutablePair<CapabilityData, GraphEdge>>, TitanOperationStatus> getFulfilledCapabilities(ComponentInstance compInstance, NodeTypeEnum nodeTypeEnum) {
3775                 DataNodeCollector<CapabilityData> collector = () -> titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeTypeEnum), compInstance.getUniqueId(), GraphEdgeLabels.CALCULATED_CAPABILITY_FULLFILLED, NodeTypeEnum.Capability,
3776                                 CapabilityData.class);
3777
3778                 return getDataFromGraph(collector);
3779         }
3780
3781         @Override
3782         public Either<List<ImmutablePair<RequirementData, GraphEdge>>, TitanOperationStatus> getFulfilledRequirements(ComponentInstance compInstance, NodeTypeEnum nodeTypeEnum) {
3783
3784                 DataNodeCollector<RequirementData> collector = () -> titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeTypeEnum), compInstance.getUniqueId(), GraphEdgeLabels.CALCULATED_REQUIREMENT_FULLFILLED, NodeTypeEnum.Requirement,
3785                                 RequirementData.class);
3786
3787                 return getDataFromGraph(collector);
3788
3789         }
3790
3791         public Either<Boolean, StorageOperationStatus> isAvailableRequirement(ComponentInstance fromResInstance, RequirementAndRelationshipPair relationPair) {
3792                 Either<TitanVertex, TitanOperationStatus> fromRi = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), fromResInstance.getUniqueId());
3793                 if (fromRi.isRight()) {
3794                         log.debug("Failed to fetch component instance {}  error {}", fromResInstance.getUniqueId(), fromRi.right().value());
3795                         return Either.right(StorageOperationStatus.NOT_FOUND);
3796                 }
3797                 Iterator<Edge> edgeIter = fromRi.left().value().edges(Direction.OUT, GraphEdgeLabels.CALCULATED_REQUIREMENT.name());
3798                 if (edgeIter == null || !edgeIter.hasNext()) {
3799                         log.debug("No available CALCULATED_REQUIREMENT edges. All full filled for RI {}", fromResInstance.getUniqueId());
3800                         return Either.left(false);
3801                 }
3802                 boolean exist = false;
3803                 while (edgeIter.hasNext()) {
3804                         Edge edge = edgeIter.next();
3805                         TitanVertex reqVertex = (TitanVertex) edge.inVertex();
3806                         String reqId = (String) titanGenericDao.getProperty(reqVertex, UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Requirement));
3807                         if (reqId.equals(relationPair.getRequirementUid())) {
3808                                 String ownerIdOnEdge = (String) edge.value(GraphEdgePropertiesDictionary.OWNER_ID.getProperty());
3809                                 if (ownerIdOnEdge.equals(relationPair.getRequirementOwnerId())) {
3810                                         String leftOccurrences = (String) edge.value(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty());
3811                                         if (leftOccurrences != null && !leftOccurrences.equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
3812                                                 Integer leftIntValue = Integer.parseInt(leftOccurrences);
3813                                                 if (leftIntValue > 0) {
3814                                                         exist = true;
3815                                                 }
3816                                         } else {
3817                                                 exist = true;
3818                                         }
3819                                         break;
3820                                 }
3821                         }
3822                 }
3823                 return Either.left(exist);
3824         }
3825
3826         public Either<Boolean, StorageOperationStatus> isAvailableCapabilty(ComponentInstance toResInstance, RequirementAndRelationshipPair relationPair) {
3827                 Either<TitanVertex, TitanOperationStatus> fromRi = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), toResInstance.getUniqueId());
3828                 if (fromRi.isRight()) {
3829                         log.debug("Failed to fetch component instance {} error {}", toResInstance.getUniqueId(), fromRi.right().value());
3830                         return Either.right(StorageOperationStatus.NOT_FOUND);
3831                 }
3832                 Iterator<Edge> edgeIter = fromRi.left().value().edges(Direction.OUT, GraphEdgeLabels.CALCULATED_CAPABILITY.name());
3833                 if (edgeIter == null || !edgeIter.hasNext()) {
3834                         log.debug("No available CALCULATED_CAPABILITY edges. All full filled for RI {}", toResInstance.getUniqueId());
3835                         return Either.right(StorageOperationStatus.NOT_FOUND);
3836                 }
3837                 boolean exist = false;
3838                 while (edgeIter.hasNext()) {
3839                         Edge edge = edgeIter.next();
3840                         TitanVertex reqVertex = (TitanVertex) edge.inVertex();
3841                         String capId = (String) titanGenericDao.getProperty(reqVertex, UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Capability));
3842                         if (capId.equals(relationPair.getCapabilityUid())) {
3843                                 String ownerIdOnEdge = (String) edge.value(GraphEdgePropertiesDictionary.OWNER_ID.getProperty());
3844                                 if (ownerIdOnEdge.equals(relationPair.getCapabilityOwnerId())) {
3845                                         String leftOccurrences = (String) edge.value(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty());
3846                                         if (leftOccurrences != null && !leftOccurrences.equals(CapabilityDataDefinition.MAX_OCCURRENCES)) {
3847                                                 Integer leftIntValue = Integer.parseInt(leftOccurrences);
3848                                                 if (leftIntValue > 0) {
3849                                                         exist = true;
3850                                                 }
3851                                         } else {
3852                                                 exist = true;
3853                                         }
3854                                         break;
3855                                 }
3856                         }
3857                 }
3858                 return Either.left(exist);
3859         }
3860
3861         interface DataNodeCollector<Data> {
3862                 Either<List<ImmutablePair<Data, GraphEdge>>, TitanOperationStatus> getDataNodes();
3863         }
3864
3865         public <Data> Either<List<ImmutablePair<Data, GraphEdge>>, TitanOperationStatus> getDataFromGraph(DataNodeCollector<Data> dataCollector) {
3866                 Either<List<ImmutablePair<Data, GraphEdge>>, TitanOperationStatus> eitherRet;
3867
3868                 Either<List<ImmutablePair<Data, GraphEdge>>, TitanOperationStatus> childrenNodes = dataCollector.getDataNodes();
3869
3870                 if (childrenNodes.isLeft()) {
3871                         List<ImmutablePair<Data, GraphEdge>> collectedData = childrenNodes.left().value().stream().map(element -> new ImmutablePair<Data, GraphEdge>(element.getLeft(), element.getRight())).collect(Collectors.toList());
3872                         eitherRet = Either.left(collectedData);
3873                 } else {
3874                         eitherRet = Either.right(childrenNodes.right().value());
3875                 }
3876                 return eitherRet;
3877         }
3878
3879         public ComponentOperation getComponentOperation(NodeTypeEnum componentType) {
3880                 if (NodeTypeEnum.Service == componentType) {
3881                         return serviceOperation;
3882                 } else if (NodeTypeEnum.Resource == componentType) {
3883                         return resourceOperation;
3884                 }
3885                 return null;
3886         }
3887
3888         private boolean isAtomicResource(Component component) {
3889                 // true if component is of type VL/CP/VFC
3890                 boolean isFromAtomicResource = (component.getComponentType() == ComponentTypeEnum.RESOURCE && ((Resource) component).getResourceType() != ResourceTypeEnum.VF);
3891                 return isFromAtomicResource;
3892         }
3893
3894         private StorageOperationStatus cloneResourceInstanceAttributeValues(ComponentInstance createdInstance, ComponentInstance resourceInstance) {
3895                 Wrapper<StorageOperationStatus> storageStatusWrapper = new Wrapper<>();
3896                 Wrapper<List<ComponentInstanceAttribute>> compInstanceAttList = new Wrapper<>();
3897
3898                 findAllAttributesOfResourceInstance(resourceInstance, compInstanceAttList, storageStatusWrapper);
3899
3900                 if (storageStatusWrapper.isEmpty()) {
3901                         validateListNotEmpty(storageStatusWrapper, compInstanceAttList.getInnerElement());
3902                 }
3903
3904                 if (storageStatusWrapper.isEmpty()) {
3905                         List<ComponentInstanceAttribute> attributesOnInstance = compInstanceAttList.getInnerElement();
3906                         for (int i = 0; i < attributesOnInstance.size() && storageStatusWrapper.isEmpty(); i++) {
3907                                 cloneSingleAttributeOnResourceInstance(createdInstance, attributesOnInstance.get(i), storageStatusWrapper);
3908                         }
3909                 }
3910
3911                 StorageOperationStatus result = storageStatusWrapper.isEmpty() ? StorageOperationStatus.OK : storageStatusWrapper.getInnerElement();
3912                 return result;
3913
3914         }
3915
3916         private StorageOperationStatus cloneResourceInstanceAttributeValues(TitanVertex createdInstanceVertex, ComponentInstance resourceInstance, String instanceId) {
3917                 Wrapper<StorageOperationStatus> storageStatusWrapper = new Wrapper<>();
3918                 Wrapper<List<ComponentInstanceAttribute>> compInstanceAttList = new Wrapper<>();
3919
3920                 findAllAttributesOfResourceInstance(resourceInstance, compInstanceAttList, storageStatusWrapper);
3921
3922                 if (storageStatusWrapper.isEmpty()) {
3923                         validateListNotEmpty(storageStatusWrapper, compInstanceAttList.getInnerElement());
3924                 }
3925
3926                 if (storageStatusWrapper.isEmpty()) {
3927                         List<ComponentInstanceAttribute> attributesOnInstance = compInstanceAttList.getInnerElement();
3928                         for (int i = 0; i < attributesOnInstance.size() && storageStatusWrapper.isEmpty(); i++) {
3929                                 StorageOperationStatus result = cloneSingleAttributeOnResourceInstance(createdInstanceVertex, attributesOnInstance.get(i), instanceId);
3930                                 if (result != StorageOperationStatus.OK) {
3931                                         log.trace("Failed to clone attribute for instance {} error {}", instanceId, result);
3932                                         return result;
3933                                 }
3934                         }
3935                 }
3936
3937                 StorageOperationStatus result = storageStatusWrapper.isEmpty() ? StorageOperationStatus.OK : storageStatusWrapper.getInnerElement();
3938                 return result;
3939
3940         }
3941
3942         private <T> void validateListNotEmpty(Wrapper<StorageOperationStatus> storageStatusWrapper, List<T> attributesOnInstance) {
3943                 if (attributesOnInstance == null || attributesOnInstance.isEmpty() == true) {
3944                         storageStatusWrapper.setInnerElement(StorageOperationStatus.OK);
3945                 }
3946         }
3947
3948         private void findAllAttributesOfResourceInstance(ComponentInstance resourceInstance, Wrapper<List<ComponentInstanceAttribute>> compInstanceAttList, Wrapper<StorageOperationStatus> storageStatusWrapper) {
3949
3950                 Either<List<ComponentInstanceAttribute>, TitanOperationStatus> allAttributes = attributeOperation.getAllAttributesOfResourceInstance(resourceInstance);
3951                 if (allAttributes.isRight()) {
3952                         TitanOperationStatus status = allAttributes.right().value();
3953                         if (status == TitanOperationStatus.NOT_FOUND) {
3954                                 status = TitanOperationStatus.OK;
3955                         }
3956                         StorageOperationStatus storageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
3957                         storageStatusWrapper.setInnerElement(storageStatus);
3958                 } else {
3959                         compInstanceAttList.setInnerElement(allAttributes.left().value());
3960                 }
3961         }
3962
3963         private void cloneSingleAttributeOnResourceInstance(ComponentInstance createdInstance, ComponentInstanceAttribute attribute, Wrapper<StorageOperationStatus> storageStatusWrapper) {
3964                 // Only if valueUniqueId is not empty, then its belongs to the
3965                 // instance
3966                 if (attribute.getValueUniqueUid() != null) {
3967                         attribute.setValueUniqueUid(null);
3968                         Either<Integer, StorageOperationStatus> counterRes = increaseAndGetResourceInstanceSpecificCounter(createdInstance.getUniqueId(), GraphPropertiesDictionary.ATTRIBUTE_COUNTER, true);
3969                         if (counterRes.isRight()) {
3970                                 storageStatusWrapper.setInnerElement(counterRes.right().value());
3971                         } else {
3972                                 Either<AttributeValueData, TitanOperationStatus> addAttributeToResourceInstance = addAttributeToResourceInstance(attribute, createdInstance.getUniqueId(), counterRes.left().value());
3973
3974                                 if (addAttributeToResourceInstance.isRight()) {
3975                                         TitanOperationStatus status = addAttributeToResourceInstance.right().value();
3976                                         StorageOperationStatus storageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
3977                                         storageStatusWrapper.setInnerElement(storageStatus);
3978                                 }
3979                         }
3980                 }
3981
3982         }
3983
3984         private StorageOperationStatus cloneSingleAttributeOnResourceInstance(TitanVertex createdInstanceVertex, ComponentInstanceAttribute attribute, String instanceId) {
3985                 // Only if valueUniqueId is not empty, then its belongs to the
3986                 // instance
3987                 if (attribute.getValueUniqueUid() != null) {
3988                         attribute.setValueUniqueUid(null);
3989                         Either<Integer, StorageOperationStatus> counterRes = increaseAndGetResourceInstanceSpecificCounter(createdInstanceVertex, GraphPropertiesDictionary.ATTRIBUTE_COUNTER);
3990                         if (counterRes.isRight()) {
3991                                 return counterRes.right().value();
3992                         } else {
3993                                 Either<AttributeValueData, TitanOperationStatus> addAttributeToResourceInstance = addAttributeToResourceInstance(attribute, instanceId, counterRes.left().value());
3994
3995                                 if (addAttributeToResourceInstance.isRight()) {
3996                                         TitanOperationStatus status = addAttributeToResourceInstance.right().value();
3997                                         StorageOperationStatus storageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
3998                                         return storageStatus;
3999                                 }
4000                         }
4001                 }
4002                 return StorageOperationStatus.OK;
4003
4004         }
4005
4006         private void connectAttValueDataToComponentInstanceData(Wrapper<TitanOperationStatus> errorWrapper, ComponentInstanceData compIns, AttributeValueData attValueData) {
4007
4008                 Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(compIns, attValueData, GraphEdgeLabels.ATTRIBUTE_VALUE, null);
4009
4010                 if (createRelResult.isRight()) {
4011                         TitanOperationStatus operationStatus = createRelResult.right().value();
4012                         errorWrapper.setInnerElement(operationStatus);
4013                         BeEcompErrorManager.getInstance().logInternalFlowError("connectAttValueDataToComponentInstanceData",
4014                                         "Failed to associate resource instance " + compIns.getUniqueId() + " attribute value " + attValueData.getUniqueId() + " in graph. status is " + operationStatus, ErrorSeverity.ERROR);
4015                 }
4016         }
4017
4018         private void connectInputValueDataToComponentInstanceData(Wrapper<TitanOperationStatus> errorWrapper, ComponentInstanceData compIns, InputValueData attValueData) {
4019
4020                 Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(compIns, attValueData, GraphEdgeLabels.INPUT_VALUE, null);
4021
4022                 if (createRelResult.isRight()) {
4023                         TitanOperationStatus operationStatus = createRelResult.right().value();
4024                         errorWrapper.setInnerElement(operationStatus);
4025                         BeEcompErrorManager.getInstance().logInternalFlowError("connectInputValueDataToComponentInstanceData",
4026                                         "Failed to associate resource instance " + compIns.getUniqueId() + " input value " + attValueData.getUniqueId() + " in graph. status is " + operationStatus, ErrorSeverity.ERROR);
4027                 }
4028         }
4029
4030         private void connectAttValueDataToAttData(Wrapper<TitanOperationStatus> errorWrapper, AttributeData attData, AttributeValueData attValueData) {
4031
4032                 Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(attValueData, attData, GraphEdgeLabels.ATTRIBUTE_IMPL, null);
4033
4034                 if (createRelResult.isRight()) {
4035                         TitanOperationStatus operationStatus = createRelResult.right().value();
4036                         BeEcompErrorManager.getInstance().logInternalFlowError("connectAttValueDataToAttData",
4037                                         "Failed to associate attribute value " + attValueData.getUniqueId() + " to attribute " + attData.getUniqueId() + " in graph. status is " + operationStatus, ErrorSeverity.ERROR);
4038
4039                         errorWrapper.setInnerElement(operationStatus);
4040                 }
4041         }
4042
4043         private void connectInputValueDataToInputData(Wrapper<TitanOperationStatus> errorWrapper, InputsData attData, InputValueData attValueData) {
4044
4045                 Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(attValueData, attData, GraphEdgeLabels.INPUT_IMPL, null);
4046
4047                 if (createRelResult.isRight()) {
4048                         TitanOperationStatus operationStatus = createRelResult.right().value();
4049                         BeEcompErrorManager.getInstance().logInternalFlowError("connectInputValueDataToInputData", "Failed to associate input value " + attValueData.getUniqueId() + " to input " + attData.getUniqueId() + " in graph. status is " + operationStatus,
4050                                         ErrorSeverity.ERROR);
4051
4052                         errorWrapper.setInnerElement(operationStatus);
4053                 }
4054         }
4055
4056         private void createAttributeValueDataNode(ComponentInstanceAttribute attributeInstanceProperty, Integer index, Wrapper<TitanOperationStatus> errorWrapper, ComponentInstanceData resourceInstanceData,
4057                         Wrapper<AttributeValueData> attValueDataWrapper) {
4058                 String valueUniqueUid = attributeInstanceProperty.getValueUniqueUid();
4059                 if (valueUniqueUid == null) {
4060
4061                         String attValueDatauniqueId = UniqueIdBuilder.buildResourceInstanceAttributeValueUid(resourceInstanceData.getUniqueId(), index);
4062                         AttributeValueData attributeValueData = buildAttributeValueDataFromComponentInstanceAttribute(attributeInstanceProperty, attValueDatauniqueId);
4063
4064                         log.debug("Before adding attribute value to graph {}", attributeValueData);
4065                         Either<AttributeValueData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(attributeValueData, AttributeValueData.class);
4066                         log.debug("After adding attribute value to graph {}", attributeValueData);
4067
4068                         if (createNodeResult.isRight()) {
4069                                 TitanOperationStatus operationStatus = createNodeResult.right().value();
4070                                 errorWrapper.setInnerElement(operationStatus);
4071                         } else {
4072                                 attValueDataWrapper.setInnerElement(createNodeResult.left().value());
4073                         }
4074
4075                 } else {
4076                         BeEcompErrorManager.getInstance().logInternalFlowError("CreateAttributeValueDataNode", "attribute value already exists.", ErrorSeverity.ERROR);
4077                         errorWrapper.setInnerElement(TitanOperationStatus.ALREADY_EXIST);
4078                 }
4079         }
4080
4081         /*
4082          * private void createInputValueDataNode(ComponentInstanceInput inputInstanceProperty, Integer index, Wrapper<TitanOperationStatus> errorWrapper, ComponentInstanceData resourceInstanceData, Wrapper<AttributeValueData> attValueDataWrapper) {
4083          * String valueUniqueUid = inputInstanceProperty.getValueUniqueUid(); if (valueUniqueUid == null) {
4084          * 
4085          * String attValueDatauniqueId = UniqueIdBuilder.buildResourceInstanceInputValueUid(resourceInstanceData. getUniqueId(), index); AttributeValueData attributeValueData = buildAttributeValueDataFromComponentInstanceAttribute( inputInstanceProperty,
4086          * attValueDatauniqueId);
4087          * 
4088          * log.debug("Before adding attribute value to graph {}", attributeValueData); Either<AttributeValueData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(attributeValueData, AttributeValueData.class);
4089          * log.debug("After adding attribute value to graph {}", attributeValueData);
4090          * 
4091          * if (createNodeResult.isRight()) { TitanOperationStatus operationStatus = createNodeResult.right().value(); errorWrapper.setInnerElement(operationStatus); } else { attValueDataWrapper.setInnerElement(createNodeResult.left().value()); }
4092          * 
4093          * } else { BeEcompErrorManager.getInstance().logInternalFlowError( "CreateAttributeValueDataNode", "attribute value already exists.", ErrorSeverity.ERROR); errorWrapper.setInnerElement(TitanOperationStatus.ALREADY_EXIST); } }
4094          */
4095
4096         private AttributeValueData buildAttributeValueDataFromComponentInstanceAttribute(ComponentInstanceAttribute resourceInstanceAttribute, String uniqueId) {
4097                 AttributeValueData attributeValueData = new AttributeValueData();
4098                 attributeValueData.setUniqueId(uniqueId);
4099                 attributeValueData.setHidden(resourceInstanceAttribute.isHidden());
4100                 attributeValueData.setValue(resourceInstanceAttribute.getValue());
4101                 attributeValueData.setType(resourceInstanceAttribute.getType());
4102                 long currentTimeMillis = System.currentTimeMillis();
4103                 attributeValueData.setCreationTime(currentTimeMillis);
4104                 attributeValueData.setModificationTime(currentTimeMillis);
4105                 return attributeValueData;
4106         }
4107
4108         private InputValueData buildAttributeValueDataFromComponentInstanceAttribute(ComponentInstanceInput resourceInstanceInput, String uniqueId) {
4109                 InputValueData inputValueData = new InputValueData();
4110                 inputValueData.setUniqueId(uniqueId);
4111                 inputValueData.setHidden(resourceInstanceInput.isHidden());
4112                 inputValueData.setValue(resourceInstanceInput.getValue());
4113                 inputValueData.setType(resourceInstanceInput.getType());
4114                 long currentTimeMillis = System.currentTimeMillis();
4115                 inputValueData.setCreationTime(currentTimeMillis);
4116                 inputValueData.setModificationTime(currentTimeMillis);
4117                 return inputValueData;
4118         }
4119
4120         private StorageOperationStatus cloneResourceInstancePropertyValues(ComponentInstance toResourceInstance, ComponentInstance fromResourceInstance) {
4121
4122                 Either<List<ComponentInstanceProperty>, TitanOperationStatus> allProperties = propertyOperation.getAllPropertiesOfResourceInstanceOnlyPropertyDefId(fromResourceInstance.getUniqueId());
4123                 if (allProperties.isRight()) {
4124                         TitanOperationStatus status = allProperties.right().value();
4125                         if (status == TitanOperationStatus.NOT_FOUND) {
4126                                 status = TitanOperationStatus.OK;
4127                         }
4128                         StorageOperationStatus storageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
4129                         return storageStatus;
4130                 }
4131
4132                 List<ComponentInstanceProperty> propertiesOnInstance = allProperties.left().value();
4133                 if (propertiesOnInstance == null || propertiesOnInstance.isEmpty() == true) {
4134                         return StorageOperationStatus.OK;
4135                 }
4136
4137                 for (ComponentInstanceProperty property : propertiesOnInstance) {
4138
4139                         // Only if valueUniqueId is not empty, then its belongs to the
4140                         // instance
4141                         if (property.getValueUniqueUid() != null) {
4142                                 property.setValueUniqueUid(null);
4143                                 List<PropertyRule> rules = property.getRules();
4144                                 if (rules != null) {
4145                                         for (PropertyRule propertyRule : rules) {
4146                                                 propertyRule.replaceFirstToken(toResourceInstance.getUniqueId());
4147                                         }
4148                                 }
4149
4150                         } else {
4151                                 continue;
4152                         }
4153
4154                         String resourceInstanceId = toResourceInstance.getUniqueId();
4155
4156                         Either<Integer, StorageOperationStatus> counterRes = this.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, GraphPropertiesDictionary.PROPERTY_COUNTER, true);
4157
4158                         if (counterRes.isRight()) {
4159                                 log.debug("increaseAndGetResourcePropertyCounter failed resource instance {} property {}", resourceInstanceId, property);
4160                                 StorageOperationStatus status = counterRes.right().value();
4161                                 return status;
4162                         }
4163                         Integer index = counterRes.left().value();
4164
4165                         Either<PropertyValueData, TitanOperationStatus> addPropertyToResourceInstance = this.addPropertyToResourceInstance(property, toResourceInstance.getUniqueId(), false, index);
4166
4167                         if (addPropertyToResourceInstance.isRight()) {
4168                                 TitanOperationStatus status = addPropertyToResourceInstance.right().value();
4169                                 StorageOperationStatus storageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
4170                                 return storageStatus;
4171                         }
4172                 }
4173
4174                 return StorageOperationStatus.OK;
4175         }
4176
4177         private StorageOperationStatus cloneResourceInstancePropertyValues(TitanVertex toResourceInstance, ComponentInstance fromResourceInstance, Map<String, List<ComponentInstanceProperty>> inputsPropMap, Resource newResource) {
4178
4179                 String riId = (String) titanGenericDao.getProperty(toResourceInstance, GraphPropertiesDictionary.UNIQUE_ID.getProperty());
4180                 Either<List<ComponentInstanceProperty>, TitanOperationStatus> allProperties = propertyOperation.getAllPropertiesOfResourceInstanceOnlyPropertyDefId(fromResourceInstance.getUniqueId());
4181                 List<InputDefinition> newInputs = newResource.getInputs();
4182                 //
4183                 if (allProperties.isRight()) {
4184                         TitanOperationStatus status = allProperties.right().value();
4185                         if (status == TitanOperationStatus.NOT_FOUND) {
4186                                 status = TitanOperationStatus.OK;
4187                         }
4188                         StorageOperationStatus storageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
4189                         return storageStatus;
4190                 }
4191
4192                 List<ComponentInstanceProperty> propertiesOnInstance = allProperties.left().value();
4193                 if (propertiesOnInstance == null || propertiesOnInstance.isEmpty() == true) {
4194                         return StorageOperationStatus.OK;
4195                 }
4196
4197                 for (ComponentInstanceProperty property : propertiesOnInstance) {
4198
4199                         // Only if valueUniqueId is not empty, then its belongs to the
4200                         // instance
4201                         if (property.getValueUniqueUid() != null) {
4202                                 property.setValueUniqueUid(null);
4203                                 List<PropertyRule> rules = property.getRules();
4204                                 if (rules != null) {
4205                                         for (PropertyRule propertyRule : rules) {
4206                                                 propertyRule.replaceFirstToken(riId);
4207                                         }
4208                                 }
4209
4210                         } else {
4211                                 continue;
4212                         }
4213
4214                         String resourceInstanceId = riId;
4215
4216                         Either<Integer, StorageOperationStatus> counterRes = this.increaseAndGetResourceInstanceSpecificCounter(toResourceInstance, GraphPropertiesDictionary.PROPERTY_COUNTER);
4217
4218                         if (counterRes.isRight()) {
4219                                 log.debug("increaseAndGetResourcePropertyCounter failed resource instance {} property {}", resourceInstanceId, property);
4220                                 StorageOperationStatus status = counterRes.right().value();
4221                                 return status;
4222                         }
4223                         Integer index = counterRes.left().value();
4224
4225                         Either<ComponentInstanceProperty, TitanOperationStatus> addPropertyToResourceInstance = this.addPropertyToResourceInstance(property, toResourceInstance, false, index, resourceInstanceId);
4226
4227                         if (addPropertyToResourceInstance.isRight() && addPropertyToResourceInstance.right().value() != TitanOperationStatus.OK) {
4228                                 StorageOperationStatus storageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(addPropertyToResourceInstance.right().value());
4229                                 return storageStatus;
4230                         }
4231                         if (addPropertyToResourceInstance.isLeft()) {
4232                                 ComponentInstanceProperty newProp = addPropertyToResourceInstance.left().value();
4233                                 Set<String> inputsKey = inputsPropMap.keySet();
4234                                 String inputToAssName = null;
4235                                 GetInputValueDataDefinition getInputInfo = null;
4236                                 for (String inputName : inputsKey) {
4237                                         List<ComponentInstanceProperty> propsList = inputsPropMap.get(inputName);
4238                                         Optional<ComponentInstanceProperty> op = propsList.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
4239                                         if (op.isPresent()) {
4240                                                 ComponentInstanceProperty inpProp = op.get();
4241                                                 getInputInfo = new GetInputValueDataDefinition();
4242                                                 getInputInfo.setPropName(inpProp.getName());
4243                                                 getInputInfo.setInputName(inputName);
4244                                                 inputToAssName = inputName;
4245                                                 break;
4246                                         }
4247
4248                                 }
4249                                 if (inputToAssName != null) {
4250                                         for (InputDefinition input1 : newInputs) {
4251                                                 if (input1.getName().equals(inputToAssName)) {
4252                                                         this.inputOperation.associatePropertyToInput(riId, input1.getUniqueId(), newProp, getInputInfo);
4253                                                         break;
4254                                                 }
4255                                         }
4256                                 }
4257
4258                         }
4259                 }
4260
4261                 return StorageOperationStatus.OK;
4262         }
4263
4264         private StorageOperationStatus cloneResourceInstanceInputsValues(ComponentInstance toResourceInstance, ComponentInstance fromResourceInstance, Component comonentTo, Map<String, List<ComponentInstanceInput>> inputsValuesMap) {
4265
4266                 Either<List<ComponentInstanceInput>, TitanOperationStatus> allProperties = inputOperation.getAllInputsOfResourceInstanceOnlyInputDefId(fromResourceInstance.getUniqueId());
4267                 if (allProperties.isRight()) {
4268                         TitanOperationStatus status = allProperties.right().value();
4269                         if (status == TitanOperationStatus.NOT_FOUND) {
4270                                 status = TitanOperationStatus.OK;
4271                         }
4272                         StorageOperationStatus storageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
4273                         return storageStatus;
4274                 }
4275
4276                 List<ComponentInstanceInput> propertiesOnInstance = allProperties.left().value();
4277                 if (propertiesOnInstance == null || propertiesOnInstance.isEmpty() == true) {
4278                         return StorageOperationStatus.OK;
4279                 }
4280                 List<InputDefinition> newInputs = comonentTo.getInputs();
4281
4282                 for (ComponentInstanceInput property : propertiesOnInstance) {
4283
4284                         List<InputDefinition> inputToAss = new ArrayList<InputDefinition>();
4285                         if (newInputs != null && !inputsValuesMap.isEmpty()) {
4286
4287                                 Set<String> inputsName = inputsValuesMap.keySet();
4288                                 for (String name : inputsName) {
4289                                         List<ComponentInstanceInput> inputsValue = inputsValuesMap.get(name);
4290                                         if (inputsValue != null) {
4291                                                 Optional<ComponentInstanceInput> op = inputsValue.stream().filter(p -> p.getValueUniqueUid().equals(property.getValueUniqueUid())).findAny();
4292                                                 if (op.isPresent()) {
4293                                                         Optional<InputDefinition> optional = newInputs.stream().filter(e -> e.getName().equals(name)).findAny();
4294                                                         if (optional.isPresent()) {
4295                                                                 inputToAss.add(optional.get());
4296                                                         }
4297                                                 }
4298                                         }
4299                                 }
4300                         }
4301
4302                         // Only if valueUniqueId is not empty, then its belongs to the
4303                         // instance
4304                         if (property.getValueUniqueUid() != null) {
4305                                 property.setValueUniqueUid(null);
4306                                 List<PropertyRule> rules = property.getRules();
4307                                 if (rules != null) {
4308                                         for (PropertyRule propertyRule : rules) {
4309                                                 propertyRule.replaceFirstToken(toResourceInstance.getUniqueId());
4310                                         }
4311                                 }
4312
4313                         } else {
4314                                 continue;
4315                         }
4316
4317                         String resourceInstanceId = toResourceInstance.getUniqueId();
4318
4319                         Either<Integer, StorageOperationStatus> counterRes = this.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, GraphPropertiesDictionary.INPUT_COUNTER, true);
4320
4321                         if (counterRes.isRight()) {
4322                                 log.debug("increaseAndGetResourcePropertyCounter failed resource instance {} property {}", resourceInstanceId, property);
4323                                 StorageOperationStatus status = counterRes.right().value();
4324                                 return status;
4325                         }
4326                         Integer index = counterRes.left().value();
4327
4328                         Either<InputValueData, TitanOperationStatus> addPropertyToResourceInstance = this.addInputToResourceInstance(property, toResourceInstance.getUniqueId(), index);
4329
4330                         if (addPropertyToResourceInstance.isRight()) {
4331                                 TitanOperationStatus status = addPropertyToResourceInstance.right().value();
4332                                 StorageOperationStatus storageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
4333                                 return storageStatus;
4334                         }
4335
4336                         for (InputDefinition input : inputToAss) {
4337                                 Map<String, Object> props = new HashMap<String, Object>();
4338                                 props.put(GraphEdgePropertiesDictionary.NAME.getProperty(), input.getName());
4339                                 props.put(GraphEdgePropertiesDictionary.OWNER_ID.getProperty(), toResourceInstance.getUniqueId());
4340
4341                                 GraphNode inputData = new UniqueIdData(NodeTypeEnum.Input, input.getUniqueId());
4342                                 GraphNode propertyData = new UniqueIdData(NodeTypeEnum.InputValue, addPropertyToResourceInstance.left().value().getUniqueId());
4343
4344                                 Either<GraphRelation, TitanOperationStatus> addPropRefResult = titanGenericDao.createRelation(inputData, propertyData, GraphEdgeLabels.GET_INPUT, props);
4345
4346                                 if (addPropRefResult.isRight()) {
4347                                         TitanOperationStatus status = addPropRefResult.right().value();
4348                                         log.debug("Failed to associate input {}  to input value {} in graph. Status is {}", input.getUniqueId(), propertyData.getUniqueId(), status);
4349
4350                                         return DaoStatusConverter.convertTitanStatusToStorageStatus(status);
4351                                 }
4352                         }
4353                 }
4354
4355                 return StorageOperationStatus.OK;
4356         }
4357
4358         private StorageOperationStatus cloneResourceInstanceInputsValues(TitanVertex toResourceInstanceVertex, ComponentInstance fromResourceInstance, String instanceId, Resource newResource, Map<String, List<ComponentInstanceInput>> inputsValuesMap) {
4359
4360                 Either<List<ComponentInstanceInput>, TitanOperationStatus> allProperties = inputOperation.getAllInputsOfResourceInstanceOnlyInputDefId(fromResourceInstance.getUniqueId());
4361                 if (allProperties.isRight()) {
4362                         TitanOperationStatus status = allProperties.right().value();
4363                         if (status == TitanOperationStatus.NOT_FOUND) {
4364                                 status = TitanOperationStatus.OK;
4365                         }
4366                         StorageOperationStatus storageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
4367                         return storageStatus;
4368                 }
4369
4370                 List<ComponentInstanceInput> propertiesOnInstance = allProperties.left().value();
4371                 if (propertiesOnInstance == null || propertiesOnInstance.isEmpty() == true) {
4372                         return StorageOperationStatus.OK;
4373                 }
4374
4375                 for (ComponentInstanceInput property : propertiesOnInstance) {
4376
4377                         // Only if valueUniqueId is not empty, then its belongs to the
4378                         // instance
4379                         if (property.getValueUniqueUid() != null) {
4380                                 property.setValueUniqueUid(null);
4381                                 List<PropertyRule> rules = property.getRules();
4382                                 if (rules != null) {
4383                                         for (PropertyRule propertyRule : rules) {
4384                                                 propertyRule.replaceFirstToken(instanceId);
4385                                         }
4386                                 }
4387
4388                         } else {
4389                                 continue;
4390                         }
4391
4392                         String resourceInstanceId = instanceId;
4393
4394                         Either<Integer, StorageOperationStatus> counterRes = this.increaseAndGetResourceInstanceSpecificCounter(toResourceInstanceVertex, GraphPropertiesDictionary.INPUT_COUNTER);
4395
4396                         if (counterRes.isRight()) {
4397                                 log.debug("increaseAndGetResourcePropertyCounter failed resource instance {} property {}", resourceInstanceId, property);
4398                                 StorageOperationStatus status = counterRes.right().value();
4399                                 return status;
4400                         }
4401                         Integer index = counterRes.left().value();
4402
4403                         Either<InputValueData, TitanOperationStatus> addPropertyToResourceInstance = this.addInputToResourceInstance(property, resourceInstanceId, index);
4404
4405                         if (addPropertyToResourceInstance.isRight()) {
4406                                 TitanOperationStatus status = addPropertyToResourceInstance.right().value();
4407                                 StorageOperationStatus storageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
4408                                 return storageStatus;
4409                         }
4410                 }
4411
4412                 return StorageOperationStatus.OK;
4413         }
4414
4415         public Either<ComponentInstanceProperty, StorageOperationStatus> updatePropertyValueInResourceInstance(ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId, boolean inTransaction) {
4416
4417                 Either<ComponentInstanceProperty, StorageOperationStatus> result = null;
4418
4419                 try {
4420                         // TODO: verify validUniqueId exists
4421                         Either<PropertyValueData, TitanOperationStatus> eitherStatus = this.updatePropertyOfResourceInstance(resourceInstanceProperty, resourceInstanceId, true);
4422
4423                         if (eitherStatus.isRight()) {
4424                                 log.error("Failed to add property value {} to resource instance {} in Graph. status is {}", resourceInstanceProperty, resourceInstanceId, eitherStatus.right().value().name());
4425                                 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(eitherStatus.right().value()));
4426                                 return result;
4427                         } else {
4428                                 PropertyValueData propertyValueData = eitherStatus.left().value();
4429
4430                                 ComponentInstanceProperty propertyValueResult = propertyOperation.buildResourceInstanceProperty(propertyValueData, resourceInstanceProperty);
4431
4432                                 log.debug("The returned ResourceInstanceProperty is {}", propertyValueResult);
4433
4434                                 Either<String, TitanOperationStatus> findDefaultValue = propertyOperation.findDefaultValueFromSecondPosition(resourceInstanceProperty.getPath(), propertyValueData.getUniqueId(), resourceInstanceProperty.getDefaultValue());
4435                                 if (findDefaultValue.isRight()) {
4436                                         result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(findDefaultValue.right().value()));
4437                                         return result;
4438                                 }
4439                                 String defaultValue = findDefaultValue.left().value();
4440                                 propertyValueResult.setDefaultValue(defaultValue);
4441                                 log.debug("The returned default value in ResourceInstanceProperty is {}", defaultValue);
4442
4443                                 result = Either.left(propertyValueResult);
4444                                 return result;
4445                         }
4446                 }
4447
4448                 finally {
4449                         if (false == inTransaction) {
4450                                 if (result == null || result.isRight()) {
4451                                         log.error("Going to execute rollback on graph.");
4452                                         titanGenericDao.rollback();
4453                                 } else {
4454                                         log.debug("Going to execute commit on graph.");
4455                                         titanGenericDao.commit();
4456                                 }
4457                         }
4458                 }
4459
4460         }
4461
4462         private static final class UpdateDataContainer<SomeData, SomeValueData> {
4463                 final Wrapper<SomeValueData> valueDataWrapper;
4464                 final Wrapper<SomeData> dataWrapper;
4465                 final GraphEdgeLabels graphEdge;
4466                 final Supplier<Class<SomeData>> someDataClassGen;
4467                 final Supplier<Class<SomeValueData>> someValueDataClassGen;
4468                 final NodeTypeEnum nodeType;
4469                 final NodeTypeEnum nodeTypeValue;
4470
4471                 private UpdateDataContainer(GraphEdgeLabels graphEdge, Supplier<Class<SomeData>> someDataClassGen, Supplier<Class<SomeValueData>> someValueDataClassGen, NodeTypeEnum nodeType, NodeTypeEnum nodeTypeValue) {
4472                         super();
4473                         this.valueDataWrapper = new Wrapper<>();
4474                         this.dataWrapper = new Wrapper<>();
4475                         this.graphEdge = graphEdge;
4476                         this.someDataClassGen = someDataClassGen;
4477                         this.someValueDataClassGen = someValueDataClassGen;
4478                         this.nodeType = nodeType;
4479                         this.nodeTypeValue = nodeTypeValue;
4480                 }
4481
4482                 public Wrapper<SomeValueData> getValueDataWrapper() {
4483                         return valueDataWrapper;
4484                 }
4485
4486                 public Wrapper<SomeData> getDataWrapper() {
4487                         return dataWrapper;
4488                 }
4489
4490                 public GraphEdgeLabels getGraphEdge() {
4491                         return graphEdge;
4492                 }
4493
4494                 public Supplier<Class<SomeData>> getSomeDataClassGen() {
4495                         return someDataClassGen;
4496                 }
4497
4498                 public Supplier<Class<SomeValueData>> getSomeValueDataClassGen() {
4499                         return someValueDataClassGen;
4500                 }
4501
4502                 public NodeTypeEnum getNodeType() {
4503                         return nodeType;
4504                 }
4505
4506                 public NodeTypeEnum getNodeTypeValue() {
4507                         return nodeTypeValue;
4508                 }
4509         }
4510
4511         @Override
4512         public Either<AttributeValueData, TitanOperationStatus> createOrUpdateAttributeOfResourceInstance(ComponentInstanceAttribute attributeInstanceProperty, String resourceInstanceId) {
4513                 Either<AttributeValueData, TitanOperationStatus> result;
4514                 // Create
4515                 if (attributeInstanceProperty.getValueUniqueUid() == null) {
4516                         Either<Integer, StorageOperationStatus> counterRes = increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, GraphPropertiesDictionary.ATTRIBUTE_COUNTER, true);
4517                         if (counterRes.isRight()) {
4518                                 BeEcompErrorManager.getInstance().logInternalFlowError("createOrUpdateAttributeOfResourceInstance", "Failed to get AttributeValueData Counter", ErrorSeverity.ERROR);
4519                                 result = Either.right(TitanOperationStatus.GENERAL_ERROR);
4520
4521                         } else {
4522                                 result = addAttributeToResourceInstance(attributeInstanceProperty, resourceInstanceId, counterRes.left().value());
4523                         }
4524                 }
4525                 // Update
4526                 else {
4527                         result = updateAttributeOfResourceInstance(attributeInstanceProperty, resourceInstanceId);
4528                 }
4529                 return result;
4530         }
4531
4532         /**
4533          * update value of attribute on resource instance
4534          * 
4535          * @param resourceInstanceAttribute
4536          * @param resourceInstanceId
4537          * @return
4538          */
4539         private Either<AttributeValueData, TitanOperationStatus> updateAttributeOfResourceInstance(ComponentInstanceAttribute resourceInstanceAttribute, String resourceInstanceId) {
4540
4541                 Either<AttributeValueData, TitanOperationStatus> result = null;
4542                 Wrapper<TitanOperationStatus> errorWrapper = new Wrapper<>();
4543                 UpdateDataContainer<AttributeData, AttributeValueData> updateDataContainer = new UpdateDataContainer<>(GraphEdgeLabels.ATTRIBUTE_IMPL, (() -> AttributeData.class), (() -> AttributeValueData.class), NodeTypeEnum.Attribute,
4544                                 NodeTypeEnum.AttributeValue);
4545                 preUpdateElementOfResourceInstanceValidations(updateDataContainer, resourceInstanceAttribute, resourceInstanceId, errorWrapper);
4546                 if (errorWrapper.isEmpty()) {
4547                         AttributeValueData attributeValueData = updateDataContainer.getValueDataWrapper().getInnerElement();
4548                         attributeValueData.setHidden(resourceInstanceAttribute.isHidden());
4549                         attributeValueData.setValue(resourceInstanceAttribute.getValue());
4550                         Either<AttributeValueData, TitanOperationStatus> updateRes = titanGenericDao.updateNode(attributeValueData, AttributeValueData.class);
4551                         if (updateRes.isRight()) {
4552                                 TitanOperationStatus status = updateRes.right().value();
4553                                 errorWrapper.setInnerElement(status);
4554                         } else {
4555                                 result = Either.left(updateRes.left().value());
4556                         }
4557                 }
4558                 if (!errorWrapper.isEmpty()) {
4559                         result = Either.right(errorWrapper.getInnerElement());
4560                 }
4561                 return result;
4562
4563         }
4564
4565         private Either<AttributeValueData, TitanOperationStatus> addAttributeToResourceInstance(ComponentInstanceAttribute attributeInstanceProperty, String resourceInstanceId, Integer index) {
4566                 Wrapper<TitanOperationStatus> errorWrapper = new Wrapper<>();
4567                 Wrapper<ComponentInstanceData> compInsWrapper = new Wrapper<>();
4568                 Wrapper<AttributeData> attDataWrapper = new Wrapper<>();
4569                 Wrapper<AttributeValueData> attValueDataWrapper = new Wrapper<>();
4570
4571                 // Verify RI Exist
4572                 validateRIExist(resourceInstanceId, compInsWrapper, errorWrapper);
4573
4574                 if (errorWrapper.isEmpty()) {
4575                         // Verify Attribute Exist
4576                         validateElementExistInGraph(attributeInstanceProperty.getUniqueId(), NodeTypeEnum.Attribute, () -> AttributeData.class, attDataWrapper, errorWrapper);
4577                 }
4578                 if (errorWrapper.isEmpty()) {
4579                         // Create AttributeValueData that is connected to RI
4580                         createAttributeValueDataNode(attributeInstanceProperty, index, errorWrapper, compInsWrapper.getInnerElement(), attValueDataWrapper);
4581                 }
4582                 if (errorWrapper.isEmpty()) {
4583                         // Connect AttributeValueData (Att on RI) to AttData (Att on
4584                         // Resource)
4585                         connectAttValueDataToAttData(errorWrapper, attDataWrapper.getInnerElement(), attValueDataWrapper.getInnerElement());
4586                 }
4587                 if (errorWrapper.isEmpty()) {
4588                         // Connect AttributeValueData to RI
4589                         connectAttValueDataToComponentInstanceData(errorWrapper, compInsWrapper.getInnerElement(), attValueDataWrapper.getInnerElement());
4590                 }
4591
4592                 if (errorWrapper.isEmpty()) {
4593                         return Either.left(attValueDataWrapper.getInnerElement());
4594                 } else {
4595                         return Either.right(errorWrapper.getInnerElement());
4596                 }
4597
4598         }
4599
4600         /**
4601          * update value of attribute on resource instance
4602          * 
4603          * @param resourceInstanceProerty
4604          * @param resourceInstanceId
4605          * @return
4606          */
4607         public Either<PropertyValueData, TitanOperationStatus> updatePropertyOfResourceInstance(ComponentInstanceProperty resourceInstanceProerty, String resourceInstanceId, boolean isValidate) {
4608
4609                 Wrapper<TitanOperationStatus> errorWrapper = new Wrapper<>();
4610                 UpdateDataContainer<PropertyData, PropertyValueData> updateDataContainer = new UpdateDataContainer<>(GraphEdgeLabels.PROPERTY_IMPL, (() -> PropertyData.class), (() -> PropertyValueData.class), NodeTypeEnum.Property,
4611                                 NodeTypeEnum.PropertyValue);
4612
4613                 preUpdateElementOfResourceInstanceValidations(updateDataContainer, resourceInstanceProerty, resourceInstanceId, errorWrapper);
4614                 if (!errorWrapper.isEmpty()) {
4615                         return Either.right(errorWrapper.getInnerElement());
4616                 }
4617
4618                 else {
4619                         String value = resourceInstanceProerty.getValue();
4620                         // Specific Validation Logic
4621                         PropertyData propertyData = updateDataContainer.getDataWrapper().getInnerElement();
4622
4623                         String innerType = null;
4624
4625                         PropertyDataDefinition propDataDef = propertyData.getPropertyDataDefinition();
4626                         String propertyType = propDataDef.getType();
4627                         ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
4628                         log.debug("The type of the property {} is {}", propertyData.getUniqueId(), propertyType);
4629
4630                         if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
4631                                 SchemaDefinition def = propDataDef.getSchema();
4632                                 if (def == null) {
4633                                         log.debug("Schema doesn't exists for property of type {}", type);
4634                                         return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
4635                                 }
4636                                 PropertyDataDefinition propDef = def.getProperty();
4637                                 if (propDef == null) {
4638                                         log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
4639                                         return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
4640                                 }
4641                                 innerType = propDef.getType();
4642                         }
4643                         // Specific Update Logic
4644                         Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
4645                         if (allDataTypes.isRight()) {
4646                                 TitanOperationStatus status = allDataTypes.right().value();
4647                                 BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
4648                                 return Either.right(status);
4649                         }
4650                         Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, value, isValidate, innerType, allDataTypes.left().value());
4651
4652                         String newValue = value;
4653                         if (isValid.isRight()) {
4654                                 Boolean res = isValid.right().value();
4655                                 if (res == false) {
4656                                         return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
4657                                 }
4658                         } else {
4659                                 Object object = isValid.left().value();
4660                                 if (object != null) {
4661                                         newValue = object.toString();
4662                                 }
4663                         }
4664                         PropertyValueData propertyValueData = updateDataContainer.getValueDataWrapper().getInnerElement();
4665                         log.debug("Going to update property value from {} to {}", propertyValueData.getValue(), newValue);
4666                         propertyValueData.setValue(newValue);
4667
4668                         ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, resourceInstanceProerty.getRules(), innerType, allDataTypes.left().value(), isValidate);
4669                         if (pair.getRight() != null && pair.getRight() == false) {
4670                                 BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), resourceInstanceProerty.getName(), propertyType);
4671                                 return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
4672                         }
4673                         propertyOperation.updateRulesInPropertyValue(propertyValueData, resourceInstanceProerty, resourceInstanceId);
4674
4675                         Either<PropertyValueData, TitanOperationStatus> updateRes = titanGenericDao.updateNode(propertyValueData, PropertyValueData.class);
4676                         if (updateRes.isRight()) {
4677                                 TitanOperationStatus status = updateRes.right().value();
4678                                 return Either.right(status);
4679                         } else {
4680                                 return Either.left(updateRes.left().value());
4681                         }
4682                 }
4683
4684         }
4685
4686         /**
4687          * update value of attribute on resource instance
4688          * 
4689          * @param resourceInstanceProerty
4690          * @param resourceInstanceId
4691          * @return
4692          */
4693         public Either<InputValueData, TitanOperationStatus> updateInputOfResourceInstance(ComponentInstanceInput resourceInstanceProerty, String resourceInstanceId) {
4694
4695                 Wrapper<TitanOperationStatus> errorWrapper = new Wrapper<>();
4696                 UpdateDataContainer<PropertyData, InputValueData> updateDataContainer = new UpdateDataContainer<>(GraphEdgeLabels.INPUT_IMPL, (() -> PropertyData.class), (() -> InputValueData.class), NodeTypeEnum.Input, NodeTypeEnum.InputValue);
4697
4698                 preUpdateElementOfResourceInstanceValidations(updateDataContainer, resourceInstanceProerty, resourceInstanceId, errorWrapper);
4699                 if (!errorWrapper.isEmpty()) {
4700                         return Either.right(errorWrapper.getInnerElement());
4701                 }
4702
4703                 else {
4704                         String value = resourceInstanceProerty.getValue();
4705                         // Specific Validation Logic
4706                         PropertyData propertyData = updateDataContainer.getDataWrapper().getInnerElement();
4707
4708                         String innerType = null;
4709
4710                         PropertyDataDefinition propDataDef = propertyData.getPropertyDataDefinition();
4711                         String propertyType = propDataDef.getType();
4712                         ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
4713                         log.debug("The type of the property {} is {}", propertyData.getUniqueId(), propertyType);
4714
4715                         if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
4716                                 SchemaDefinition def = propDataDef.getSchema();
4717                                 if (def == null) {
4718                                         log.debug("Schema doesn't exists for property of type {}", type);
4719                                         return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
4720                                 }
4721                                 PropertyDataDefinition propDef = def.getProperty();
4722                                 if (propDef == null) {
4723                                         log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
4724                                         return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
4725                                 }
4726                                 innerType = propDef.getType();
4727                         }
4728                         // Specific Update Logic
4729                         Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
4730                         if (allDataTypes.isRight()) {
4731                                 TitanOperationStatus status = allDataTypes.right().value();
4732                                 BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
4733                                 return Either.right(status);
4734                         }
4735                         /*
4736                          * Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, value, innerType, allDataTypes.left().value());
4737                          * 
4738                          * String newValue = value; if (isValid.isRight()) { Boolean res = isValid.right().value(); if (res == false) { return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); } } else { Object object = isValid.left().value(); if (object !=
4739                          * null) { newValue = object.toString(); } } InputValueData propertyValueData = updateDataContainer.getValueDataWrapper().getInnerElement(); log.debug("Going to update property value from " + propertyValueData.getValue() + " to " +
4740                          * newValue); propertyValueData.setValue(newValue);
4741                          * 
4742                          * ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, resourceInstanceProerty.getRules(), innerType, allDataTypes.left().value()); if (pair.getRight() != null && pair.getRight() == false) {
4743                          * BeEcompErrorManager.getInstance(). logBeInvalidValueError("Add property value", pair.getLeft(), resourceInstanceProerty.getName(), propertyType); return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); }
4744                          * propertyOperation.updateRulesInPropertyValue(propertyValueData, resourceInstanceProerty, resourceInstanceId);
4745                          * 
4746                          * Either<PropertyValueData, TitanOperationStatus> updateRes = titanGenericDao.updateNode(propertyValueData, PropertyValueData.class); if (updateRes.isRight()) { TitanOperationStatus status = updateRes.right().value(); return
4747                          * Either.right(status); } else { return Either.left(updateRes.left().value()); }
4748                          */
4749                 }
4750                 return null;
4751
4752         }
4753
4754         private <SomeData extends GraphNode, SomeValueData extends GraphNode> void preUpdateElementOfResourceInstanceValidations(UpdateDataContainer<SomeData, SomeValueData> updateDataContainer, IComponentInstanceConnectedElement resourceInstanceProerty,
4755                         String resourceInstanceId, Wrapper<TitanOperationStatus> errorWrapper) {
4756
4757                 if (errorWrapper.isEmpty()) {
4758                         // Verify VFC instance Exist
4759                         validateRIExist(resourceInstanceId, errorWrapper);
4760                 }
4761
4762                 if (errorWrapper.isEmpty()) {
4763                         // Example: Verify Property connected to VFC exist
4764                         validateElementConnectedToComponentExist(updateDataContainer, resourceInstanceProerty, errorWrapper);
4765                 }
4766
4767                 if (errorWrapper.isEmpty()) {
4768                         // Example: Verify PropertyValue connected to VFC Instance exist
4769                         validateElementConnectedToComponentInstanceExist(updateDataContainer, resourceInstanceProerty, errorWrapper);
4770                 }
4771
4772                 if (errorWrapper.isEmpty()) {
4773                         // Example: Verify PropertyValue connected Property
4774                         validateElementConnectedToInstance(updateDataContainer, resourceInstanceProerty, errorWrapper);
4775                 }
4776         }
4777
4778         private <SomeData extends GraphNode, SomeValueData extends GraphNode> void validateElementConnectedToInstance(UpdateDataContainer<SomeData, SomeValueData> updateDataContainer, IComponentInstanceConnectedElement resourceInstanceProerty,
4779                         Wrapper<TitanOperationStatus> errorWrapper) {
4780                 Either<ImmutablePair<SomeData, GraphEdge>, TitanOperationStatus> child = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(updateDataContainer.getNodeTypeValue()), resourceInstanceProerty.getValueUniqueUid(),
4781                                 updateDataContainer.getGraphEdge(), updateDataContainer.getNodeType(), updateDataContainer.getSomeDataClassGen().get());
4782
4783                 if (child.isRight()) {
4784                         TitanOperationStatus status = child.right().value();
4785                         if (status == TitanOperationStatus.NOT_FOUND) {
4786                                 status = TitanOperationStatus.INVALID_ID;
4787                         }
4788                         errorWrapper.setInnerElement(status);
4789
4790                 } else {
4791                         updateDataContainer.getDataWrapper().setInnerElement(child.left().value().left);
4792                 }
4793         }
4794
4795         private <SomeValueData extends GraphNode, SomeData extends GraphNode> void validateElementConnectedToComponentInstanceExist(UpdateDataContainer<SomeData, SomeValueData> updateDataContainer,
4796                         IComponentInstanceConnectedElement resourceInstanceProerty, Wrapper<TitanOperationStatus> errorWrapper) {
4797                 String valueUniqueUid = resourceInstanceProerty.getValueUniqueUid();
4798                 if (valueUniqueUid == null) {
4799                         errorWrapper.setInnerElement(TitanOperationStatus.INVALID_ID);
4800                 } else {
4801                         Either<SomeValueData, TitanOperationStatus> findPropertyValueRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(updateDataContainer.getNodeTypeValue()), valueUniqueUid, updateDataContainer.getSomeValueDataClassGen().get());
4802                         if (findPropertyValueRes.isRight()) {
4803                                 TitanOperationStatus status = findPropertyValueRes.right().value();
4804                                 if (status == TitanOperationStatus.NOT_FOUND) {
4805                                         status = TitanOperationStatus.INVALID_ID;
4806                                 }
4807                                 errorWrapper.setInnerElement(status);
4808                         } else {
4809                                 updateDataContainer.getValueDataWrapper().setInnerElement(findPropertyValueRes.left().value());
4810                         }
4811                 }
4812         }
4813
4814         private <SomeData extends GraphNode, SomeValueData extends GraphNode> void validateElementConnectedToComponentExist(UpdateDataContainer<SomeData, SomeValueData> updateDataContainer,
4815                         IComponentInstanceConnectedElement resourceInstanceElementConnected, Wrapper<TitanOperationStatus> errorWrapper) {
4816                 String uniqueId = resourceInstanceElementConnected.getUniqueId();
4817                 Either<SomeData, TitanOperationStatus> findPropertyDefRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(updateDataContainer.getNodeType()), uniqueId, updateDataContainer.getSomeDataClassGen().get());
4818
4819                 if (findPropertyDefRes.isRight()) {
4820                         TitanOperationStatus status = findPropertyDefRes.right().value();
4821                         errorWrapper.setInnerElement(status);
4822                 }
4823         }
4824
4825         private void validateRIExist(String resourceInstanceId, Wrapper<TitanOperationStatus> errorWrapper) {
4826                 validateRIExist(resourceInstanceId, null, errorWrapper);
4827         }
4828
4829         private void validateRIExist(String resourceInstanceId, Wrapper<ComponentInstanceData> compInsDataWrapper, Wrapper<TitanOperationStatus> errorWrapper) {
4830                 validateElementExistInGraph(resourceInstanceId, NodeTypeEnum.ResourceInstance, () -> ComponentInstanceData.class, compInsDataWrapper, errorWrapper);
4831         }
4832
4833         public <ElementData extends GraphNode> void validateElementExistInGraph(String elementUniqueId, NodeTypeEnum elementNodeType, Supplier<Class<ElementData>> elementClassGen, Wrapper<ElementData> elementDataWrapper,
4834                         Wrapper<TitanOperationStatus> errorWrapper) {
4835                 Either<ElementData, TitanOperationStatus> findResInstanceRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(elementNodeType), elementUniqueId, elementClassGen.get());
4836                 if (findResInstanceRes.isRight()) {
4837                         TitanOperationStatus status = findResInstanceRes.right().value();
4838                         if (status == TitanOperationStatus.NOT_FOUND) {
4839                                 status = TitanOperationStatus.INVALID_ID;
4840                         }
4841                         errorWrapper.setInnerElement(status);
4842                 } else {
4843                         if (elementDataWrapper != null) {
4844                                 elementDataWrapper.setInnerElement(findResInstanceRes.left().value());
4845                         }
4846                 }
4847         }
4848
4849         /**
4850          * add property to resource instance
4851          * 
4852          * @param resourceInstanceProperty
4853          * @param resourceInstanceId
4854          * @param index
4855          * @return
4856          */
4857         public Either<PropertyValueData, TitanOperationStatus> addPropertyToResourceInstance(ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId, boolean isValidate, Integer index) {
4858
4859                 Either<ComponentInstanceData, TitanOperationStatus> findResInstanceRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceId, ComponentInstanceData.class);
4860
4861                 if (findResInstanceRes.isRight()) {
4862                         TitanOperationStatus status = findResInstanceRes.right().value();
4863                         if (status == TitanOperationStatus.NOT_FOUND) {
4864                                 status = TitanOperationStatus.INVALID_ID;
4865                         }
4866                         return Either.right(status);
4867                 }
4868
4869                 String propertyId = resourceInstanceProperty.getUniqueId();
4870                 Either<PropertyData, TitanOperationStatus> findPropertyDefRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Property), propertyId, PropertyData.class);
4871
4872                 if (findPropertyDefRes.isRight()) {
4873                         TitanOperationStatus status = findPropertyDefRes.right().value();
4874                         if (status == TitanOperationStatus.NOT_FOUND) {
4875                                 status = TitanOperationStatus.INVALID_ID;
4876                         }
4877                         return Either.right(status);
4878                 }
4879
4880                 String valueUniqueUid = resourceInstanceProperty.getValueUniqueUid();
4881                 if (valueUniqueUid == null) {
4882
4883                         PropertyData propertyData = findPropertyDefRes.left().value();
4884                         ComponentInstanceData resourceInstanceData = findResInstanceRes.left().value();
4885
4886                         ImmutablePair<TitanOperationStatus, String> isPropertyValueExists = propertyOperation.findPropertyValue(resourceInstanceId, propertyId);
4887                         if (isPropertyValueExists.getLeft() == TitanOperationStatus.ALREADY_EXIST) {
4888                                 log.debug("The property {} already added to the resource instance {}", propertyId, resourceInstanceId);
4889                                 resourceInstanceProperty.setValueUniqueUid(isPropertyValueExists.getRight());
4890                                 Either<PropertyValueData, TitanOperationStatus> updatePropertyOfResourceInstance = updatePropertyOfResourceInstance(resourceInstanceProperty, resourceInstanceId, isValidate);
4891                                 if (updatePropertyOfResourceInstance.isRight()) {
4892                                         BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + updatePropertyOfResourceInstance.right().value(), ErrorSeverity.ERROR);
4893                                         return Either.right(updatePropertyOfResourceInstance.right().value());
4894                                 }
4895                                 return Either.left(updatePropertyOfResourceInstance.left().value());
4896                         }
4897
4898                         if (isPropertyValueExists.getLeft() != TitanOperationStatus.NOT_FOUND) {
4899                                 log.debug("After finding property value of {} on componenet instance {}", propertyId, resourceInstanceId);
4900                                 return Either.right(isPropertyValueExists.getLeft());
4901                         }
4902
4903                         String innerType = null;
4904
4905                         PropertyDataDefinition propDataDef = propertyData.getPropertyDataDefinition();
4906                         String propertyType = propDataDef.getType();
4907                         String value = resourceInstanceProperty.getValue();
4908                         ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
4909
4910                         if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
4911                                 SchemaDefinition def = propDataDef.getSchema();
4912                                 if (def == null) {
4913                                         log.debug("Schema doesn't exists for property of type {}", type);
4914                                         return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
4915                                 }
4916                                 PropertyDataDefinition propDef = def.getProperty();
4917                                 if (propDef == null) {
4918                                         log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
4919                                         return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
4920                                 }
4921                                 innerType = propDef.getType();
4922                         }
4923
4924                         log.debug("Before validateAndUpdatePropertyValue");
4925                         Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
4926                         if (allDataTypes.isRight()) {
4927                                 TitanOperationStatus status = allDataTypes.right().value();
4928                                 BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
4929                                 return Either.right(status);
4930                         }
4931                         Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, value, isValidate, innerType, allDataTypes.left().value());
4932                         log.debug("After validateAndUpdatePropertyValue. isValid = {}", isValid);
4933
4934                         String newValue = value;
4935                         if (isValid.isRight()) {
4936                                 Boolean res = isValid.right().value();
4937                                 if (res == false) {
4938                                         return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
4939                                 }
4940                         } else {
4941                                 Object object = isValid.left().value();
4942                                 if (object != null) {
4943                                         newValue = object.toString();
4944                                 }
4945                         }
4946
4947                         String uniqueId = UniqueIdBuilder.buildResourceInstancePropertyValueUid(resourceInstanceData.getUniqueId(), index);
4948                         PropertyValueData propertyValueData = new PropertyValueData();
4949                         propertyValueData.setUniqueId(uniqueId);
4950                         propertyValueData.setValue(newValue);
4951
4952                         log.debug("Before validateAndUpdateRules");
4953                         ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, resourceInstanceProperty.getRules(), innerType, allDataTypes.left().value(), isValidate);
4954                         log.debug("After validateAndUpdateRules. pair = {}", pair);
4955                         if (pair.getRight() != null && pair.getRight() == false) {
4956                                 BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), resourceInstanceProperty.getName(), propertyType);
4957                                 return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
4958                         }
4959                         propertyOperation.addRulesToNewPropertyValue(propertyValueData, resourceInstanceProperty, resourceInstanceId);
4960
4961                         log.debug("Before adding property value to graph {}", propertyValueData);
4962                         Either<PropertyValueData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(propertyValueData, PropertyValueData.class);
4963                         log.debug("After adding property value to graph {}", propertyValueData);
4964
4965                         if (createNodeResult.isRight()) {
4966                                 TitanOperationStatus operationStatus = createNodeResult.right().value();
4967                                 return Either.right(operationStatus);
4968                         }
4969                         propertyValueData = createNodeResult.left().value();
4970
4971                         Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(propertyValueData, propertyData, GraphEdgeLabels.PROPERTY_IMPL, null);
4972
4973                         if (createRelResult.isRight()) {
4974                                 TitanOperationStatus operationStatus = createRelResult.right().value();
4975                                 log.error("Failed to associate property value {} to property {} in graph. status is {}", uniqueId, propertyId, operationStatus);
4976                                 return Either.right(operationStatus);
4977                         }
4978
4979                         createRelResult = titanGenericDao.createRelation(resourceInstanceData, propertyValueData, GraphEdgeLabels.PROPERTY_VALUE, null);
4980
4981                         if (createRelResult.isRight()) {
4982                                 TitanOperationStatus operationStatus = createRelResult.right().value();
4983                                 log.error("Failed to associate resource instance {} property value {} in graph. status is {}", resourceInstanceId, uniqueId, operationStatus);
4984                                 return Either.right(operationStatus);
4985                         }
4986
4987                         return Either.left(propertyValueData);
4988                 } else {
4989                         log.error("property value already exists.");
4990                         return Either.right(TitanOperationStatus.ALREADY_EXIST);
4991                 }
4992
4993         }
4994
4995         public Either<ComponentInstanceProperty, TitanOperationStatus> addPropertyToResourceInstance(ComponentInstanceProperty resourceInstanceProperty, TitanVertex resourceInstanceVertex, boolean isValidate, Integer index, String resourceInstanceId) {
4996
4997                 String propertyId = resourceInstanceProperty.getUniqueId();
4998                 Either<PropertyData, TitanOperationStatus> findPropertyDefRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Property), propertyId, PropertyData.class);
4999
5000                 if (findPropertyDefRes.isRight()) {
5001                         TitanOperationStatus status = findPropertyDefRes.right().value();
5002                         if (status == TitanOperationStatus.NOT_FOUND) {
5003                                 status = TitanOperationStatus.INVALID_ID;
5004                         }
5005                         return Either.right(status);
5006                 }
5007
5008                 String valueUniqueUid = resourceInstanceProperty.getValueUniqueUid();
5009                 if (valueUniqueUid == null) {
5010
5011                         PropertyData propertyData = findPropertyDefRes.left().value();
5012
5013                         ImmutablePair<TitanOperationStatus, String> isPropertyValueExists = propertyOperation.findPropertyValue(resourceInstanceId, propertyId);
5014                         if (isPropertyValueExists.getLeft() == TitanOperationStatus.ALREADY_EXIST) {
5015                                 log.trace("The property {} already added to the resource instance {}", propertyId, resourceInstanceId);
5016                                 resourceInstanceProperty.setValueUniqueUid(isPropertyValueExists.getRight());
5017                                 Either<PropertyValueData, TitanOperationStatus> updatePropertyOfResourceInstance = updatePropertyOfResourceInstance(resourceInstanceProperty, resourceInstanceId, isValidate);
5018                                 if (updatePropertyOfResourceInstance.isRight()) {
5019                                         BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + updatePropertyOfResourceInstance.right().value(), ErrorSeverity.ERROR);
5020                                         return Either.right(updatePropertyOfResourceInstance.right().value());
5021                                 }
5022                                 return Either.right(TitanOperationStatus.OK);
5023                         }
5024
5025                         if (isPropertyValueExists.getLeft() != TitanOperationStatus.NOT_FOUND) {
5026                                 log.trace("After finding property value of {} on componenet instance {}", propertyId, resourceInstanceId);
5027                                 return Either.right(isPropertyValueExists.getLeft());
5028                         }
5029
5030                         String innerType = null;
5031
5032                         PropertyDataDefinition propDataDef = propertyData.getPropertyDataDefinition();
5033                         String propertyType = propDataDef.getType();
5034                         String value = resourceInstanceProperty.getValue();
5035                         ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
5036
5037                         if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
5038                                 SchemaDefinition def = propDataDef.getSchema();
5039                                 if (def == null) {
5040                                         log.debug("Schema doesn't exists for property of type {}", type);
5041                                         return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
5042                                 }
5043                                 PropertyDataDefinition propDef = def.getProperty();
5044                                 if (propDef == null) {
5045                                         log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
5046                                         return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
5047                                 }
5048                                 innerType = propDef.getType();
5049                         }
5050
5051                         log.trace("Before validateAndUpdatePropertyValue");
5052                         Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
5053                         if (allDataTypes.isRight()) {
5054                                 TitanOperationStatus status = allDataTypes.right().value();
5055                                 BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
5056                                 return Either.right(status);
5057                         }
5058                         Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, value, isValidate, innerType, allDataTypes.left().value());
5059                         log.trace("After validateAndUpdatePropertyValue. isValid = {}", isValid);
5060
5061                         String newValue = value;
5062                         if (isValid.isRight()) {
5063                                 Boolean res = isValid.right().value();
5064                                 if (res == false) {
5065                                         return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
5066                                 }
5067                         } else {
5068                                 Object object = isValid.left().value();
5069                                 if (object != null) {
5070                                         newValue = object.toString();
5071                                 }
5072                         }
5073
5074                         String uniqueId = UniqueIdBuilder.buildResourceInstancePropertyValueUid(resourceInstanceId, index);
5075                         PropertyValueData propertyValueData = new PropertyValueData();
5076                         propertyValueData.setUniqueId(uniqueId);
5077                         propertyValueData.setValue(newValue);
5078
5079                         log.trace("Before validateAndUpdateRules");
5080                         ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, resourceInstanceProperty.getRules(), innerType, allDataTypes.left().value(), isValidate);
5081                         log.debug("After validateAndUpdateRules. pair = {} ", pair);
5082                         if (pair.getRight() != null && pair.getRight() == false) {
5083                                 BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), resourceInstanceProperty.getName(), propertyType);
5084                                 return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
5085                         }
5086                         propertyOperation.addRulesToNewPropertyValue(propertyValueData, resourceInstanceProperty, resourceInstanceId);
5087
5088                         log.trace("Before adding property value to graph {}", propertyValueData);
5089                         Either<PropertyValueData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(propertyValueData, PropertyValueData.class);
5090                         log.trace("After adding property value to graph {}", propertyValueData);
5091
5092                         if (createNodeResult.isRight()) {
5093                                 TitanOperationStatus operationStatus = createNodeResult.right().value();
5094                                 return Either.right(operationStatus);
5095                         }
5096                         propertyValueData = createNodeResult.left().value();
5097
5098                         Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(propertyValueData, propertyData, GraphEdgeLabels.PROPERTY_IMPL, null);
5099
5100                         if (createRelResult.isRight()) {
5101                                 TitanOperationStatus operationStatus = createRelResult.right().value();
5102                                 log.error("Failed to associate property value {} to property {} in graph. status is {}", uniqueId, propertyId, operationStatus);
5103                                 return Either.right(operationStatus);
5104                         }
5105
5106                         TitanOperationStatus edgeResult = titanGenericDao.createEdge(resourceInstanceVertex, propertyValueData, GraphEdgeLabels.PROPERTY_VALUE, null);
5107
5108                         if (edgeResult != TitanOperationStatus.OK) {
5109                                 log.error("Failed to associate resource instance {} property value {} in graph. status is {}", resourceInstanceId, uniqueId, edgeResult);
5110                                 return Either.right(edgeResult);
5111                         }
5112
5113                         ComponentInstanceProperty propertyValueResult = propertyOperation.buildResourceInstanceProperty(propertyValueData, resourceInstanceProperty);
5114                         log.debug("The returned ResourceInstanceProperty is {} ", propertyValueResult);
5115
5116                         return Either.left(propertyValueResult);
5117                 } else {
5118                         log.debug("property value already exists.");
5119                         return Either.right(TitanOperationStatus.ALREADY_EXIST);
5120                 }
5121
5122         }
5123
5124         /**
5125          * add property to resource instance
5126          * 
5127          * @param resourceInstanceProperty
5128          * @param resourceInstanceId
5129          * @param index
5130          * @return
5131          */
5132         public Either<InputValueData, TitanOperationStatus> addInputToResourceInstance(ComponentInstanceInput resourceInstanceInput, String resourceInstanceId, Integer index) {
5133
5134                 Either<ComponentInstanceData, TitanOperationStatus> findResInstanceRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceId, ComponentInstanceData.class);
5135
5136                 if (findResInstanceRes.isRight()) {
5137                         TitanOperationStatus status = findResInstanceRes.right().value();
5138                         if (status == TitanOperationStatus.NOT_FOUND) {
5139                                 status = TitanOperationStatus.INVALID_ID;
5140                         }
5141                         return Either.right(status);
5142                 }
5143
5144                 String propertyId = resourceInstanceInput.getUniqueId();
5145                 Either<InputsData, TitanOperationStatus> findPropertyDefRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Input), propertyId, InputsData.class);
5146
5147                 if (findPropertyDefRes.isRight()) {
5148                         TitanOperationStatus status = findPropertyDefRes.right().value();
5149                         if (status == TitanOperationStatus.NOT_FOUND) {
5150                                 status = TitanOperationStatus.INVALID_ID;
5151                         }
5152                         return Either.right(status);
5153                 }
5154
5155                 String valueUniqueUid = resourceInstanceInput.getValueUniqueUid();
5156                 if (valueUniqueUid == null) {
5157
5158                         InputsData propertyData = findPropertyDefRes.left().value();
5159
5160                         ComponentInstanceData resourceInstanceData = findResInstanceRes.left().value();
5161
5162                         ImmutablePair<TitanOperationStatus, String> isInputValueExists = inputOperation.findInputValue(resourceInstanceId, propertyId);
5163                         if (isInputValueExists.getLeft() == TitanOperationStatus.ALREADY_EXIST) {
5164                                 log.debug("The property {} already added to the resource instance {}", propertyId, resourceInstanceId);
5165                                 resourceInstanceInput.setValueUniqueUid(isInputValueExists.getRight());
5166                                 /*
5167                                  * Either<InputValueData, TitanOperationStatus> updatePropertyOfResourceInstance = updatePropertyOfResourceInstance(resourceInstanceInput, resourceInstanceId); if (updatePropertyOfResourceInstance.isRight()) {
5168                                  * BeEcompErrorManager.getInstance().logInternalFlowError( "UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + updatePropertyOfResourceInstance.right().value(), ErrorSeverity.ERROR);
5169                                  * return Either.right(updatePropertyOfResourceInstance.right().value() ); } return Either.left(updatePropertyOfResourceInstance.left().value());
5170                                  */
5171                         }
5172
5173                         if (isInputValueExists.getLeft() != TitanOperationStatus.NOT_FOUND) {
5174                                 log.debug("After finding input value of {} on componenet instance {}", propertyId, resourceInstanceId);
5175                                 return Either.right(isInputValueExists.getLeft());
5176                         }
5177
5178                         String innerType = null;
5179
5180                         PropertyDataDefinition propDataDef = propertyData.getPropertyDataDefinition();
5181                         String propertyType = propDataDef.getType();
5182                         String value = resourceInstanceInput.getValue();
5183                         ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
5184
5185                         if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
5186                                 SchemaDefinition def = propDataDef.getSchema();
5187                                 if (def == null) {
5188                                         log.debug("Schema doesn't exists for property of type {}", type);
5189                                         return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
5190                                 }
5191                                 PropertyDataDefinition propDef = def.getProperty();
5192                                 if (propDef == null) {
5193                                         log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
5194                                         return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
5195                                 }
5196                                 innerType = propDef.getType();
5197                         }
5198
5199                         log.debug("Before validateAndUpdatePropertyValue");
5200                         Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
5201                         if (allDataTypes.isRight()) {
5202                                 TitanOperationStatus status = allDataTypes.right().value();
5203                                 BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
5204                                 return Either.right(status);
5205                         }
5206
5207                         String uniqueId = UniqueIdBuilder.buildResourceInstanceInputValueUid(resourceInstanceData.getUniqueId(), index);
5208                         InputValueData propertyValueData = new InputValueData();
5209                         propertyValueData.setUniqueId(uniqueId);
5210                         propertyValueData.setValue(value);
5211
5212                         log.debug("Before validateAndUpdateRules");
5213                         ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, resourceInstanceInput.getRules(), innerType, allDataTypes.left().value(), true);
5214                         log.debug("After validateAndUpdateRules. pair = {} ", pair);
5215                         if (pair.getRight() != null && pair.getRight() == false) {
5216                                 BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), resourceInstanceInput.getName(), propertyType);
5217                                 return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
5218                         }
5219                         // propertyOperation.addRulesToNewPropertyValue(propertyValueData,
5220                         // resourceInstanceInput, resourceInstanceId);
5221
5222                         log.debug("Before adding property value to graph {}", propertyValueData);
5223                         Either<InputValueData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(propertyValueData, InputValueData.class);
5224                         log.debug("After adding property value to graph {}", propertyValueData);
5225
5226                         if (createNodeResult.isRight()) {
5227                                 TitanOperationStatus operationStatus = createNodeResult.right().value();
5228                                 return Either.right(operationStatus);
5229                         }
5230
5231                         Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(propertyValueData, propertyData, GraphEdgeLabels.INPUT_IMPL, null);
5232
5233                         if (createRelResult.isRight()) {
5234                                 TitanOperationStatus operationStatus = createRelResult.right().value();
5235                                 log.error("Failed to associate property value {} to property {} in graph. status is {}", uniqueId, propertyId, operationStatus);
5236                                 return Either.right(operationStatus);
5237                         }
5238
5239                         Map<String, Object> properties1 = new HashMap<String, Object>();
5240
5241                         properties1.put(GraphEdgePropertiesDictionary.NAME.getProperty(), resourceInstanceData.getComponentInstDataDefinition().getName());
5242                         properties1.put(GraphEdgePropertiesDictionary.OWNER_ID.getProperty(), resourceInstanceData.getComponentInstDataDefinition().getUniqueId());
5243
5244                         createRelResult = titanGenericDao.createRelation(resourceInstanceData, propertyValueData, GraphEdgeLabels.INPUT_VALUE, properties1);
5245
5246                         if (createRelResult.isRight()) {
5247                                 TitanOperationStatus operationStatus = createNodeResult.right().value();
5248                                 log.error("Failed to associate resource instance {} property value {} in graph. status is {}", resourceInstanceId, uniqueId, operationStatus);
5249                                 return Either.right(operationStatus);
5250
5251                         }
5252
5253                         // inputOperation.associatePropertyToInput(resourceInstanceId,
5254                         // resourceInstanceInput.getInputId(), propertyValueData,
5255                         // resourceInstanceInput.getName());
5256
5257                         return Either.left(createNodeResult.left().value());
5258                 } else {
5259                         log.error("property value already exists.");
5260                         return Either.right(TitanOperationStatus.ALREADY_EXIST);
5261                 }
5262
5263         }
5264
5265         @Override
5266         public Either<ComponentInstanceAttribute, StorageOperationStatus> addAttributeValueToResourceInstance(ComponentInstanceAttribute resourceInstanceAttribute, String resourceInstanceId, Integer index, boolean inTransaction) {
5267                 Either<ComponentInstanceAttribute, StorageOperationStatus> result = null;
5268
5269                 try {
5270
5271                         Either<AttributeValueData, TitanOperationStatus> eitherStatus = this.addAttributeToResourceInstance(resourceInstanceAttribute, resourceInstanceId, index);
5272
5273                         if (eitherStatus.isRight()) {
5274                                 log.error("Failed to add attribute value {} to resource instance {} in Graph. status is {}", resourceInstanceAttribute, resourceInstanceId, eitherStatus.right().value().name());
5275                                 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(eitherStatus.right().value()));
5276                                 return result;
5277                         } else {
5278                                 AttributeValueData attributeValueData = eitherStatus.left().value();
5279
5280                                 ComponentInstanceAttribute attributeValueResult = attributeOperation.buildResourceInstanceAttribute(attributeValueData, resourceInstanceAttribute);
5281                                 log.debug("The returned ResourceInstanceAttribute is {}", attributeValueResult);
5282
5283                                 result = Either.left(attributeValueResult);
5284                                 return result;
5285                         }
5286                 }
5287
5288                 finally {
5289                         handleTransactionCommitRollback(inTransaction, result);
5290                 }
5291         }
5292
5293         @Override
5294         public Either<ComponentInstanceAttribute, StorageOperationStatus> updateAttributeValueInResourceInstance(ComponentInstanceAttribute resourceInstanceAttribute, String resourceInstanceId, boolean inTransaction) {
5295
5296                 Either<ComponentInstanceAttribute, StorageOperationStatus> result = null;
5297
5298                 try {
5299                         Either<AttributeValueData, TitanOperationStatus> eitherAttributeValue = updateAttributeOfResourceInstance(resourceInstanceAttribute, resourceInstanceId);
5300
5301                         if (eitherAttributeValue.isRight()) {
5302                                 log.error("Failed to add attribute value {} to resource instance {} in Graph. status is {}", resourceInstanceAttribute, resourceInstanceId, eitherAttributeValue.right().value().name());
5303                                 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(eitherAttributeValue.right().value()));
5304                                 return result;
5305                         } else {
5306                                 AttributeValueData attributeValueData = eitherAttributeValue.left().value();
5307
5308                                 ComponentInstanceAttribute attributeValueResult = attributeOperation.buildResourceInstanceAttribute(attributeValueData, resourceInstanceAttribute);
5309                                 log.debug("The returned ResourceInstanceAttribute is {}", attributeValueResult);
5310
5311                                 result = Either.left(attributeValueResult);
5312                                 return result;
5313                         }
5314                 }
5315
5316                 finally {
5317                         handleTransactionCommitRollback(inTransaction, result);
5318                 }
5319
5320         }
5321
5322         @Override
5323         public Either<ComponentInstanceProperty, StorageOperationStatus> addPropertyValueToResourceInstance(ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId, Integer index, boolean inTransaction) {
5324                 return addPropertyValueToResourceInstance(resourceInstanceProperty, resourceInstanceId, true, index, inTransaction);
5325         }
5326
5327         @Override
5328         public Either<ComponentInstanceProperty, StorageOperationStatus> addPropertyValueToResourceInstance(ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId, boolean isValidate, Integer index, boolean inTransaction) {
5329
5330                 /// #RULES SUPPORT
5331                 /// Ignore rules received from client till support
5332                 resourceInstanceProperty.setRules(null);
5333                 ///
5334                 ///
5335
5336                 Either<ComponentInstanceProperty, StorageOperationStatus> result = null;
5337
5338                 try {
5339
5340                         Either<PropertyValueData, TitanOperationStatus> eitherStatus = addPropertyToResourceInstance(resourceInstanceProperty, resourceInstanceId, isValidate, index);
5341
5342                         if (eitherStatus.isRight()) {
5343                                 log.error("Failed to add property value {} to resource instance {} in Graph. status is {}", resourceInstanceProperty, resourceInstanceId, eitherStatus.right().value().name());
5344                                 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(eitherStatus.right().value()));
5345                                 return result;
5346                         } else {
5347                                 PropertyValueData propertyValueData = eitherStatus.left().value();
5348
5349                                 ComponentInstanceProperty propertyValueResult = propertyOperation.buildResourceInstanceProperty(propertyValueData, resourceInstanceProperty);
5350                                 log.debug("The returned ResourceInstanceProperty is {}", propertyValueResult);
5351
5352                                 Either<String, TitanOperationStatus> findDefaultValue = propertyOperation.findDefaultValueFromSecondPosition(resourceInstanceProperty.getPath(), resourceInstanceProperty.getUniqueId(), resourceInstanceProperty.getDefaultValue());
5353                                 if (findDefaultValue.isRight()) {
5354                                         result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(findDefaultValue.right().value()));
5355                                         return result;
5356                                 }
5357                                 String defaultValue = findDefaultValue.left().value();
5358                                 propertyValueResult.setDefaultValue(defaultValue);
5359                                 log.debug("The returned default value in ResourceInstanceProperty is {}", defaultValue);
5360
5361                                 result = Either.left(propertyValueResult);
5362                                 return result;
5363                         }
5364                 }
5365
5366                 finally {
5367                         if (false == inTransaction) {
5368                                 if (result == null || result.isRight()) {
5369                                         log.error("Going to execute rollback on graph.");
5370                                         titanGenericDao.rollback();
5371                                 } else {
5372                                         log.debug("Going to execute commit on graph.");
5373                                         titanGenericDao.commit();
5374                                 }
5375                         }
5376                 }
5377
5378         }
5379
5380         @Override
5381         public Either<ComponentInstanceInput, StorageOperationStatus> addInputValueToResourceInstance(ComponentInstanceInput resourceInstanceInput, String resourceInstanceId, Integer index, boolean inTransaction) {
5382
5383                 /// #RULES SUPPORT
5384                 /// Ignore rules received from client till support
5385                 resourceInstanceInput.setRules(null);
5386                 ///
5387                 ///
5388
5389                 Either<ComponentInstanceInput, StorageOperationStatus> result = null;
5390
5391                 try {
5392
5393                         Either<InputValueData, TitanOperationStatus> eitherStatus = addInputToResourceInstance(resourceInstanceInput, resourceInstanceId, index);
5394
5395                         if (eitherStatus.isRight()) {
5396                                 log.error("Failed to add input value {} to resource instance {} in Graph. status is {}", resourceInstanceInput, resourceInstanceId, eitherStatus.right().value().name());
5397                                 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(eitherStatus.right().value()));
5398                                 return result;
5399                         } else {
5400                                 InputValueData propertyValueData = eitherStatus.left().value();
5401
5402                                 ComponentInstanceInput propertyValueResult = inputOperation.buildResourceInstanceInput(propertyValueData, resourceInstanceInput);
5403                                 log.debug("The returned ResourceInstanceProperty is {}", propertyValueResult);
5404
5405                                 Either<String, TitanOperationStatus> findDefaultValue = propertyOperation.findDefaultValueFromSecondPosition(resourceInstanceInput.getPath(), resourceInstanceInput.getUniqueId(), resourceInstanceInput.getDefaultValue());
5406                                 if (findDefaultValue.isRight()) {
5407                                         result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(findDefaultValue.right().value()));
5408                                         return result;
5409                                 }
5410                                 String defaultValue = findDefaultValue.left().value();
5411                                 propertyValueResult.setDefaultValue(defaultValue);
5412                                 log.debug("The returned default value in ResourceInstanceProperty is {}", defaultValue);
5413
5414                                 result = Either.left(propertyValueResult);
5415                                 return result;
5416                         }
5417                 }
5418
5419                 finally {
5420                         if (false == inTransaction) {
5421                                 if (result == null || result.isRight()) {
5422                                         log.error("Going to execute rollback on graph.");
5423                                         titanGenericDao.rollback();
5424                                 } else {
5425                                         log.debug("Going to execute commit on graph.");
5426                                         titanGenericDao.commit();
5427                                 }
5428                         }
5429                 }
5430
5431         }
5432
5433         public Either<List<ComponentInstanceProperty>, TitanOperationStatus> getComponentInstancesProperties(List<ComponentInstance> resourceInstances, Map<String, List<PropertyDefinition>> alreadyProcessedResources,
5434                         Map<String, List<ComponentInstanceProperty>> resourceInstancesProperties, Map<String, ImmutablePair<ComponentInstance, Integer>> processedInstances, List<String> path) {
5435
5436                 List<ComponentInstanceProperty> result = new ArrayList<>();
5437
5438                 for (ComponentInstance componentInstance : resourceInstances) {
5439
5440                         path.add(componentInstance.getUniqueId());
5441
5442                         Either<List<ComponentInstanceProperty>, TitanOperationStatus> componentInstancesProperties = getComponentInstanceProperties(componentInstance, alreadyProcessedResources, resourceInstancesProperties, processedInstances, path);
5443                         if (componentInstancesProperties.isRight()) {
5444                                 TitanOperationStatus status = componentInstancesProperties.right().value();
5445                                 if (status != TitanOperationStatus.OK) {
5446                                         return Either.right(status);
5447                                 }
5448                         }
5449
5450                         List<ComponentInstanceProperty> compInstancePropertyList = componentInstancesProperties.left().value();
5451                         if (compInstancePropertyList != null) {
5452                                 result.addAll(compInstancePropertyList);
5453                         }
5454
5455                         String uniqueId = componentInstance.getUniqueId();
5456                         if (false == processedInstances.containsKey(uniqueId)) {
5457                                 processedInstances.put(uniqueId, new ImmutablePair<ComponentInstance, Integer>(componentInstance, path.size()));
5458                         }
5459                         path.remove(path.size() - 1);
5460
5461                 }
5462
5463                 return Either.left(result);
5464         }
5465
5466         // TODO Tal G US831698
5467         public Either<List<ComponentInstanceProperty>, StorageOperationStatus> getComponentInstancesPropertiesAndValuesFromGraph(ComponentInstance resourceInstance) {
5468
5469                 Map<String, List<PropertyDefinition>> alreadyProcessedResources = new HashMap<>();
5470                 Map<String, List<ComponentInstanceProperty>> alreadyProcessedInstances = new HashMap<>();
5471                 Map<String, ImmutablePair<ComponentInstance, Integer>> processedInstances = new HashMap<>();
5472                 Map<String, List<ComponentInstanceProperty>> resourceInstancesProperties = new HashMap<>();
5473
5474                 List<String> path = new ArrayList<>();
5475                 path.add(resourceInstance.getUniqueId());
5476                 Either<List<ComponentInstanceProperty>, TitanOperationStatus> componentInstanceProperties = getComponentInstanceProperties(resourceInstance, alreadyProcessedResources, alreadyProcessedInstances, processedInstances, path);
5477
5478                 if (componentInstanceProperties.isRight()) {
5479                         StorageOperationStatus convertTitanStatusToStorageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(componentInstanceProperties.right().value());
5480                         return Either.right(convertTitanStatusToStorageStatus);
5481                 }
5482
5483                 List<ComponentInstanceProperty> listOfProps = componentInstanceProperties.left().value();
5484                 resourceInstancesProperties.put(resourceInstance.getUniqueId(), listOfProps);
5485
5486                 processedInstances.put(resourceInstance.getUniqueId(), new ImmutablePair<ComponentInstance, Integer>(resourceInstance, path.size()));
5487                 path.remove(path.size() - 1);
5488
5489                 Either<Map<String, Map<String, ComponentInstanceProperty>>, TitanOperationStatus> findAllPropertiesValuesOnInstances = findAllPropertyValueOnInstances(processedInstances);
5490                 // 1. check status
5491                 if (findAllPropertiesValuesOnInstances.isRight()) {
5492                         return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(findAllPropertiesValuesOnInstances.right().value()));
5493                 }
5494
5495                 propertyOperation.updatePropertiesByPropertyValues(resourceInstancesProperties, findAllPropertiesValuesOnInstances.left().value());
5496
5497                 return Either.left(resourceInstancesProperties.get(resourceInstance.getUniqueId()));
5498         }
5499
5500         public Either<List<ComponentInstanceProperty>, TitanOperationStatus> getComponentInstanceProperties(ComponentInstance resourceInstance, Map<String, List<PropertyDefinition>> alreadyProcessedResources,
5501                         Map<String, List<ComponentInstanceProperty>> alreadyProcessedInstances, Map<String, ImmutablePair<ComponentInstance, Integer>> processedInstances, List<String> path) {
5502
5503                 // 1. Go over each instance
5504                 // 1.1 get all properties of from the parents of the instance
5505                 // 1.2 get all updated properties
5506                 // 1.3 find all instances included in the parent of this instance and
5507                 // run this method on them.
5508                 if (log.isDebugEnabled())
5509                         log.debug("Going to update properties of resource instance {}", resourceInstance.getUniqueId());
5510                 String resourceUid = resourceInstance.getComponentUid();
5511
5512                 List<PropertyDefinition> properties = alreadyProcessedResources.get(resourceUid);
5513                 if (properties == null) {
5514                         properties = new ArrayList<>();
5515                         TitanOperationStatus findAllRes = propertyOperation.findAllResourcePropertiesRecursively(resourceUid, properties);
5516                         if (findAllRes != TitanOperationStatus.OK) {
5517                                 return Either.right(findAllRes);
5518                         }
5519                         alreadyProcessedResources.put(resourceUid, properties);
5520                 }
5521
5522                 if (log.isDebugEnabled())
5523                         log.debug("After getting properties of resource {} . Number of properties is {}", resourceUid, (properties == null ? 0 : properties.size()));
5524                 List<ComponentInstanceProperty> resourceInstancePropertyList = new ArrayList<>();
5525                 if (false == properties.isEmpty()) {
5526
5527                         // TODO: WE MAY HAVE INDIRECT PROPERTY VALUE ALSO IN CASE NO
5528                         // PROPERTY ON THIS COMPONENT
5529
5530                         // String resourceInstanceUid = resourceInstance.getUniqueId();
5531
5532                         for (PropertyDefinition propertyDefinition : properties) {
5533
5534                                 String defaultValue = propertyDefinition.getDefaultValue();
5535                                 String value = defaultValue;
5536                                 String valueUid = null;
5537
5538                                 // String propertyId = propertyDefinition.getUniqueId();
5539
5540                                 ComponentInstanceProperty resourceInstanceProperty = new ComponentInstanceProperty(propertyDefinition, value, valueUid);
5541
5542                                 resourceInstanceProperty.setPath(cloneList(path));
5543
5544                                 // TODO: currently ignore constraints since they are not inuse
5545                                 // and cause to error in convertion to object.
5546                                 resourceInstanceProperty.setConstraints(null);
5547
5548                                 resourceInstancePropertyList.add(resourceInstanceProperty);
5549
5550                         }
5551                 }
5552
5553                 OriginTypeEnum originType = resourceInstance.getOriginType();
5554
5555                 Either<List<ComponentInstance>, TitanOperationStatus> findInstancesUnderParentOfInstance = findInstancesUnderParentOfInstance(originType, resourceUid);
5556
5557                 if (findInstancesUnderParentOfInstance.isRight()) {
5558                         TitanOperationStatus status = findInstancesUnderParentOfInstance.right().value();
5559                         if (status != TitanOperationStatus.NOT_FOUND) {
5560                                 return Either.right(status);
5561                         }
5562                 } else {
5563                         List<ComponentInstance> listOfInstances = findInstancesUnderParentOfInstance.left().value();
5564                         Either<List<ComponentInstanceProperty>, TitanOperationStatus> componentInstancesProperties = getComponentInstancesProperties(listOfInstances, alreadyProcessedResources, alreadyProcessedInstances, processedInstances, path);
5565                         if (componentInstancesProperties.isRight()) {
5566                                 TitanOperationStatus status = componentInstancesProperties.right().value();
5567                                 if (status != TitanOperationStatus.OK) {
5568                                         return Either.right(status);
5569                                 }
5570                         }
5571                         List<ComponentInstanceProperty> currentList = componentInstancesProperties.left().value();
5572                         if (currentList != null) {
5573                                 resourceInstancePropertyList.addAll(currentList);
5574                         }
5575                 }
5576
5577                 return Either.left(resourceInstancePropertyList);
5578         }
5579
5580         public Either<List<ComponentInstance>, TitanOperationStatus> findInstancesUnderParentOfInstance(OriginTypeEnum originType, String resourceUid) {
5581
5582                 NodeTypeEnum containerNodeType = null;
5583                 NodeTypeEnum compInstNodeType = null;
5584
5585                 switch (originType) {
5586
5587                 case VF:
5588                         containerNodeType = NodeTypeEnum.Resource;
5589                         compInstNodeType = NodeTypeEnum.Resource;
5590                         break;
5591                 case SERVICE:
5592                         containerNodeType = NodeTypeEnum.Service;
5593                         compInstNodeType = NodeTypeEnum.Resource;
5594                         break;
5595                 case PRODUCT:
5596                         containerNodeType = NodeTypeEnum.Product;
5597                         compInstNodeType = NodeTypeEnum.Service;
5598                         break;
5599                 case VFC:
5600                 case VFCMT:
5601                 case VL:
5602                 case CP:
5603                         break;
5604                 default:
5605                         break;
5606                 }
5607
5608                 if (containerNodeType == null || compInstNodeType == null) {
5609                         return Either.right(TitanOperationStatus.NOT_FOUND);
5610                 }
5611
5612                 Either<ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>>, TitanOperationStatus> componentInstancesOfComponent = this.getComponentInstancesOfComponent(resourceUid, containerNodeType, compInstNodeType);
5613
5614                 if (componentInstancesOfComponent.isRight()) {
5615                         TitanOperationStatus status = componentInstancesOfComponent.right().value();
5616                         log.debug("After getting instances of {}  from type {}. Status is {}", resourceUid, originType, status);
5617                         return Either.right(status);
5618                 } else {
5619                         List<ComponentInstance> listOfInstances = componentInstancesOfComponent.left().value().getLeft();
5620                         if (log.isDebugEnabled()) {
5621                                 String msg = "After getting instances of {}  from type {}   {}.";
5622                                 log.debug(msg, resourceUid, originType, (listOfInstances != null ? listOfInstances.size() : 0));
5623                                 if (log.isTraceEnabled())
5624                                         log.trace(msg, resourceUid, originType, listOfInstances);
5625                         }
5626                         return Either.left(listOfInstances);
5627                 }
5628
5629         }
5630
5631         private List<String> cloneList(List<String> list) {
5632
5633                 if (list == null) {
5634                         return null;
5635                 }
5636
5637                 List<String> clonedList = new ArrayList<String>();
5638                 clonedList.addAll(list);
5639
5640                 return clonedList;
5641         }
5642
5643         public Either<Map<String, Map<String, ComponentInstanceProperty>>, TitanOperationStatus> findAllPropertyValueOnInstances(Map<String, ImmutablePair<ComponentInstance, Integer>> processedInstances) {
5644
5645                 if (processedInstances == null) {
5646                         return Either.right(TitanOperationStatus.OK);
5647                 }
5648
5649                 Set<Entry<String, ImmutablePair<ComponentInstance, Integer>>> entrySet = processedInstances.entrySet();
5650
5651                 Map<String, Map<String, ComponentInstanceProperty>> propertyToInstanceValue = new HashMap<>();
5652
5653                 for (Entry<String, ImmutablePair<ComponentInstance, Integer>> entry : entrySet) {
5654
5655                         String compInstUniqueId = entry.getKey();
5656
5657                         ImmutablePair<ComponentInstance, Integer> pair = entry.getValue();
5658
5659                         ComponentInstance componentInstance = pair.getLeft();
5660
5661                         Either<List<ComponentInstanceProperty>, TitanOperationStatus> propeprtyValueOnCIResult = findPropertyValueOnComponentInstance(componentInstance);
5662
5663                         if (propeprtyValueOnCIResult.isRight()) {
5664                                 TitanOperationStatus status = propeprtyValueOnCIResult.right().value();
5665                                 if (status != TitanOperationStatus.OK) {
5666                                         return Either.right(status);
5667                                 }
5668                                 continue;
5669                         }
5670
5671                         List<ComponentInstanceProperty> propertyValuesOnCI = propeprtyValueOnCIResult.left().value();
5672                         if (propertyValuesOnCI != null) {
5673                                 for (ComponentInstanceProperty instanceProperty : propertyValuesOnCI) {
5674                                         boolean result = addPropertyValue(compInstUniqueId, instanceProperty, propertyToInstanceValue);
5675                                         if (!result) {
5676                                                 return Either.right(TitanOperationStatus.ALREADY_EXIST);
5677                                         }
5678                                 }
5679                         }
5680
5681                 }
5682
5683                 return Either.left(propertyToInstanceValue);
5684         }
5685
5686         private boolean addPropertyValue(String compInstUniqueId, ComponentInstanceProperty instanceProperty, Map<String, Map<String, ComponentInstanceProperty>> propertyToInstanceValue) {
5687
5688                 String propertyUid = instanceProperty.getUniqueId();
5689
5690                 Map<String, ComponentInstanceProperty> map = propertyToInstanceValue.get(propertyUid);
5691                 if (map == null) {
5692                         map = new HashMap<>();
5693                         propertyToInstanceValue.put(propertyUid, map);
5694                 }
5695
5696                 ComponentInstanceProperty putIfAbsent = map.putIfAbsent(compInstUniqueId, instanceProperty);
5697                 if (putIfAbsent != null) {
5698                         BeEcompErrorManager.getInstance().logInternalUnexpectedError("find property value", "Found 2 values on the same instance", ErrorSeverity.ERROR);
5699                         return false;
5700                 }
5701
5702                 return true;
5703
5704         }
5705
5706         private boolean addInputValue(String compInstUniqueId, ComponentInstanceInput instanceProperty, Map<String, Map<String, ComponentInstanceInput>> propertyToInstanceValue) {
5707
5708                 String propertyUid = instanceProperty.getUniqueId();
5709
5710                 Map<String, ComponentInstanceInput> map = propertyToInstanceValue.get(propertyUid);
5711                 if (map == null) {
5712                         map = new HashMap<>();
5713                         propertyToInstanceValue.put(propertyUid, map);
5714                 }
5715
5716                 ComponentInstanceInput putIfAbsent = map.putIfAbsent(compInstUniqueId, instanceProperty);
5717                 if (putIfAbsent != null) {
5718                         BeEcompErrorManager.getInstance().logInternalUnexpectedError("find property value", "Found 2 values on the same instance", ErrorSeverity.ERROR);
5719                         return false;
5720                 }
5721
5722                 return true;
5723
5724         }
5725
5726         private Either<List<ComponentInstanceProperty>, TitanOperationStatus> findPropertyValueOnComponentInstance(ComponentInstance componentInstance) {
5727                 String resourceInstanceUid = componentInstance.getUniqueId();
5728                 OriginTypeEnum originType = componentInstance.getOriginType();
5729
5730                 NodeTypeEnum instanceNodeType = findInstanceNodeTypeEnumFromOriginType(originType);
5731
5732                 Either<List<ComponentInstanceProperty>, TitanOperationStatus> propertyValuesResult = propertyOperation.getAllPropertiesOfResourceInstanceOnlyPropertyDefId(resourceInstanceUid, instanceNodeType);
5733
5734                 log.debug("After fetching property under resource instance {}", resourceInstanceUid);
5735                 if (propertyValuesResult.isRight()) {
5736                         TitanOperationStatus status = propertyValuesResult.right().value();
5737                         if (status != TitanOperationStatus.NOT_FOUND) {
5738                                 return Either.right(status);
5739                         }
5740                         return Either.right(TitanOperationStatus.OK);
5741                 }
5742
5743                 return Either.left(propertyValuesResult.left().value());
5744
5745         }
5746
5747         private NodeTypeEnum findInstanceNodeTypeEnumFromOriginType(OriginTypeEnum originType) {
5748                 NodeTypeEnum nodeType = NodeTypeEnum.ResourceInstance;
5749                 switch (originType) {
5750                 case SERVICE:
5751                         nodeType = NodeTypeEnum.ResourceInstance;
5752                         break;
5753                 default:
5754                         break;
5755                 }
5756
5757                 return nodeType;
5758         }
5759
5760         /**
5761          * add capability property values to resource instance
5762          * 
5763          * @param resourceInstanceId
5764          * @param capability
5765          * @param isNewlyCreatedResourceInstance
5766          * @return
5767          */
5768         public Either<Map<CapabilityInstData, List<PropertyValueData>>, TitanOperationStatus> addCapabilityPropertyValuesToResourceInstance(String resourceInstanceId, CapabilityDefinition capability, boolean isNewlyCreatedResourceInstance) {
5769                 log.debug("Before adding capability property values to resource instance {}.", resourceInstanceId);
5770                 TitanOperationStatus error = null;
5771
5772                 Either<Map<CapabilityInstData, List<PropertyValueData>>, TitanOperationStatus> addCapInstWithPropertiesRes = capabilityInstanceOperation.createCapabilityInstanceOfCapabilityWithPropertyValuesForResourceInstance(resourceInstanceId,
5773                                 capability.getUniqueId(), capability.getName(), capability.getProperties(), !isNewlyCreatedResourceInstance);
5774                 if (addCapInstWithPropertiesRes.isRight()) {
5775                         error = addCapInstWithPropertiesRes.right().value();
5776                         log.debug("Failed to assotiate capability instance to resource instance {}. status is {}", resourceInstanceId, error);
5777                 }
5778                 log.debug("After adding capability property values to resource instance {}. Status is {}", resourceInstanceId, error);
5779                 if (error == null) {
5780                         return Either.left(addCapInstWithPropertiesRes.left().value());
5781                 }
5782                 return Either.right(error);
5783         }
5784
5785         public TitanOperationStatus addCapabilityPropertyValuesToResourceInstance(TitanVertex resourceInstanceVertex, String resourceInstanceId, CapabilityDefinition capability, boolean isNewlyCreatedResourceInstance) {
5786                 log.trace("Before adding capability property values to resource instance {}.", resourceInstanceId);
5787                 TitanOperationStatus error = TitanOperationStatus.OK;
5788
5789                 TitanOperationStatus addCapInstWithPropertiesRes = capabilityInstanceOperation.createCapabilityInstanceOfCapabilityWithPropertyValuesForResourceInstance(resourceInstanceVertex, resourceInstanceId, capability.getUniqueId(),
5790                                 capability.getName(), capability.getProperties(), !isNewlyCreatedResourceInstance);
5791                 if (addCapInstWithPropertiesRes != TitanOperationStatus.OK) {
5792                         error = addCapInstWithPropertiesRes;
5793                         log.debug("Failed to assotiate capability instance to resource instance {} . status is {}", resourceInstanceId, error);
5794                 }
5795                 log.debug("After adding capability property values to resource instance {}. Status is {}", resourceInstanceId, error);
5796
5797                 return error;
5798         }
5799
5800         /**
5801          * update capability property values of capability
5802          * 
5803          * @param resourceInstanceId
5804          * @param capabilityId
5805          * @param propertyValues
5806          * @return
5807          */
5808         public Either<List<PropertyValueData>, TitanOperationStatus> updateCapabilityPropertyValuesOfResourceInstance(String resourceInstanceId, String capabilityId, List<ComponentInstanceProperty> propertyValues) {
5809                 log.debug("Before updating property values of capability {} of resource instance {}.", capabilityId, resourceInstanceId);
5810                 TitanOperationStatus error = null;
5811                 Either<List<PropertyValueData>, TitanOperationStatus> updateCapabilityPropertyValuesRes = capabilityInstanceOperation.updateCapabilityPropertyValues(resourceInstanceId, capabilityId, propertyValues);
5812                 if (updateCapabilityPropertyValuesRes.isRight()) {
5813                         error = updateCapabilityPropertyValuesRes.right().value();
5814                         log.debug("Failed to update property values of capability {} of resource instance {}. status is {}", capabilityId, resourceInstanceId, error);
5815                 }
5816                 log.debug("After updating property values of capability {} of resource instance {}. Status is {}", capabilityId, resourceInstanceId, error);
5817                 if (error == null) {
5818                         return Either.left(updateCapabilityPropertyValuesRes.left().value());
5819                 }
5820                 return Either.right(error);
5821         }
5822
5823         /**
5824          * delete property values of capability from resource instance
5825          * 
5826          * @param capabilityId
5827          * @param resourceInstanceId
5828          * @return
5829          */
5830         public Either<CapabilityInstData, TitanOperationStatus> deletePropertyValuesOfCapabilityFromResourceInstance(String capabilityId, String resourceInstanceId) {
5831                 log.debug("Before deleting property values of capability {} from resource instance {}.", capabilityId, resourceInstanceId);
5832                 TitanOperationStatus error = null;
5833                 Either<CapabilityInstData, TitanOperationStatus> deleteCapInstWithPropertiesRes = null;
5834                 Either<CapabilityInstData, TitanOperationStatus> getCapInstByCapabilityRes = capabilityInstanceOperation.getCapabilityInstanceOfCapabilityOfResourceInstance(resourceInstanceId, capabilityId);
5835                 if (getCapInstByCapabilityRes.isRight()) {
5836                         error = getCapInstByCapabilityRes.right().value();
5837                         log.debug("Failed to retrieve capability instance of capability {} of resource instance {}. status is {}", capabilityId, resourceInstanceId, error);
5838                 }
5839                 if (error == null) {
5840                         String capabilityInstanceId = getCapInstByCapabilityRes.left().value().getUniqueId();
5841                         deleteCapInstWithPropertiesRes = capabilityInstanceOperation.deleteCapabilityInstanceFromResourceInstance(resourceInstanceId, capabilityInstanceId);
5842                         if (deleteCapInstWithPropertiesRes.isRight()) {
5843                                 error = deleteCapInstWithPropertiesRes.right().value();
5844                                 log.debug("Failed to delete capability instance {} to resource instance {}. status is {}", capabilityInstanceId, resourceInstanceId, error);
5845                         }
5846                 }
5847                 log.debug("After deleting property values of capability {} from resource instance {}. Status is {}", capabilityId, resourceInstanceId, error);
5848                 if (error == null) {
5849                         return Either.left(deleteCapInstWithPropertiesRes.left().value());
5850                 }
5851                 return Either.right(error);
5852         }
5853
5854         /**
5855          * clone capability instances of resource instance
5856          * 
5857          * @param createdComponentInstance
5858          * @param resourceInstance
5859          * @return
5860          */
5861         private Either<Map<ImmutablePair<CapabilityInstData, GraphEdge>, List<PropertyValueData>>, TitanOperationStatus> cloneCapabilityInstancesOfResourceInstance(ComponentInstanceData createdComponentInstance, ComponentInstance resourceInstance) {
5862                 TitanOperationStatus error = null;
5863                 String resourceInstanceId = resourceInstance.getUniqueId();
5864                 log.debug("Before cloning of capability instances of resource instance {}.", resourceInstanceId);
5865
5866                 Map<ImmutablePair<CapabilityInstData, GraphEdge>, List<PropertyValueData>> result = new HashMap<>();
5867                 Either<ImmutablePair<CapabilityInstData, List<PropertyValueData>>, TitanOperationStatus> cloneAssociateCIWithPropertyValuesRes;
5868                 Either<List<ImmutablePair<CapabilityInstData, GraphEdge>>, TitanOperationStatus> getAllCapabilityInstancesRes = capabilityInstanceOperation.getAllCapabilityInstancesOfResourceInstance(resourceInstanceId);
5869                 if (getAllCapabilityInstancesRes.isRight() && !getAllCapabilityInstancesRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
5870                         error = getAllCapabilityInstancesRes.right().value();
5871                         log.debug("Failed to get capability instances of component instance {}. status is {}", resourceInstanceId, error);
5872                 }
5873                 if (getAllCapabilityInstancesRes.isLeft()) {
5874                         List<ImmutablePair<CapabilityInstData, GraphEdge>> capabilityInstances = getAllCapabilityInstancesRes.left().value();
5875                         Map<String, List<CapabilityDefinition>> allCapabilitiesMap = resourceInstance.getCapabilities();
5876                         List<CapabilityDefinition> allCapabilitiesList = new ArrayList<>();
5877                         for (List<CapabilityDefinition> curList : allCapabilitiesMap.values()) {
5878                                 allCapabilitiesList.addAll(curList);
5879                         }
5880                         Map<String, CapabilityDefinition> capabilities = allCapabilitiesList.stream().collect(Collectors.toMap(CapabilityDefinition::getUniqueId, Function.identity()));
5881                         String propertyName = GraphPropertiesDictionary.CAPABILITY_ID.getProperty();
5882                         for (ImmutablePair<CapabilityInstData, GraphEdge> capabilityInstPair : capabilityInstances) {
5883                                 String capabilityId = (String) capabilityInstPair.getRight().getProperties().get(propertyName);
5884                                 CapabilityDefinition relatedCapability = capabilities.get(capabilityId);
5885                                 cloneAssociateCIWithPropertyValuesRes = capabilityInstanceOperation.cloneAssociateCapabilityInstanceWithPropertyValues(createdComponentInstance, relatedCapability, capabilityInstPair);
5886                                 if (cloneAssociateCIWithPropertyValuesRes.isRight()) {
5887                                         error = cloneAssociateCIWithPropertyValuesRes.right().value();
5888                                         log.debug("Failed to clone capability instances {} of component instance {}. status is {}", capabilityInstPair.getLeft().getUniqueId(), resourceInstanceId, error);
5889                                         break;
5890                                 } else {
5891                                         result.put(new ImmutablePair<CapabilityInstData, GraphEdge>(cloneAssociateCIWithPropertyValuesRes.left().value().getLeft(), capabilityInstPair.getRight()), cloneAssociateCIWithPropertyValuesRes.left().value().getRight());
5892                                 }
5893                         }
5894                 }
5895                 log.debug("After cloning of capability instance of resource instance {}. Status is {}", resourceInstanceId, error);
5896                 if (error == null) {
5897                         return Either.left(result);
5898                 }
5899                 return Either.right(error);
5900         }
5901
5902         private Either<List<ImmutablePair<TitanVertex, GraphEdge>>, TitanOperationStatus> cloneCapabilityInstancesOfResourceInstance(TitanVertex componentInstanceVertex, ComponentInstance resourceInstance) {
5903                 TitanOperationStatus error = null;
5904                 String resourceInstanceId = resourceInstance.getUniqueId();
5905                 log.debug("Before cloning of capability instances of resource instance {}.", resourceInstanceId);
5906
5907                 Either<TitanVertex, TitanOperationStatus> cloneAssociateCIWithPropertyValuesRes = null;
5908                 Either<List<ImmutablePair<CapabilityInstData, GraphEdge>>, TitanOperationStatus> getAllCapabilityInstancesRes = capabilityInstanceOperation.getAllCapabilityInstancesOfResourceInstance(resourceInstanceId);
5909                 if (getAllCapabilityInstancesRes.isRight() && getAllCapabilityInstancesRes.right().value() != TitanOperationStatus.NOT_FOUND) {
5910                         error = getAllCapabilityInstancesRes.right().value();
5911                         log.debug("Failed to get capability instances of component instance {}. status is {}", resourceInstanceId, error);
5912                 }
5913                 List<ImmutablePair<TitanVertex, GraphEdge>> list = new ArrayList<>();
5914                 if (getAllCapabilityInstancesRes.isLeft()) {
5915                         List<ImmutablePair<CapabilityInstData, GraphEdge>> capabilityInstances = getAllCapabilityInstancesRes.left().value();
5916                         Map<String, List<CapabilityDefinition>> allCapabilitiesMap = resourceInstance.getCapabilities();
5917                         List<CapabilityDefinition> allCapabilitiesList = new ArrayList<>();
5918                         for (List<CapabilityDefinition> curList : allCapabilitiesMap.values()) {
5919                                 allCapabilitiesList.addAll(curList);
5920                         }
5921                         Map<String, CapabilityDefinition> capabilities = allCapabilitiesList.stream().collect(Collectors.toMap(CapabilityDefinition::getUniqueId, Function.identity()));
5922                         String propertyName = GraphPropertiesDictionary.CAPABILITY_ID.getProperty();
5923                         for (ImmutablePair<CapabilityInstData, GraphEdge> capabilityInstPair : capabilityInstances) {
5924                                 String capabilityId = (String) capabilityInstPair.getRight().getProperties().get(propertyName);
5925                                 CapabilityDefinition relatedCapability = capabilities.get(capabilityId);
5926                                 cloneAssociateCIWithPropertyValuesRes = capabilityInstanceOperation.cloneAssociateCapabilityInstanceWithPropertyValues(componentInstanceVertex, relatedCapability, capabilityInstPair);
5927                                 if (cloneAssociateCIWithPropertyValuesRes.isRight()) {
5928                                         error = cloneAssociateCIWithPropertyValuesRes.right().value();
5929                                         log.debug("Failed to clone capability instances {} of component instance {}. status is {}", capabilityInstPair.getLeft().getUniqueId(), resourceInstanceId, error);
5930                                         break;
5931                                 } else {
5932                                         list.add(new ImmutablePair<TitanVertex, GraphEdge>(cloneAssociateCIWithPropertyValuesRes.left().value(), capabilityInstPair.right));
5933                                 }
5934                         }
5935                 }
5936                 log.debug("After cloning of capability instance of resource instance {}. Status is {}", resourceInstanceId, error);
5937                 if (error == null) {
5938                         return Either.left(list);
5939                 }
5940                 return Either.right(error);
5941         }
5942
5943         public Either<List<ComponentInstance>, StorageOperationStatus> getAllComponentInstancesMetadataOnly(String componentId, NodeTypeEnum containerNodeType) {
5944
5945                 List<ComponentInstance> componentInstancesResult = new ArrayList<ComponentInstance>();
5946                 Either<List<ComponentInstance>, StorageOperationStatus> result = Either.left(componentInstancesResult);
5947
5948                 Either<List<ImmutablePair<ComponentInstanceData, GraphEdge>>, TitanOperationStatus> resourceInstancesRes = getAllComponentInstanceFromGraph(componentId, containerNodeType, false);
5949
5950                 if (resourceInstancesRes.isRight()) {
5951
5952                         if (log.isDebugEnabled()) {
5953                                 log.debug("Resource instance was found under service {} . status is {} ", componentId, resourceInstancesRes.right().value());
5954                         }
5955                         return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resourceInstancesRes.right().value()));
5956                 }
5957
5958                 List<ImmutablePair<ComponentInstanceData, GraphEdge>> resourceInstances = resourceInstancesRes.left().value();
5959                 if (resourceInstances != null && false == resourceInstances.isEmpty()) {
5960
5961                         for (ImmutablePair<ComponentInstanceData, GraphEdge> immutablePair : resourceInstances) {
5962                                 ComponentInstanceData resourceInstanceData = immutablePair.getKey();
5963                                 if (log.isDebugEnabled()) {
5964                                         log.debug("Going to fetch the relationships of resource instance {}", resourceInstanceData);
5965                                 }
5966                                 componentInstancesResult.add(new ComponentInstance(resourceInstanceData.getComponentInstDataDefinition()));
5967
5968                         }
5969                 }
5970
5971                 return result;
5972         }
5973
5974         public Either<List<CapabilityDefinition>, TitanOperationStatus> updateCapDefPropertyValues(ComponentInstance componentInstance, List<CapabilityDefinition> capabilityDefList) {
5975                 String componentInstanceId = componentInstance.getUniqueId();
5976                 log.debug("Before updating property values of capabilities of component istance {}.", componentInstanceId);
5977                 TitanOperationStatus error = null;
5978                 NodeTypeEnum nodeType = NodeTypeEnum.getByNameIgnoreCase(componentInstance.getOriginType().getInstanceType().trim());
5979
5980                 log.debug("Before getting all capability instances of component istance {}.", componentInstanceId);
5981                 Either<List<ImmutablePair<CapabilityInstData, GraphEdge>>, TitanOperationStatus> getCapabilityInstancesRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeType), componentInstanceId, GraphEdgeLabels.CAPABILITY_INST,
5982                                 NodeTypeEnum.CapabilityInst, CapabilityInstData.class);
5983                 if (getCapabilityInstancesRes.isRight() && !getCapabilityInstancesRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
5984                         error = getCapabilityInstancesRes.right().value();
5985                         log.debug("Failed to retrieve capability Instances of resource instance {}. Status is {}", componentInstance.getName(), error);
5986                 }
5987                 log.debug("After getting all capability instances of component istance {}. Status is {}", componentInstanceId, error);
5988                 Map<String, Map<String, PropertyValueData>> overridedCapabilitiesHM = new HashMap<>();
5989                 if (getCapabilityInstancesRes.isLeft()) {
5990                         List<ImmutablePair<CapabilityInstData, GraphEdge>> capabilityInstDataPair = getCapabilityInstancesRes.left().value();
5991
5992                         for (ImmutablePair<CapabilityInstData, GraphEdge> curCapabilityPair : capabilityInstDataPair) {
5993                                 CapabilityInstData curCapabilityInst = curCapabilityPair.getLeft();
5994                                 String curCapInstUid = curCapabilityInst.getUniqueId();
5995
5996                                 log.debug("Before getting all property values of capability instance {} of component istance {}.", curCapInstUid, componentInstanceId);
5997                                 Either<List<ImmutablePair<PropertyValueData, GraphEdge>>, TitanOperationStatus> getOverridedPropertyValuesRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.getByName(curCapabilityInst.getLabel())),
5998                                                 curCapInstUid, GraphEdgeLabels.PROPERTY_VALUE, NodeTypeEnum.PropertyValue, PropertyValueData.class);
5999                                 if (getOverridedPropertyValuesRes.isRight()) {
6000                                         error = getOverridedPropertyValuesRes.right().value();
6001                                         log.debug("Failed to retrieve property values of capability instance {}. Status is {}", curCapInstUid, error);
6002                                 } else {                                
6003                                         log.debug("After getting all property values of capability instance {} of component istance {}. Status is {}", curCapInstUid, componentInstanceId, error);
6004                                         Map<String, PropertyValueData> overridedPropertyValuesHM = new HashMap<>();
6005                                         List<ImmutablePair<PropertyValueData, GraphEdge>> overridedPropertyValues = getOverridedPropertyValuesRes.left().value();
6006                                         for (ImmutablePair<PropertyValueData, GraphEdge> curPropertyValuePair : overridedPropertyValues) {
6007                                                 PropertyValueData curPropertyValue = curPropertyValuePair.getLeft();
6008                                                 String propertyValueUid = curPropertyValue.getUniqueId();
6009                                                 log.debug("Before getting property related to property value {} of capability instance {} of component istance {}.", propertyValueUid, curCapInstUid, componentInstanceId);
6010                                                 Either<ImmutablePair<PropertyData, GraphEdge>, TitanOperationStatus> getPropertyDataRes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.getByName(curPropertyValue.getLabel())), propertyValueUid,
6011                                                                 GraphEdgeLabels.PROPERTY_IMPL, NodeTypeEnum.Property, PropertyData.class);
6012                                                 if (getPropertyDataRes.isRight()) {
6013                                                         error = getOverridedPropertyValuesRes.right().value();
6014                                                         log.debug("Failed to retrieve property of property value {} Status is {}", propertyValueUid, error);
6015                                                 }
6016                                                 log.debug("After getting property related to property value {} of capability instance {} of component istance {}. Status is {}", propertyValueUid, curCapInstUid, componentInstanceId, error);
6017                                                 PropertyData propertyData = getPropertyDataRes.left().value().getLeft();
6018                                                 overridedPropertyValuesHM.put((String) propertyData.getUniqueId(), curPropertyValue);
6019                                         }
6020                                         overridedCapabilitiesHM.put((String) curCapabilityPair.getRight().getProperties().get(GraphPropertiesDictionary.CAPABILITY_ID.getProperty()), overridedPropertyValuesHM);
6021                                 }
6022                         }
6023                 }
6024                 if (error == null && !overridedCapabilitiesHM.isEmpty()) {
6025                         updateCapabilityPropertyValues(componentInstance.getCapabilities(), capabilityDefList, overridedCapabilitiesHM);
6026                 }
6027                 log.debug("After updating property values of capabilities of component istance {}. Status is {}", componentInstanceId, error);
6028                 if (error == null) {
6029                         return Either.left(capabilityDefList);
6030                 }
6031                 return Either.right(error);
6032         }
6033
6034         private void updateCapabilityPropertyValues(Map<String, List<CapabilityDefinition>> capabilitiesOfRI, List<CapabilityDefinition> capabilitiesOfContainer, Map<String, Map<String, PropertyValueData>> overridedCapabilitiesHM) {
6035
6036                 capabilitiesOfContainer.stream().filter(capability -> overridedCapabilitiesHM.containsKey(capability.getUniqueId())).forEach(capability -> {
6037                         boolean updateProperties = false;
6038                         for (ComponentInstanceProperty property : capability.getProperties()) {
6039                                 if (overridedCapabilitiesHM.get(capability.getUniqueId()).containsKey(property.getUniqueId())) {
6040                                         property.setValue(overridedCapabilitiesHM.get(capability.getUniqueId()).get(property.getUniqueId()).getValue());
6041                                         property.setValueUniqueUid(overridedCapabilitiesHM.get(capability.getUniqueId()).get(property.getUniqueId()).getUniqueId());
6042                                         updateProperties = true;
6043                                 }
6044                         }
6045                         if (updateProperties) {
6046                                 capabilitiesOfRI.get(capability.getType()).get(0).setProperties(capability.getProperties());
6047                         }
6048                 });
6049         }
6050
6051         @Override
6052         public Either<ComponentInstanceInput, StorageOperationStatus> updateInputValueInResourceInstance(ComponentInstanceInput input, String resourceInstanceId, boolean b) {
6053                 return null;
6054         }
6055
6056         public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> fetchCIEnvArtifacts(String componentInstanceId) {
6057                 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> result = artifactOperation.getArtifacts(componentInstanceId, NodeTypeEnum.ResourceInstance, true, ArtifactGroupTypeEnum.DEPLOYMENT.getType());
6058                 if (result.isRight() && result.right().value() == StorageOperationStatus.NOT_FOUND)
6059                         return Either.right(StorageOperationStatus.OK);
6060                 return result;
6061         }
6062
6063         @Override
6064         public StorageOperationStatus updateCustomizationUUID(String componentInstanceId) {
6065                 Either<TitanVertex, TitanOperationStatus> vertexByProperty = titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), componentInstanceId);
6066                 if (vertexByProperty.isRight()) {
6067                         log.debug("Failed to fetch component instance by id {} error {}", componentInstanceId, vertexByProperty.right().value());
6068                         return DaoStatusConverter.convertTitanStatusToStorageStatus(vertexByProperty.right().value());
6069                 }
6070                 UUID uuid = UUID.randomUUID();
6071                 TitanVertex ciVertex = vertexByProperty.left().value();
6072                 ciVertex.property(GraphPropertiesDictionary.CUSTOMIZATION_UUID.getProperty(), uuid.toString());
6073
6074                 return StorageOperationStatus.OK;
6075         }
6076
6077         private Either<String, Boolean> handleGroupInstanceNameLogic(TitanVertex ciVertex, GroupInstance groupInstance, String componentInstanceId, String componentInstanceName, String groupName) {
6078
6079                 groupInstance.setGroupName(groupName);
6080
6081                 String logicalName = groupInstanceOperation.createGroupInstLogicalName(componentInstanceName, groupName);
6082
6083                 Boolean eitherValidation = validateGroupInstanceName(logicalName, groupInstance, true);
6084                 if (!eitherValidation) {
6085                         return Either.right(false);
6086                 }
6087                 // groupInstance.setName(logicalName);
6088                 return Either.left(logicalName);
6089         }
6090
6091         private Boolean validateGroupInstanceName(String groupInstanceName, GroupInstance groupInstance, boolean isCreate) {
6092
6093                 if (!ValidationUtils.validateStringNotEmpty(groupInstanceName)) {
6094                         return false;
6095                 }
6096                 groupInstance.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(groupInstanceName));
6097                 if (!isCreate) {
6098                         if (!ValidationUtils.validateResourceInstanceNameLength(groupInstanceName)) {
6099                                 return false;
6100                         }
6101                         if (!ValidationUtils.validateResourceInstanceName(groupInstanceName)) {
6102                                 return false;
6103                         }
6104                 }
6105
6106                 return true;
6107
6108         }
6109         // Evg: need to be public for reuse code in migration
6110         public Either<GroupInstance, StorageOperationStatus> createGroupInstance(TitanVertex ciVertex, GroupDefinition groupDefinition, ComponentInstance componentInstance) {
6111                 // create VFC instance on VF
6112                 GroupInstance groupInstance = null;
6113
6114                 boolean isCreateName = false;
6115                 List<GroupInstance> groupInstances = componentInstance.getGroupInstances();
6116                 if (groupInstances != null && !groupInstances.isEmpty()) {
6117                         Optional<GroupInstance> op = groupInstances.stream().filter(p -> p.getGroupUid().equals(groupDefinition.getUniqueId())).findAny();
6118                         if (op.isPresent()) {
6119                                 groupInstance = op.get();
6120
6121                         }
6122                 }
6123                 if (groupInstance == null) {
6124                         groupInstance = new GroupInstance();
6125                         groupInstance.setGroupUid(groupDefinition.getUniqueId());
6126
6127                         groupInstance.setArtifacts(groupDefinition.getArtifacts());
6128                         Either<String, Boolean> handleNameLogic = handleGroupInstanceNameLogic(ciVertex, groupInstance, componentInstance.getUniqueId(), componentInstance.getNormalizedName(), groupDefinition.getName());
6129                         if (handleNameLogic.isRight() && !handleNameLogic.right().value()) {
6130
6131                                 if (handleNameLogic.isRight()) {
6132                                         log.debug("failed to create logical name gor group instance {}", groupInstance.getName());
6133                                         return Either.right(StorageOperationStatus.INVALID_ID);
6134
6135                                 }
6136                         }
6137                         isCreateName = true;
6138                         // groupInstance.setName(handleNameLogic.left().value());
6139
6140                 }
6141
6142                 return groupInstanceOperation.createGroupInstance(ciVertex, componentInstance.getUniqueId(), groupInstance, isCreateName);
6143
6144         }
6145
6146         @Override
6147         public Either<ComponentInstanceData, StorageOperationStatus> updateComponentInstanceModificationTimeAndCustomizationUuidOnGraph(ComponentInstance componentInstance, NodeTypeEnum componentInstanceType, Long modificationTime, boolean inTransaction) {
6148                 
6149                 log.debug("Going to update modification time of component instance {}. ", componentInstance.getName());
6150                 Either<ComponentInstanceData, StorageOperationStatus> result = null;
6151                 try{
6152                         ComponentInstanceData componentData = new ComponentInstanceData(componentInstance, componentInstance.getGroupInstances().size());
6153                         componentData.getComponentInstDataDefinition().setModificationTime(modificationTime);
6154                         componentData.getComponentInstDataDefinition().setCustomizationUUID(UUID.randomUUID().toString());
6155                         Either<ComponentInstanceData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(componentData, ComponentInstanceData.class);
6156                         if (updateNode.isRight()) {
6157                                 log.error("Failed to update resource {}. status is {}", componentInstance.getUniqueId(), updateNode.right().value());
6158                                 result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateNode.right().value()));
6159                         }else{
6160                                 result = Either.left(updateNode.left().value());
6161                         }
6162                 }catch(Exception e){
6163                         log.error("Exception occured during  update modification date of compomemt instance{}. The message is {}. ", componentInstance.getName(), e.getMessage(), e);
6164                         result = Either.right(StorageOperationStatus.GENERAL_ERROR);
6165                 }finally {
6166                         if(!inTransaction){
6167                                 if (result == null || result.isRight()) {
6168                                         log.error("Going to execute rollback on graph.");
6169                                         titanGenericDao.rollback();
6170                                 } else {
6171                                         log.debug("Going to execute commit on graph.");
6172                                         titanGenericDao.commit();
6173                                 }
6174                         }
6175                 }
6176                 return result;
6177         }
6178 }