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