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