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