aboutsummaryrefslogtreecommitdiffstats
path: root/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ComponentOperation.java
blob: 9d9814efcb42cf3767b48982ad15821aa84f691e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
/*-
 * ============LICENSE_START=======================================================
 * SDC
 * ================================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.openecomp.sdc.be.model.operations.impl;

import java.time.Duration;
import java.time.Instant;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.ImmutableTriple;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.dao.graph.GraphElementFactory;
import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
import org.openecomp.sdc.be.dao.graph.datatype.GraphElementTypeEnum;
import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation;
import org.openecomp.sdc.be.dao.graph.datatype.RelationEndPoint;
import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
import org.openecomp.sdc.be.dao.neo4j.GraphEdgePropertiesDictionary;
import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
import org.openecomp.sdc.be.dao.titan.QueryType;
import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
import org.openecomp.sdc.be.dao.titan.TitanGraphClient;
import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
import org.openecomp.sdc.be.datatypes.category.GroupingDataDefinition;
import org.openecomp.sdc.be.datatypes.components.ComponentMetadataDataDefinition;
import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.model.AdditionalInformationDefinition;
import org.openecomp.sdc.be.model.ArtifactDefinition;
import org.openecomp.sdc.be.model.CapabilityDefinition;
import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.ComponentInstance;
import org.openecomp.sdc.be.model.ComponentInstanceInput;
import org.openecomp.sdc.be.model.ComponentInstanceProperty;
import org.openecomp.sdc.be.model.ComponentParametersView;
import org.openecomp.sdc.be.model.DataTypeDefinition;
import org.openecomp.sdc.be.model.GroupDefinition;
import org.openecomp.sdc.be.model.InputDefinition;
import org.openecomp.sdc.be.model.LifecycleStateEnum;
import org.openecomp.sdc.be.model.PropertyDefinition;
import org.openecomp.sdc.be.model.PropertyDefinition.PropertyNames;
import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
import org.openecomp.sdc.be.model.RequirementDefinition;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
import org.openecomp.sdc.be.model.cache.ComponentCache;
import org.openecomp.sdc.be.model.category.CategoryDefinition;
import org.openecomp.sdc.be.model.category.GroupingDefinition;
import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
import org.openecomp.sdc.be.model.operations.api.IAdditionalInformationOperation;
import org.openecomp.sdc.be.model.operations.api.IArtifactOperation;
import org.openecomp.sdc.be.model.operations.api.ICapabilityOperation;
import org.openecomp.sdc.be.model.operations.api.IElementOperation;
import org.openecomp.sdc.be.model.operations.api.IRequirementOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.api.ToscaDefinitionPathCalculator;
import org.openecomp.sdc.be.resources.data.ArtifactData;
import org.openecomp.sdc.be.resources.data.CapabilityData;
import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
import org.openecomp.sdc.be.resources.data.ProductMetadataData;
import org.openecomp.sdc.be.resources.data.RequirementData;
import org.openecomp.sdc.be.resources.data.ResourceMetadataData;
import org.openecomp.sdc.be.resources.data.ServiceMetadataData;
import org.openecomp.sdc.be.resources.data.TagData;
import org.openecomp.sdc.be.resources.data.UniqueIdData;
import org.openecomp.sdc.be.resources.data.UserData;
import org.openecomp.sdc.be.resources.data.category.CategoryData;
import org.openecomp.sdc.be.resources.data.category.GroupingData;
import org.openecomp.sdc.be.resources.data.category.SubCategoryData;
import org.openecomp.sdc.be.utils.CommonBeUtils;
import org.openecomp.sdc.be.workers.Job;
import org.openecomp.sdc.be.workers.Manager;
import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
import org.openecomp.sdc.common.util.StreamUtils;
import org.openecomp.sdc.common.util.ValidationUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;

import com.google.common.collect.ImmutableSet;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.thinkaurelius.titan.core.TitanGraph;
import com.thinkaurelius.titan.core.TitanGraphQuery;
import com.thinkaurelius.titan.core.TitanVertex;

import fj.data.Either;

public abstract class ComponentOperation {
	private static Logger log = LoggerFactory.getLogger(ComponentOperation.class.getName());

	@Autowired
	protected TitanGenericDao titanGenericDao;

	@Autowired
	protected IArtifactOperation artifactOperation;

	@Autowired
	protected IElementOperation elementOperation;

	@Autowired
	protected ICapabilityOperation capabilityOperation;

	@Autowired
	protected IRequirementOperation requirementOperation;

	@Autowired
	protected ComponentInstanceOperation componentInstanceOperation;

	@Autowired
	private PropertyOperation propertyOperation;

	@Autowired
	protected InputsOperation inputOperation;

	@Autowired
	protected IAdditionalInformationOperation additionalInformationOperation;

	@Autowired
	protected GroupOperation groupOperation;

	@Autowired
	protected InputsOperation inputsOperation;

	@Autowired
	protected ApplicationDataTypeCache applicationDataTypeCache;

	@Autowired
	private ComponentCache componentCache;

	@Autowired
	private ToscaDefinitionPathCalculator toscaDefinitionPathCalculator;

	private static Pattern uuidNewVersion = Pattern.compile("^\\d{1,}.1");

	protected Gson prettyJson = new GsonBuilder().setPrettyPrinting().create();

	protected Either<List<TagData>, StorageOperationStatus> createNewTagsList(List<String> tags) {

		List<TagData> existingTags = new ArrayList<TagData>();
		List<TagData> tagsToCreate = new ArrayList<TagData>();
		Either<List<TagData>, TitanOperationStatus> either = titanGenericDao.getAll(NodeTypeEnum.Tag, TagData.class);

		if ((either.isRight()) && (either.right().value() != TitanOperationStatus.NOT_FOUND)) {
			return Either.right(StorageOperationStatus.GENERAL_ERROR);
		} else if (either.isLeft()) {
			existingTags = either.left().value();
		}

		for (String tagName : tags) {
			TagData tag = new TagData(tagName);
			if ((existingTags == null) || (!existingTags.contains(tag))) {
				tagsToCreate.add(tag);
			}
		}
		return Either.left(tagsToCreate);

	}
 
	protected StorageOperationStatus createTagNodesOnGraph(List<TagData> tagsToCreate) {
		StorageOperationStatus result = StorageOperationStatus.OK;
		// In order to avoid duplicate tags
		tagsToCreate = ImmutableSet.copyOf(tagsToCreate).asList();
		if (tagsToCreate != null && false == tagsToCreate.isEmpty()) {
			for (TagData tagData : tagsToCreate) {
				log.debug("Before creating tag {}" , tagData);
				Either<TagData, TitanOperationStatus> createTagResult = titanGenericDao.createNode(tagData, TagData.class);
				if (createTagResult.isRight()) {
					TitanOperationStatus status = createTagResult.right().value();
					log.error("Cannot create {} in the graph. status is {}", tagData, status);
					result = DaoStatusConverter.convertTitanStatusToStorageStatus(status);

				}
				log.debug("After creating tag {}", tagData);
			}
		}
		return result;
	}

	public Either<Component, StorageOperationStatus> getLatestComponentByUuid(NodeTypeEnum nodeType, String uuid) {
		Either<Component, StorageOperationStatus> getComponentResult = null;
		Either<ComponentMetadataData, StorageOperationStatus> latestComponentMetadataRes = getLatestComponentMetadataByUuid(nodeType, uuid, false);
		if (latestComponentMetadataRes.isRight()) {
			getComponentResult = Either.right(latestComponentMetadataRes.right().value());
		}
		if (getComponentResult == null) {
			ComponentMetadataData latestVersion = latestComponentMetadataRes.left().value();
			String id = latestVersion.getMetadataDataDefinition().getUniqueId();
			Either<Component, StorageOperationStatus> component = getComponent(id, false);
			if (component.isRight()) {
				log.debug("Couldn't fetch component with type {} and id {}, error: {}", nodeType, id, component.right().value());
				getComponentResult = Either.right(component.right().value());
			} else {
				getComponentResult = Either.left(component.left().value());
			}
		}
		return getComponentResult;
	}

	public Either<ComponentMetadataData, StorageOperationStatus> getLatestComponentMetadataByUuid(NodeTypeEnum nodeType, String uuid, boolean inTransaction) {

		Either<ComponentMetadataData, StorageOperationStatus> getComponentResult = null;
		List<ComponentMetadataData> latestVersionList = null;
		ComponentMetadataData latestVersion = null;

		Map<String, Object> propertiesToMatch = new HashMap<String, Object>();
		propertiesToMatch.put(GraphPropertiesDictionary.UUID.getProperty(), uuid);
		propertiesToMatch.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true);
		try{
			Either<List<ComponentMetadataData>, TitanOperationStatus> getComponentEither = titanGenericDao.getByCriteria(nodeType, propertiesToMatch, ComponentMetadataData.class);
			if (getComponentEither.isRight()) {
				log.debug("Couldn't fetch metadata for component with type {} and uuid {}, error: {}", nodeType, uuid, getComponentEither.right().value());
				getComponentResult = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getComponentEither.right().value()));
	
			}
			if (getComponentResult == null) {
				latestVersionList = getComponentEither.left().value();
				if (latestVersionList.isEmpty()) {
					log.debug("Component with type {} and uuid {} was not found", nodeType, uuid);
					getComponentResult = Either.right(StorageOperationStatus.NOT_FOUND);
				}
			}
			if (getComponentResult == null) {
				latestVersion = latestVersionList.size() == 1 ? latestVersionList.get(0)
						: latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getMetadataDataDefinition().getVersion()), Double.parseDouble(c2.getMetadataDataDefinition().getVersion()))).get();
				getComponentResult = Either.left(latestVersion);
			}
		} catch (Exception e){
			log.debug("Failed to get latest component metadata with type {} by uuid {}. ", nodeType.getName(), uuid, e);
		}finally {
			if (!inTransaction) {
				titanGenericDao.commit();
			}
		}
		return getComponentResult;
	}

	public <T extends GraphNode> Either<T, StorageOperationStatus> getComponentByLabelAndId(String uniqueId, NodeTypeEnum nodeType, Class<T> clazz) {

		Map<String, Object> propertiesToMatch = new HashMap<String, Object>();
		propertiesToMatch.put(UniqueIdBuilder.getKeyByNodeType(nodeType), uniqueId);
		Either<List<T>, TitanOperationStatus> getResponse = titanGenericDao.getByCriteria(nodeType, propertiesToMatch, clazz);
		if (getResponse.isRight()) {
			log.debug("Couldn't fetch component with type {} and unique id {}, error: {}", nodeType, uniqueId, getResponse.right().value());
			return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getResponse.right().value()));

		}
		List<T> serviceDataList = getResponse.left().value();
		if (serviceDataList.isEmpty()) {
			log.debug("Component with type {} and unique id {} was not found", nodeType, uniqueId);
			return Either.right(StorageOperationStatus.NOT_FOUND);
		}
		T serviceData = serviceDataList.get(0);
		return Either.left(serviceData);
	}

	/**
	 * 
	 * @param component
	 * @param uniqueId
	 * @param nodeType
	 * @return
	 */
	protected TitanOperationStatus setComponentCreatorFromGraph(Component component, String uniqueId, NodeTypeEnum nodeType) {
		Either<ImmutablePair<UserData, GraphEdge>, TitanOperationStatus> parentNode = titanGenericDao.getParentNode(UniqueIdBuilder.getKeyByNodeType(nodeType), uniqueId, GraphEdgeLabels.CREATOR, NodeTypeEnum.User, UserData.class);
		if (parentNode.isRight()) {
			return parentNode.right().value();
		}

		ImmutablePair<UserData, GraphEdge> value = parentNode.left().value();
		if (log.isDebugEnabled())
			log.debug("Found parent node {}", value);
		UserData userData = value.getKey();
		if (log.isDebugEnabled())
			log.debug("Build resource : set creator userId to {}", userData.getUserId());
		String fullName = buildFullName(userData);
		if (log.isDebugEnabled())
			log.debug("Build resource : set last modifier full name to {} ", fullName);
		component.setCreatorUserId(userData.getUserId());
		component.setCreatorFullName(fullName);

		return TitanOperationStatus.OK;
	}

	protected TitanOperationStatus setComponentLastModifierFromGraph(Component component, String uniqueId, NodeTypeEnum nodeType) {

		Either<ImmutablePair<UserData, GraphEdge>, TitanOperationStatus> parentNode = titanGenericDao.getParentNode(UniqueIdBuilder.getKeyByNodeType(nodeType), uniqueId, GraphEdgeLabels.LAST_MODIFIER, NodeTypeEnum.User, UserData.class);
		if (parentNode.isRight()) {
			return parentNode.right().value();
		}

		ImmutablePair<UserData, GraphEdge> value = parentNode.left().value();
		if (log.isDebugEnabled())
			log.debug("Found parent node {}", value);
		UserData userData = value.getKey();

		if (log.isDebugEnabled())
			log.debug("Build resource : set last modifier userId to {}", userData.getUserId());
		String fullName = buildFullName(userData);
		if (log.isDebugEnabled())
			log.debug("Build resource : set last modifier full name to {}", fullName);
		component.setLastUpdaterUserId(userData.getUserId());
		component.setLastUpdaterFullName(fullName);

		return TitanOperationStatus.OK;
	}

	/**
	 * 
	 * @param userData
	 * @return
	 */
	protected String buildFullName(UserData userData) {

		String fullName = userData.getFirstName();
		if (fullName == null) {
			fullName = "";
		} else {
			fullName = fullName + " ";
		}
		String lastName = userData.getLastName();
		if (lastName != null) {
			fullName += lastName;
		}
		return fullName;
	}

	protected Either<UserData, TitanOperationStatus> findUser(String userId) {
		String key = UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User);
		Either<UserData, TitanOperationStatus> findUser = titanGenericDao.getNode(key, userId, UserData.class);
		return findUser;
	}

	protected Either<TitanVertex, TitanOperationStatus> findUserVertex(String userId) {
		String key = UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User);
		return titanGenericDao.getVertexByProperty(key, userId);
	}

	protected Either<GroupingData, TitanOperationStatus> findGrouping(NodeTypeEnum nodeType, String groupingId) {
		String key = UniqueIdBuilder.getKeyByNodeType(nodeType);
		Either<GroupingData, TitanOperationStatus> findGrouping = titanGenericDao.getNode(key, groupingId, GroupingData.class);
		return findGrouping;
	}

	protected Either<SubCategoryData, TitanOperationStatus> findSubCategory(NodeTypeEnum nodeType, String subCategoryId) {
		String key = UniqueIdBuilder.getKeyByNodeType(nodeType);
		Either<SubCategoryData, TitanOperationStatus> findSubCategory = titanGenericDao.getNode(key, subCategoryId, SubCategoryData.class);
		return findSubCategory;
	}

	protected Either<CategoryData, TitanOperationStatus> findCategory(NodeTypeEnum nodeType, String categoryId) {
		String key = UniqueIdBuilder.getKeyByNodeType(nodeType);
		Either<CategoryData, TitanOperationStatus> findCategory = titanGenericDao.getNode(key, categoryId, CategoryData.class);
		return findCategory;
	}

	protected TitanOperationStatus associateMetadataToComponent(ComponentMetadataData componentData, UserData userData, UserData updater, CategoryData categoryData, List<ResourceMetadataData> derivedResources) {

		Map<String, Object> props = new HashMap<String, Object>();
		props.put(GraphPropertiesDictionary.STATE.getProperty(), componentData.getMetadataDataDefinition().getState());
		Either<GraphRelation, TitanOperationStatus> result = titanGenericDao.createRelation(updater, componentData, GraphEdgeLabels.STATE, props);
		log.debug("After associating user {} to component {}. Edge type is {}" , updater, componentData.getUniqueId(),  GraphEdgeLabels.STATE);
		if (result.isRight()) {
			return result.right().value();
		}

		result = titanGenericDao.createRelation(updater, componentData, GraphEdgeLabels.LAST_MODIFIER, null);
		log.debug("After associating user {} to component {}. Edge type is {}",  updater,  componentData.getUniqueId(), GraphEdgeLabels.LAST_MODIFIER);
		if (result.isRight()) {
			log.error("Failed to associate user {} to component {}. Edge type is {}", updater, componentData.getUniqueId(), GraphEdgeLabels.LAST_MODIFIER);
			return result.right().value();
		}

		result = titanGenericDao.createRelation(userData, componentData, GraphEdgeLabels.CREATOR, null);
		log.debug("After associating user {} to component {}. Edge type is {}" , userData, componentData.getUniqueId(), GraphEdgeLabels.CREATOR);
		if (result.isRight()) {
			log.error("Failed to associate user {} to component {}. Edge type is {}", userData, componentData.getUniqueId(), GraphEdgeLabels.CREATOR);
			return result.right().value();
		}

		if (derivedResources != null) {
			for (ResourceMetadataData derivedResource : derivedResources) {
				log.debug("After associating component {} to parent component {}. Edge type is {}" ,componentData.getUniqueId(), derivedResource.getUniqueId(), GraphEdgeLabels.DERIVED_FROM);
				result = titanGenericDao.createRelation(componentData, derivedResource, GraphEdgeLabels.DERIVED_FROM, null);
				if (result.isRight()) {
					log.error("Failed to associate user {} to component {}. Edge type is {}", userData, componentData.getUniqueId(), GraphEdgeLabels.CREATOR);
					return result.right().value();
				}
			}
		}

		if (categoryData != null) {
			result = titanGenericDao.createRelation(componentData, categoryData, GraphEdgeLabels.CATEGORY, null);
			log.debug("After associating component {} to category {}. Edge type is {}", componentData.getUniqueId(), categoryData, GraphEdgeLabels.CATEGORY);
			if (result.isRight()) {
				log.error("Faield to associate component {} to category {}. Edge type is {}", componentData.getUniqueId(), categoryData, GraphEdgeLabels.CATEGORY);
				return result.right().value();
			}
		}

		return TitanOperationStatus.OK;
	}

	protected StorageOperationStatus associateArtifactsToComponent(NodeTypeEnum nodeType, ComponentMetadataData componentData, Map<String, ArtifactDefinition> artifacts) {

		if (artifacts != null) {
			for (Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {

				ArtifactDefinition artifactDefinition = entry.getValue();
				Either<ArtifactDefinition, StorageOperationStatus> addArifactToResource = Either.left(artifactDefinition);
				addArifactToResource = artifactOperation.addArifactToComponent(artifactDefinition, (String) componentData.getUniqueId(), nodeType, false, true);
				if (addArifactToResource.isRight()) {
					return addArifactToResource.right().value();
				}
			}
		}
		return StorageOperationStatus.OK;

	}

	protected Either<Boolean, StorageOperationStatus> validateResourceNameUniqueness(String name, Map<String, Object> hasProps, Map<String, Object> hasNotProps, TitanGenericDao titanGenericDao) {
		if (hasProps == null) {
			hasProps = new HashMap<String, Object>();
		}
		String normalizedName = ValidationUtils.normaliseComponentName(name);
		hasProps.put(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), normalizedName);

		Either<List<ResourceMetadataData>, TitanOperationStatus> resources = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, hasProps, hasNotProps, ResourceMetadataData.class);
		if (resources.isRight() && resources.right().value() != TitanOperationStatus.NOT_FOUND) {
			log.debug("failed to get resources from graph with property name: {}", name);
			return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resources.right().value()));
		}
		List<ResourceMetadataData> resourceList = (resources.isLeft() ? resources.left().value() : null);
		if (resourceList != null && resourceList.size() > 0) {
			if (log.isDebugEnabled()) {
				StringBuilder builder = new StringBuilder();
				for (ResourceMetadataData resourceData : resourceList) {
					builder.append(resourceData.getUniqueId() + "|");
				}
				log.debug("resources  with property name:{} exists in graph. found {}",name, builder.toString());
			}
			return Either.left(false);
		} else {
			log.debug("resources  with property name:{} does not exists in graph", name);
			return Either.left(true);
		}

	}
	
	protected Either<Boolean, StorageOperationStatus> validateServiceNameUniqueness(String name, TitanGenericDao titanGenericDao) {
		Map<String, Object> properties = new HashMap<>();
		String normalizedName = ValidationUtils.normaliseComponentName(name);
		properties.put(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), normalizedName);

		Either<List<ServiceMetadataData>, TitanOperationStatus> services = titanGenericDao.getByCriteria(NodeTypeEnum.Service, properties, ServiceMetadataData.class);
		if (services.isRight() && services.right().value() != TitanOperationStatus.NOT_FOUND) {
			log.debug("failed to get services from graph with property name: {}" , name);
			return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(services.right().value()));
		}
		List<ServiceMetadataData> serviceList = (services.isLeft() ? services.left().value() : null);
		if (serviceList != null && serviceList.size() > 0) {
			if (log.isDebugEnabled()) {
				StringBuilder builder = new StringBuilder();
				for (ServiceMetadataData serviceData : serviceList) {
					builder.append(serviceData.getUniqueId() + "|");
				}
				log.debug("Service with property name:{} exists in graph. found {}" , name, builder.toString());
			}

			return Either.left(false);
		} else {
			log.debug("Service  with property name:{} does not exists in graph", name);
			return Either.left(true);
		}
	}
	
	protected Either<Boolean, StorageOperationStatus> validateToscaResourceNameUniqueness(String name, TitanGenericDao titanGenericDao) {
		Map<String, Object> properties = new HashMap<>();

		properties.put(GraphPropertiesDictionary.TOSCA_RESOURCE_NAME.getProperty(), name);

		Either<List<ResourceMetadataData>, TitanOperationStatus> resources = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, properties, ResourceMetadataData.class);
		if (resources.isRight() && resources.right().value() != TitanOperationStatus.NOT_FOUND) {
			log.debug("failed to get resources from graph with property name: {}" , name);
			return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resources.right().value()));
		}
		List<ResourceMetadataData> resourceList = (resources.isLeft() ? resources.left().value() : null);
		if (resourceList != null && resourceList.size() > 0) {
			if (log.isDebugEnabled()) {
				StringBuilder builder = new StringBuilder();
				for (ResourceMetadataData resourceData : resourceList) {
					builder.append(resourceData.getUniqueId() + "|");
				}
				log.debug("resources  with property name:{} exists in graph. found {}" , name, builder.toString());
			}
			return Either.left(false);
		} else {
			log.debug("resources  with property name:{} does not exists in graph", name);
			return Either.left(true);
		}

	}

	protected Either<Boolean, StorageOperationStatus> validateComponentNameUniqueness(String name, TitanGenericDao titanGenericDao, NodeTypeEnum type) {
		Map<String, Object> properties = new HashMap<>();
		String normalizedName = ValidationUtils.normaliseComponentName(name);
		properties.put(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), normalizedName);

		Either<List<ComponentMetadataData>, TitanOperationStatus> components = titanGenericDao.getByCriteria(type, properties, ComponentMetadataData.class);
		if (components.isRight() && components.right().value() != TitanOperationStatus.NOT_FOUND) {
			log.debug("failed to get components from graph with property name: {}" , name);
			return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(components.right().value()));
		}
		List<ComponentMetadataData> componentList = (components.isLeft() ? components.left().value() : null);
		if (componentList != null && componentList.size() > 0) {
			if (log.isDebugEnabled()) {
				StringBuilder builder = new StringBuilder();
				for (ComponentMetadataData componentData : componentList) {
					builder.append(componentData.getUniqueId() + "|");
				}
				log.debug("Component with property name:{} exists in graph. found {}" , name, builder.toString());
			}

			return Either.left(false);
		} else {
			log.debug("Component with property name:{} does not exists in graph", name);
			return Either.left(true);
		}
	}

	protected StorageOperationStatus setArtifactFromGraph(String uniqueId, Component component, NodeTypeEnum type, IArtifactOperation artifactOperation) {
		StorageOperationStatus result = StorageOperationStatus.OK;
		Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts = artifactOperation.getArtifacts(uniqueId, type, true);
		if (artifacts.isRight()) {
			result = artifacts.right().value();
		} else {
			// component.setArtifacts(artifacts.left().value());
			createSpecificArtifactList(component, artifacts.left().value());
		}
		return result;
	}

	protected Component createSpecificArtifactList(Component component, Map<String, ArtifactDefinition> artifacts) {

		if (artifacts != null) {
			Map<String, ArtifactDefinition> deploymentArtifacts = new HashMap<>();
			Map<String, ArtifactDefinition> serviceApiArtifacts = new HashMap<>();
			Map<String, ArtifactDefinition> toscaArtifacts = new HashMap<>();

			Set<Entry<String, ArtifactDefinition>> specificet = new HashSet<>();

			for (Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
				ArtifactDefinition artifact = entry.getValue();
				ArtifactGroupTypeEnum artifactGroupType = artifact.getArtifactGroupType();
				if (artifactGroupType == null) {
					artifactGroupType = ArtifactGroupTypeEnum.INFORMATIONAL;
				}

				switch (artifactGroupType) {
				case DEPLOYMENT:
					deploymentArtifacts.put(artifact.getArtifactLabel(), artifact);
					specificet.add(entry);
					break;
				case SERVICE_API:
					serviceApiArtifacts.put(artifact.getArtifactLabel(), artifact);
					specificet.add(entry);
					break;
				case TOSCA:
					toscaArtifacts.put(artifact.getArtifactLabel(), artifact);
					specificet.add(entry);
					break;
				default:
					break;
				}

			}
			artifacts.entrySet().removeAll(specificet);

			component.setSpecificComponetTypeArtifacts(serviceApiArtifacts);
			component.setDeploymentArtifacts(deploymentArtifacts);
			component.setToscaArtifacts(toscaArtifacts);
			component.setArtifacts(artifacts);
		}
		return component;
	}

	private <T, S extends ComponentMetadataData> Either<List<T>, StorageOperationStatus> collectComponents(TitanGraph graph, NodeTypeEnum neededType, String categoryUid, NodeTypeEnum categoryType, Class<S> clazz, ResourceTypeEnum resourceType) {
		List<T> components = new ArrayList<>();
		Either<List<ImmutablePair<S, GraphEdge>>, TitanOperationStatus> parentNodes = titanGenericDao.getParentNodes(UniqueIdBuilder.getKeyByNodeType(categoryType), categoryUid, GraphEdgeLabels.CATEGORY, neededType, clazz);
		if (parentNodes.isLeft()) {
			for (ImmutablePair<S, GraphEdge> component : parentNodes.left().value()) {
				ComponentMetadataDataDefinition componentData = component.getLeft().getMetadataDataDefinition();
				Boolean isHighest = componentData.isHighestVersion();
				boolean isMatchingResourceType = isMatchingByResourceType(neededType, resourceType, componentData);
				
				if (isHighest && isMatchingResourceType) {
					Either<T, StorageOperationStatus> result = getLightComponent(componentData.getUniqueId(), true);
					if (result.isRight()) {
						return Either.right(result.right().value());
					}
					components.add(result.left().value());
				}
			}
		}
		return Either.left(components);
	}

	private boolean isMatchingByResourceType(NodeTypeEnum componentType, ResourceTypeEnum resourceType,
			ComponentMetadataDataDefinition componentData) {

		boolean isMatching;
		if (componentType == NodeTypeEnum.Resource) {
			if (resourceType == null) {
				isMatching = true;
			} else {
				isMatching = resourceType == ((ResourceMetadataDataDefinition)componentData).getResourceType();
			}
		} else {
			isMatching = true;
		}
		return isMatching;
	}

	protected <T, S extends ComponentMetadataData> Either<List<T>, StorageOperationStatus> fetchByCategoryOrSubCategoryUid(String categoryUid, NodeTypeEnum categoryType, String categoryLabel, NodeTypeEnum neededType, boolean inTransaction,
			Class<S> clazz, ResourceTypeEnum resourceType) {
		try {
			Either<TitanGraph, TitanOperationStatus> graph = titanGenericDao.getGraph();
			if (graph.isRight()) {
				return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graph.right().value()));

			}
			return collectComponents(graph.left().value(), neededType, categoryUid, categoryType, clazz, resourceType);

		} finally {
			if (false == inTransaction) {
				titanGenericDao.commit();
			}
		}
	}

	protected <T, S extends ComponentMetadataData> Either<List<T>, StorageOperationStatus> fetchByCategoryOrSubCategoryName(String categoryName, NodeTypeEnum categoryType, String categoryLabel, NodeTypeEnum neededType, boolean inTransaction,
			Class<S> clazz, ResourceTypeEnum resourceType) {
		List<T> components = new ArrayList<>();
		try {
			Class categoryClazz = categoryType == NodeTypeEnum.ServiceNewCategory ? CategoryData.class : SubCategoryData.class;
			Map<String, Object> props = new HashMap<String, Object>();
			props.put(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), ValidationUtils.normalizeCategoryName4Uniqueness(categoryName));
			Either<List<GraphNode>, TitanOperationStatus> getCategory = titanGenericDao.getByCriteria(categoryType, props, categoryClazz);
			if (getCategory.isRight()) {
				return Either.right(StorageOperationStatus.CATEGORY_NOT_FOUND);
			}
			Either<TitanGraph, TitanOperationStatus> graph = titanGenericDao.getGraph();
			if (graph.isRight()) {
				return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graph.right().value()));

			}
			for (GraphNode category : getCategory.left().value()) {
				Either<List<T>, StorageOperationStatus> result = collectComponents(graph.left().value(), neededType, (String) category.getUniqueId(), categoryType, clazz, resourceType);
				if (result.isRight()) {
					return result;
				}
				components.addAll(result.left().value());
			}

			return Either.left(components);
		} finally {
			if (false == inTransaction) {
				titanGenericDao.commit();
			}
		}
	}

	<T> Either<List<T>, StorageOperationStatus> getFilteredComponents(Map<FilterKeyEnum, String> filters, boolean inTransaction, NodeTypeEnum neededType) {
		return null;
	}

	protected Either<List<Component>, StorageOperationStatus> getFollowedComponent(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates, boolean inTransaction, TitanGenericDao titanGenericDao,
			NodeTypeEnum neededType) {

		Either<List<Component>, StorageOperationStatus> result = null;

		try {
			Either<TitanGraph, TitanOperationStatus> graph = titanGenericDao.getGraph();
			if (graph.isRight()) {
				result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graph.right().value()));
				return result;
			}
			Iterable<TitanVertex> users;

			if (userId == null) {
				// get all users by label
				// for Tester and Admin retrieve all users

				// users =
				// graph.left().value().getVertices(GraphPropertiesDictionary.LABEL.getProperty(),
				// NodeTypeEnum.User.getName());
				users = graph.left().value().query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.User.getName()).vertices();

			} else {
				// for Designer retrieve specific user
				String key = UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User);
				users = graph.left().value().query().has(key, userId).vertices();
			}
			Iterator<TitanVertex> userIterator = users.iterator();

			List<Component> components = new ArrayList<>();
			while (userIterator.hasNext()) {
				Vertex vertexUser = userIterator.next();

				// get all resource with current state
				Iterator<Edge> iterator = vertexUser.edges(Direction.OUT, GraphEdgeLabels.STATE.getProperty());

				List<Component> componentsPerUser = fetchComponents(lifecycleStates, iterator, neededType, inTransaction);

				HashSet<String> ids = new HashSet<String>();

				if (componentsPerUser != null) {
					for (Component comp : componentsPerUser) {
						ids.add(comp.getUniqueId());
						components.add(comp);
					}
				}

				if (lastStateStates != null && !lastStateStates.isEmpty()) {
					// get all resource with last state
					iterator = vertexUser.edges(Direction.OUT, GraphEdgeLabels.LAST_STATE.getProperty());
					boolean isFirst;
					componentsPerUser = fetchComponents(lastStateStates, iterator, neededType, inTransaction);
					if (componentsPerUser != null) {
						for (Component comp : componentsPerUser) {
							isFirst = true;

							if (ids.contains(comp.getUniqueId())) {
								isFirst = false;
							}
							if (isFirst == true) {
								components.add(comp);
							}

						}
					}
				}

			} // whlile users

			result = Either.left(components);
			return result;

		} finally {
			if (false == inTransaction) {
				if (result == null || result.isRight()) {
					titanGenericDao.rollback();
				} else {
					titanGenericDao.commit();
				}
			}
		}

	}

	private List<Component> fetchComponents(Set<LifecycleStateEnum> lifecycleStates, Iterator<Edge> iterator, NodeTypeEnum neededType, boolean inTransaction) {
		List<Component> components = new ArrayList<>();
		while (iterator.hasNext()) {
			Edge edge = iterator.next();

			String stateStr = edge.value(GraphEdgePropertiesDictionary.STATE.getProperty());
			LifecycleStateEnum state = LifecycleStateEnum.findState(stateStr);
			if (state == null) {
				log.debug("not supported STATE for element  {}" , stateStr);
				continue;
			}
			if (lifecycleStates != null && lifecycleStates.contains(state)) {
				Vertex vertexComponent = edge.inVertex();

				Boolean isHighest = vertexComponent.value(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty());
				if (isHighest) {

					String nodeTypeStr = vertexComponent.value(GraphPropertiesDictionary.LABEL.getProperty());
					// get only latest versions
					NodeTypeEnum nodeType = NodeTypeEnum.getByName(nodeTypeStr);

					if (nodeType == null) {
						log.debug("missing node label for vertex {}", vertexComponent);
						continue;
					}

					if (neededType.equals(nodeType)) {
						switch (nodeType) {
						case Service:
							handleNode(components, vertexComponent, nodeType, inTransaction);
							break;
						case Resource:
							Boolean isAbtract = vertexComponent.value(GraphPropertiesDictionary.IS_ABSTRACT.getProperty());
							if (false == isAbtract) {
								handleNode(components, vertexComponent, nodeType, inTransaction);
							} // if not abstract
							break;
						case Product:
							handleNode(components, vertexComponent, nodeType, inTransaction);
							break;
						default:
							log.debug("not supported node type {}", nodeType);
							break;
						}// case
					} // needed type
				}
			} // if
		} // while resources
		return components;
	}

	protected <T> void handleNode(List<T> components, Vertex vertexComponent, NodeTypeEnum nodeType, boolean inTransaction) {
		String id;

		id = vertexComponent.value(UniqueIdBuilder.getKeyByNodeType(nodeType));
		if (id != null) {
			Either<T, StorageOperationStatus> component = getLightComponent(id, inTransaction);
			if (component.isRight()) {
				log.debug("Failed to get component for id =  {}  error : {} skip resource", id, component.right().value());
			} else {
				components.add(component.left().value());
			}
		} else {

			Map<String, Object> properties = this.titanGenericDao.getProperties(vertexComponent);
			log.debug("missing resource unique id for node with properties {}", properties);
		}
	}

	/**
	 * 
	 * @param component
	 * @param inTransaction
	 * @param titanGenericDao
	 * @param clazz
	 * @return
	 */
	public <T> Either<T, StorageOperationStatus> updateComponent(Component component, boolean inTransaction, TitanGenericDao titanGenericDao, Class<T> clazz, NodeTypeEnum type) {

		ComponentParametersView componentParametersView = new ComponentParametersView();
		return updateComponentFilterResult(component, inTransaction, titanGenericDao, clazz, type, componentParametersView);

	}

	private Either<ArtifactData, StorageOperationStatus> generateAndUpdateToscaFileName(String componentType, String componentName, String componentId, NodeTypeEnum type, ArtifactDefinition artifactInfo) {
		Map<String, Object> getConfig = (Map<String, Object>) ConfigurationManager.getConfigurationManager().getConfiguration().getToscaArtifacts().entrySet().stream()
				.filter(p -> p.getKey().equalsIgnoreCase(artifactInfo.getArtifactLabel()))
				.findAny()
				.get()
				.getValue();
		artifactInfo.setArtifactName(componentType + "-" + componentName + getConfig.get("artifactName"));
		return artifactOperation.updateToscaArtifactNameOnGraph(artifactInfo, artifactInfo.getUniqueId(), type, componentId);
	}

	protected StorageOperationStatus moveCategoryEdge(Component component, ComponentMetadataData componentData, CategoryDefinition newCategory, NodeTypeEnum type) {

		StorageOperationStatus result = StorageOperationStatus.OK;

		GraphRelation categoryRelation = new GraphRelation();
		categoryRelation.setType(GraphEdgeLabels.CATEGORY.getProperty());
		RelationEndPoint relationEndPoint = new RelationEndPoint(type, UniqueIdBuilder.getKeyByNodeType(type), component.getUniqueId());
		categoryRelation.setFrom(relationEndPoint);
		Either<GraphRelation, TitanOperationStatus> deleteOutgoingRelation = titanGenericDao.deleteOutgoingRelation(categoryRelation);
		if (deleteOutgoingRelation.isRight()) {
			log.error("Failed to delete category from component {}. Edge type is {}", componentData.getUniqueId(), GraphEdgeLabels.CATEGORY);
			result = DaoStatusConverter.convertTitanStatusToStorageStatus(deleteOutgoingRelation.right().value());
			return result;
		}

		log.debug("After removing edge from graph {}", deleteOutgoingRelation);

		NodeTypeEnum categoryType;
		if (NodeTypeEnum.Service.name().equalsIgnoreCase(type.name())) {
			categoryType = NodeTypeEnum.ServiceCategory;
		} else {
			categoryType = NodeTypeEnum.ResourceCategory;
		}
		Either<CategoryData, StorageOperationStatus> categoryResult = elementOperation.getNewCategoryData(newCategory.getName(), NodeTypeEnum.ServiceNewCategory, CategoryData.class);
		if (categoryResult.isRight()) {
			StorageOperationStatus status = categoryResult.right().value();
			log.error("Cannot find category {} in the graph. status is {}", newCategory.getName(), status);
			return status;
		}

		CategoryData categoryData = categoryResult.left().value();
		Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(componentData, categoryData, GraphEdgeLabels.CATEGORY, null);
		log.debug("After associating category {} to component {}. Edge type is {}", categoryData, componentData.getUniqueId(), GraphEdgeLabels.CATEGORY);
		if (createRelation.isRight()) {
			log.error("Failed to associate category {} to component {}. Edge type is {}", categoryData, componentData.getUniqueId(), GraphEdgeLabels.CATEGORY);
			result = DaoStatusConverter.convertTitanStatusToStorageStatus(createRelation.right().value());
			return result;
		}

		return result;
	}

	private StorageOperationStatus moveLastModifierEdge(Component component, ComponentMetadataData componentData, UserData modifierUserData, NodeTypeEnum type) {

		StorageOperationStatus result = StorageOperationStatus.OK;

		GraphRelation lastModifierRelation = new GraphRelation();
		lastModifierRelation.setType(GraphEdgeLabels.LAST_MODIFIER.getProperty());
		RelationEndPoint relationEndPoint = new RelationEndPoint(type, UniqueIdBuilder.getKeyByNodeType(type), component.getUniqueId());
		lastModifierRelation.setTo(relationEndPoint);
		Either<GraphRelation, TitanOperationStatus> deleteIncomingRelation = titanGenericDao.deleteIncomingRelation(lastModifierRelation);
		if (deleteIncomingRelation.isRight()) {
			log.error("Failed to delete user from component {}. Edge type is {}", componentData.getUniqueId(), GraphEdgeLabels.LAST_MODIFIER);
			result = DaoStatusConverter.convertTitanStatusToStorageStatus(deleteIncomingRelation.right().value());
			return result;
		}

		Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(modifierUserData, componentData, GraphEdgeLabels.LAST_MODIFIER, null);
		log.debug("After associating user {} to component {}. Edge type is {}", modifierUserData, componentData.getUniqueId(), GraphEdgeLabels.LAST_MODIFIER);
		if (createRelation.isRight()) {
			log.error("Failed to associate user {} to component {}. Edge type is {}", modifierUserData, componentData.getUniqueId(), GraphEdgeLabels.LAST_MODIFIER);
			result = DaoStatusConverter.convertTitanStatusToStorageStatus(createRelation.right().value());
			return result;
		}
		return result;
	}

	protected abstract ComponentMetadataData getMetaDataFromComponent(Component component);

	public abstract <T> Either<T, StorageOperationStatus> getComponent(String id, boolean inTransaction);

	public abstract <T> Either<T, StorageOperationStatus> getComponent(String id, ComponentParametersView componentParametersView, boolean inTrasnaction);

	protected abstract <T> Either<T, StorageOperationStatus> getComponentByNameAndVersion(String name, String version, Map<String, Object> additionalParams, boolean inTransaction);

	public abstract <T> Either<T, StorageOperationStatus> getLightComponent(String id, boolean inTransaction);

	public abstract <T> Either<List<T>, StorageOperationStatus> getFilteredComponents(Map<FilterKeyEnum, String> filters, boolean inTransaction);

	abstract Component convertComponentMetadataDataToComponent(ComponentMetadataData componentMetadataData);

	abstract TitanOperationStatus setComponentCategoriesFromGraph(Component component);

	protected abstract Either<Component, StorageOperationStatus> getMetadataComponent(String id, boolean inTransaction);

	protected abstract <T> Either<T, StorageOperationStatus> updateComponent(T component, boolean inTransaction);

	protected abstract <T> Either<T, StorageOperationStatus> updateComponentFilterResult(T component, boolean inTransaction, ComponentParametersView filterParametersView);

	public abstract Either<Component, StorageOperationStatus> deleteComponent(String id, boolean inTransaction);

	public <T> Either<T, StorageOperationStatus> cloneComponent(T other, String version, boolean inTransaction) {
		return cloneComponent(other, version, null, inTransaction);
	}

	public abstract <T> Either<T, StorageOperationStatus> cloneComponent(T other, String version, LifecycleStateEnum targetLifecycle, boolean inTransaction);

	public abstract Component getDefaultComponent();

	public abstract boolean isComponentExist(String componentId);

	public abstract Either<Boolean, StorageOperationStatus> validateComponentNameExists(String componentName);

	public abstract Either<Boolean, StorageOperationStatus> isComponentInUse(String componentId);

	protected Either<Boolean, StorageOperationStatus> isComponentInUse(String componentId, NodeTypeEnum nodeType) {

		Either<GraphRelation, TitanOperationStatus> relationByCriteria = titanGenericDao.getIncomingRelationByCriteria(new UniqueIdData(nodeType, componentId), GraphEdgeLabels.INSTANCE_OF, null);
		if (relationByCriteria.isRight() && !relationByCriteria.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
			log.debug("failed to check relations for component node. id = {}, type = {}, error = {}", componentId, nodeType, relationByCriteria.right().value().name());
			return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(relationByCriteria.right().value()));
		}

		if (relationByCriteria.isLeft()) {
			// component is in use
			return Either.left(true);
		} else {
			return Either.left(false);
		}

	}

	public abstract Either<List<String>, StorageOperationStatus> getAllComponentsMarkedForDeletion();

	protected Either<List<String>, StorageOperationStatus> getAllComponentsMarkedForDeletion(NodeTypeEnum nodeType) {

		List<String> componentIdsToDelete = new ArrayList<String>();
		// get all components marked for delete
		Map<String, Object> props = new HashMap<String, Object>();
		props.put(GraphPropertiesDictionary.IS_DELETED.getProperty(), true);

		Either<List<ComponentMetadataData>, TitanOperationStatus> componentsToDelete = titanGenericDao.getByCriteria(nodeType, props, ComponentMetadataData.class);

		if (componentsToDelete.isRight()) {
			TitanOperationStatus error = componentsToDelete.right().value();
			if (error.equals(TitanOperationStatus.NOT_FOUND)) {
				log.trace("no components to delete");
				return Either.left(componentIdsToDelete);
			} else {
				log.info("failed to find components to delete. error : {}", error.name());
				return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(error));
			}

		}
		for (ComponentMetadataData resourceData : componentsToDelete.left().value()) {
			componentIdsToDelete.add(resourceData.getMetadataDataDefinition().getUniqueId());
		}
		return Either.left(componentIdsToDelete);
	}

	protected <T extends GraphNode> Either<List<T>, TitanOperationStatus> __getLastVersion(NodeTypeEnum type, Map<String, Object> props, Class<T> clazz) {
		try {

			Either<TitanGraph, TitanOperationStatus> graph = titanGenericDao.getGraph();
			if (graph.isRight()) {
				return Either.right(graph.right().value());
			}

			TitanGraph tGraph = graph.left().value();
			TitanGraphQuery<? extends TitanGraphQuery> query = tGraph.query();
			query = query.has(GraphPropertiesDictionary.LABEL.getProperty(), type.getName());

			if (props != null && !props.isEmpty()) {
				for (Map.Entry<String, Object> entry : props.entrySet()) {
					query = query.hasNot(entry.getKey(), entry.getValue());
				}
			}
			query.has(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true);

			Iterable<TitanVertex> vertices = query.vertices();

			if (vertices == null) {
				return Either.right(TitanOperationStatus.NOT_FOUND);
			}

			Iterator<TitanVertex> iterator = vertices.iterator();
			List<T> result = new ArrayList<T>();

			while (iterator.hasNext()) {
				Vertex vertex = iterator.next();

				Map<String, Object> newProp = titanGenericDao.getProperties(vertex);
				T element = GraphElementFactory.createElement(type.getName(), GraphElementTypeEnum.Node, newProp, clazz);
				result.add(element);
			}
			if (result.size() == 0) {
				return Either.right(TitanOperationStatus.NOT_FOUND);
			}
			log.debug("No nodes in graph for criteria : from type = {} and properties = {}", type, props);
			return Either.left(result);
		} catch (Exception e) {
			log.debug("Failed get by criteria for type = {} and properties = {}", type, props, e);
			return Either.right(TitanGraphClient.handleTitanException(e));
		}
	}

	protected <T extends GraphNode> Either<List<T>, TitanOperationStatus> getLastVersion(NodeTypeEnum type, Map<String, Object> hasNotProps, Class<T> clazz) {
		return getLastVersion(type, null, hasNotProps, clazz);
	}

	protected <T extends GraphNode> Either<List<T>, TitanOperationStatus> getLastVersion(NodeTypeEnum type, Map<String, Object> hasProps, Map<String, Object> hasNotProps, Class<T> clazz) {

		Map<String, Object> props = new HashMap<>();

		if (hasProps != null) {
			props.putAll(hasProps);
		}
		props.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true);

		Either<List<T>, TitanOperationStatus> byCriteria = titanGenericDao.getByCriteria(type, props, hasNotProps, clazz);

		return byCriteria;

	}

	public <T, S extends GraphNode> Either<Set<T>, StorageOperationStatus> getComponentCatalogData(NodeTypeEnum type, Map<String, Object> propertiesToMatch, Class<T> clazz1, Class<S> clazz2, boolean inTransaction) {
		log.debug("Start getComponentCatalogData for type: {}", type.name());
		Set<T> result = new HashSet<T>();
		Either<List<S>, TitanOperationStatus> lastVersionNodes = getLastVersion(type, propertiesToMatch, clazz2);
		Either<Set<T>, StorageOperationStatus> last = retrieveComponentsFromNodes(lastVersionNodes, inTransaction);
		if (last.isLeft() && last.left().value() != null) {
			result.addAll(last.left().value());
		}
		if (type == NodeTypeEnum.Resource) {
			propertiesToMatch.put(GraphPropertiesDictionary.IS_ABSTRACT.getProperty(), false);
		}
		Either<List<S>, TitanOperationStatus> componentsNodes = titanGenericDao.getByCriteria(type, propertiesToMatch, clazz2);
		Either<Set<T>, StorageOperationStatus> certified = retrieveComponentsFromNodes(componentsNodes, inTransaction);
		if (certified.isLeft() && certified.left().value() != null) {
			result.addAll(certified.left().value());
		}
		return Either.left(result);

	}

	protected <T, S extends GraphNode> Either<Set<T>, StorageOperationStatus> retrieveComponentsFromNodes(Either<List<S>, TitanOperationStatus> componentsNodes, boolean inTransaction) {
		Set<T> result = new HashSet<T>();
		if (componentsNodes.isRight()) {
			// in case of NOT_FOUND from Titan client return to UI empty list
			if (componentsNodes.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
				log.debug("No components were found");
			} else {
				return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(componentsNodes.right().value()));
			}
		} else {
			List<S> componentDataList = componentsNodes.left().value();
			for (S componentData : componentDataList) {
				// Either<T, StorageOperationStatus> component =
				// getComponent((String) componentData.getUniqueId(),
				// inTransaction);
				Either<T, StorageOperationStatus> component = getLightComponent((String) componentData.getUniqueId(), inTransaction);
				if (component.isRight()) {
					log.debug("Failed to get component for id =  {}  error : {} skip resource", componentData.getUniqueId(), component.right().value());
					// return Either.right(service.right().value());
				} else {
					result.add(component.left().value());
				}
			}
		}
		return Either.left(result);
	}

	protected StorageOperationStatus removeArtifactsFromComponent(Component component, NodeTypeEnum componentType) {

		String componentId = component.getUniqueId();
		// Map<String, ArtifactDefinition> artifacts = component.getArtifacts();
		Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsRes = artifactOperation.getArtifacts(componentId, componentType, true);
		if (artifactsRes.isRight() && !artifactsRes.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
			return artifactsRes.right().value();
		}
		if (artifactsRes.isLeft() && artifactsRes.left().value() != null) {
			Map<String, ArtifactDefinition> artifacts = artifactsRes.left().value();
			for (Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {

				ArtifactDefinition artifactDefinition = entry.getValue();
				Either<ArtifactDefinition, StorageOperationStatus> removeArifactFromResource = artifactOperation.removeArifactFromResource(componentId, artifactDefinition.getUniqueId(), componentType, true, true);
				if (removeArifactFromResource.isRight()) {
					return removeArifactFromResource.right().value();
				}
			}
		}
		return StorageOperationStatus.OK;
	}

	public Either<List<Component>, StorageOperationStatus> getTesterFollowedComponent(String userId, Set<LifecycleStateEnum> lifecycleStates, boolean inTransaction, NodeTypeEnum neededType) {
		List<Component> resList = new ArrayList<>();
		Either<List<Component>, StorageOperationStatus> rip = getFollowedComponent(userId, lifecycleStates, null, inTransaction, titanGenericDao, neededType);
		if (rip.isLeft()) {
			List<Component> ripRes = rip.left().value();
			if (ripRes != null && !ripRes.isEmpty()) {
				resList.addAll(ripRes);
			}
			Set<LifecycleStateEnum> rfcState = new HashSet<>();
			rfcState.add(LifecycleStateEnum.READY_FOR_CERTIFICATION);
			Either<List<Component>, StorageOperationStatus> rfc = getFollowedComponent(null, rfcState, null, inTransaction, titanGenericDao, neededType);
			if (rfc.isLeft()) {
				List<Component> rfcRes = rfc.left().value();
				if (rfcRes != null && !rfcRes.isEmpty()) {
					resList.addAll(rfcRes);
				}
			} else {
				return Either.right(rfc.right().value());
			}

		} else {
			return Either.right(rip.right().value());
		}
		return Either.left(resList);

	}

	/**
	 * generate UUID only for case that version is "XX.01" - (start new version)
	 * 
	 * @param component
	 */
	protected void generateUUID(Component component) {
		String version = component.getVersion();
		if (uuidNewVersion.matcher(version).matches()) {
			UUID uuid = UUID.randomUUID();
			component.getComponentMetadataDefinition().getMetadataDataDefinition().setUUID(uuid.toString());
			MDC.put("serviceInstanceID", uuid.toString());
		}
	}

	protected <T extends GraphNode> Either<Map<String, String>, TitanOperationStatus> getVersionList(NodeTypeEnum type, String version, Component component, Class<T> clazz) {
		return getVersionList(type, version, component.getUUID(), component.getSystemName(), clazz);
	}

	protected <T extends GraphNode> Either<Map<String, String>, TitanOperationStatus> getVersionList(NodeTypeEnum type, String version, String uuid, String systemName, Class<T> clazz) {
		Map<String, Object> props = new HashMap<String, Object>();
		Map<String, Object> hasNotProps = new HashMap<String, Object>();

		if (version.startsWith("0")) {
			props.put(GraphPropertiesDictionary.UUID.getProperty(), uuid);
		} else {
			props.put(GraphPropertiesDictionary.SYSTEM_NAME.getProperty(), systemName);
		}
		hasNotProps.put(GraphPropertiesDictionary.IS_DELETED.getProperty(), true);
		Either<List<T>, TitanOperationStatus> result = titanGenericDao.getByCriteria(type, props, hasNotProps, clazz);

		Map<String, String> versionMap = new HashMap<String, String>();
		if (result.isRight()) {
			if (!result.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
				return Either.right(result.right().value());
			}

		} else {
			switch (type) {
			case Resource:
				List<ResourceMetadataData> components = (List<ResourceMetadataData>) result.left().value();
				for (ResourceMetadataData data : components) {
					versionMap.put(data.getMetadataDataDefinition().getVersion(), (String) data.getUniqueId());
				}
				break;
			case Service:
				List<ServiceMetadataData> componentsS = (List<ServiceMetadataData>) result.left().value();
				for (ServiceMetadataData data : componentsS) {
					versionMap.put(data.getMetadataDataDefinition().getVersion(), (String) data.getUniqueId());
				}
				break;
			case Product:
				List<ProductMetadataData> componentsP = (List<ProductMetadataData>) result.left().value();
				for (ProductMetadataData data : componentsP) {
					versionMap.put(data.getMetadataDataDefinition().getVersion(), (String) data.getUniqueId());
				}
				break;
			default:
				break;
			}
		}

		return Either.left(versionMap);
	}

	protected StorageOperationStatus deleteAdditionalInformation(NodeTypeEnum nodeType, String componentId) {

		Either<AdditionalInformationDefinition, StorageOperationStatus> deleteRes = additionalInformationOperation.deleteAllAdditionalInformationParameters(nodeType, componentId, true);

		if (deleteRes.isRight()) {
			StorageOperationStatus status = deleteRes.right().value();
			return status;
		}

		return StorageOperationStatus.OK;

	}

	protected StorageOperationStatus addAdditionalInformation(NodeTypeEnum nodeType, String componentId, AdditionalInformationDefinition informationDefinition) {

		Either<AdditionalInformationDefinition, TitanOperationStatus> status = additionalInformationOperation.addAdditionalInformationNode(nodeType, componentId, informationDefinition);

		if (status.isRight()) {
			TitanOperationStatus titanStatus = status.right().value();
			return DaoStatusConverter.convertTitanStatusToStorageStatus(titanStatus);
		}

		log.trace("After adding additional information to component {}. Result is {}" , componentId ,status.left().value());

		return StorageOperationStatus.OK;

	}

	protected StorageOperationStatus addAdditionalInformation(NodeTypeEnum nodeType, String componentId, AdditionalInformationDefinition informationDefinition, TitanVertex metadataVertex) {

		TitanOperationStatus status = additionalInformationOperation.addAdditionalInformationNode(nodeType, componentId, informationDefinition, metadataVertex);
		log.trace("After adding additional information to component {}. Result is {}", componentId, status);

		if (!status.equals(TitanOperationStatus.OK)) {
			return DaoStatusConverter.convertTitanStatusToStorageStatus(status);
		}

		return StorageOperationStatus.OK;

	}

	public Either<List<ArtifactDefinition>, StorageOperationStatus> getComponentArtifactsForDelete(String parentId, NodeTypeEnum parentType, boolean inTransacton) {
		List<ArtifactDefinition> artifacts = new ArrayList<ArtifactDefinition>();
		Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsResponse = artifactOperation.getArtifacts(parentId, parentType, inTransacton);
		if (artifactsResponse.isRight()) {
			if (!artifactsResponse.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
				log.debug("failed to retrieve artifacts for {} {}", parentType, parentId);
				return Either.right(artifactsResponse.right().value());
			}
		} else {
			artifacts.addAll(artifactsResponse.left().value().values());
		}

		if (NodeTypeEnum.Resource.equals(parentType)) {
			Either<List<ArtifactDefinition>, StorageOperationStatus> interfacesArtifactsForResource = getAdditionalArtifacts(parentId, false, true);
			if (artifactsResponse.isRight() && !interfacesArtifactsForResource.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
				log.debug("failed to retrieve interface artifacts for {} {}", parentType, parentId);
				return Either.right(interfacesArtifactsForResource.right().value());
			} else if (artifactsResponse.isLeft()) {
				artifacts.addAll(interfacesArtifactsForResource.left().value());
			}
		}
		return Either.left(artifacts);
	}

	protected void addComponentInternalFields(ComponentMetadataData componentMetadataData) {
		org.openecomp.sdc.be.datatypes.components.ComponentMetadataDataDefinition metadataDataDefinition = componentMetadataData.getMetadataDataDefinition();
		Long creationDate = metadataDataDefinition.getCreationDate();

		long currentDate = System.currentTimeMillis();
		if (creationDate == null) {
			metadataDataDefinition.setCreationDate(currentDate);
		}
		metadataDataDefinition.setLastUpdateDate(currentDate);

		String lifecycleStateEnum = metadataDataDefinition.getState();
		if (lifecycleStateEnum == null) {
			metadataDataDefinition.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name());
		}
		String componentUniqueId = UniqueIdBuilder.buildComponentUniqueId();
		metadataDataDefinition.setUniqueId(componentUniqueId);
		metadataDataDefinition.setHighestVersion(true);
	}

	protected StorageOperationStatus createTagsForComponent(Component component) {
		List<String> tags = component.getTags();
		if (tags != null && false == tags.isEmpty()) {
			Either<List<TagData>, StorageOperationStatus> tagsResult = createNewTagsList(tags);

			if (tagsResult == null) {
				log.debug("tagsResult is null");
				return StorageOperationStatus.GENERAL_ERROR;
			}
			if (tagsResult.isRight()) {
				return tagsResult.right().value();
			}
			List<TagData> tagsToCreate = tagsResult.left().value();
			return createTagNodesOnGraph(tagsToCreate);
		}
		log.trace("All tags created succesfully for component {}", component.getUniqueId());
		return StorageOperationStatus.OK;
	}

	protected Either<List<GroupingData>, StorageOperationStatus> findGroupingsForComponent(NodeTypeEnum nodeTypeEnum, Component component) {
		List<CategoryDefinition> categories = component.getCategories();
		List<GroupingData> groupingDataToAssociate = new ArrayList<>();
		if (categories != null) {
			groupingDataToAssociate = new ArrayList<>();
			for (CategoryDefinition categoryDefinition : categories) {
				List<SubCategoryDefinition> subcategories = categoryDefinition.getSubcategories();
				if (subcategories != null) {
					for (SubCategoryDefinition subCategoryDefinition : subcategories) {
						List<GroupingDefinition> groupingDataDefinitions = subCategoryDefinition.getGroupings();
						if (groupingDataDefinitions != null) {
							for (GroupingDataDefinition grouping : groupingDataDefinitions) {
								String groupingId = grouping.getUniqueId();
								Either<GroupingData, TitanOperationStatus> findGroupingEither = findGrouping(nodeTypeEnum, groupingId);
								if (findGroupingEither.isRight()) {
									TitanOperationStatus status = findGroupingEither.right().value();
									log.error("Cannot find grouping {} in the graph. status is {}", groupingId, status);
									if (status == TitanOperationStatus.NOT_FOUND) {
										return Either.right(StorageOperationStatus.CATEGORY_NOT_FOUND);
									}
									return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
								} else {
									groupingDataToAssociate.add(findGroupingEither.left().value());
								}
							}
						}
					}
				}
			}
		}
		return Either.left(groupingDataToAssociate);
	}

	protected TitanOperationStatus associateGroupingsToComponent(ComponentMetadataData componentMetadataData, List<GroupingData> groupingDataToAssociate) {
		for (GroupingData groupingData : groupingDataToAssociate) {
			GraphEdgeLabels groupingLabel = GraphEdgeLabels.GROUPING;
			Either<GraphRelation, TitanOperationStatus> result = titanGenericDao.createRelation(componentMetadataData, groupingData, groupingLabel, null);
			log.debug("After associating grouping {} to component {}. Edge type is {}", groupingData, componentMetadataData, groupingLabel);
			if (result.isRight()) {
				return result.right().value();
			}
		}
		log.trace("All groupings associated succesfully to component {}", componentMetadataData);
		return TitanOperationStatus.OK;
	}

	public abstract Either<Integer, StorageOperationStatus> increaseAndGetComponentInstanceCounter(String componentId, boolean inTransaction);

	protected Either<Integer, StorageOperationStatus> increaseAndGetComponentInstanceCounter(String componentId, NodeTypeEnum nodeType, boolean inTransaction) {
		Either<Integer, StorageOperationStatus> result = null;
		try {

			Either<TitanGraph, TitanOperationStatus> graphResult = titanGenericDao.getGraph();
			if (graphResult.isRight()) {
				result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graphResult.right().value()));
				return result;
			}
			Either<TitanVertex, TitanOperationStatus> vertexService = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId);
			if (vertexService.isRight()) {
				log.debug("failed to fetch vertex of component metadata, nodeType:{} , id: {}", nodeType, componentId);
				result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexService.right().value()));
				return result;
			}
			Vertex vertex = vertexService.left().value();
			Integer instanceCounter = vertex.value(GraphPropertiesDictionary.INSTANCE_COUNTER.getProperty());
			++instanceCounter;
			vertex.property(GraphPropertiesDictionary.INSTANCE_COUNTER.getProperty(), instanceCounter);
			result = Either.left(instanceCounter);
			return result;

		} finally {
			if (false == inTransaction) {
				if (result == null || result.isRight()) {
					log.debug("increaseAndGetComponentInstanceCounter operation : Going to execute rollback on graph.");
					titanGenericDao.rollback();
				} else {
					log.debug("increaseAndGetComponentInstanceCounter operation : Going to execute commit on graph.");
					titanGenericDao.commit();
				}
			}
		}

	}

	protected Either<Integer, StorageOperationStatus> setComponentInstanceCounter(String componentId, NodeTypeEnum nodeType, int counter, boolean inTransaction) {
		Either<Integer, StorageOperationStatus> result = null;
		try {

			Either<TitanGraph, TitanOperationStatus> graphResult = titanGenericDao.getGraph();
			if (graphResult.isRight()) {
				result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graphResult.right().value()));
				return result;
			}
			Either<TitanVertex, TitanOperationStatus> vertexService = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId);
			if (vertexService.isRight()) {
				log.debug("failed to fetch vertex of component metadata ofor id = {}", componentId);
				result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexService.right().value()));
				return result;
			}
			Vertex vertex = vertexService.left().value();
			vertex.property(GraphPropertiesDictionary.INSTANCE_COUNTER.getProperty(), counter);
			result = Either.left(counter);
			return result;

		} finally {
			if (false == inTransaction) {
				if (result == null || result.isRight()) {
					log.debug("deleteService operation : Going to execute rollback on graph.");
					titanGenericDao.rollback();
				} else {
					log.debug("deleteService operation : Going to execute commit on graph.");
					titanGenericDao.commit();
				}
			}
		}

	}

	protected TitanOperationStatus setComponentInstancesFromGraph(String uniqueId, Component component, NodeTypeEnum containerNodeType, NodeTypeEnum compInstNodeType) {

		Either<ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>>, TitanOperationStatus> resourceInstancesOfService = componentInstanceOperation.getComponentInstancesOfComponent(uniqueId, containerNodeType, compInstNodeType);

		if (resourceInstancesOfService.isRight()) {
			TitanOperationStatus status = resourceInstancesOfService.right().value();
			if (status == TitanOperationStatus.NOT_FOUND) {
				status = TitanOperationStatus.OK;
			} else {
				log.error("Failed to fetch resource instances and their relations. status is {}", status);
			}
			return status;
		}

		ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>> immutablePair = resourceInstancesOfService.left().value();
		List<ComponentInstance> instances = immutablePair.getKey();
		List<RequirementCapabilityRelDef> relations = immutablePair.getValue();

		component.setComponentInstances(instances);
		component.setComponentInstancesRelations(relations);

		return TitanOperationStatus.OK;
	}

	/**
	 * set all properties of all of its resources
	 * 
	 * @param uniqueId
	 * @return
	 */
	protected TitanOperationStatus ___setComponentInstancesPropertiesFromGraph(String uniqueId, Component component) {

		List<ComponentInstance> resourceInstances = component.getComponentInstances();

		Map<String, List<ComponentInstanceProperty>> resourceInstancesProperties = new HashMap<>();

		Map<String, List<PropertyDefinition>> alreadyProcessedResources = new HashMap<>();

		if (resourceInstances != null) {
			for (ComponentInstance resourceInstance : resourceInstances) {

				log.debug("Going to update properties of resource instance {}", resourceInstance.getUniqueId());
				String resourceUid = resourceInstance.getComponentUid();

				List<PropertyDefinition> properties = alreadyProcessedResources.get(resourceUid);
				if (properties == null) {
					properties = new ArrayList<>();
					TitanOperationStatus findAllRes = propertyOperation.findAllResourcePropertiesRecursively(resourceUid, properties);
					if (findAllRes != TitanOperationStatus.OK) {
						return findAllRes;
					}
					alreadyProcessedResources.put(resourceUid, properties);
				}
				log.debug("After getting properties of resource {}. Number of properties is {}", resourceUid, (properties == null ? 0 : properties.size()));
				if (false == properties.isEmpty()) {

					String resourceInstanceUid = resourceInstance.getUniqueId();

					Either<List<ComponentInstanceProperty>, TitanOperationStatus> propertyValuesRes = propertyOperation.getAllPropertiesOfResourceInstanceOnlyPropertyDefId(resourceInstanceUid);
					log.debug("After fetching property under resource instance {}", resourceInstanceUid);
					if (propertyValuesRes.isRight()) {
						TitanOperationStatus status = propertyValuesRes.right().value();
						if (status != TitanOperationStatus.NOT_FOUND) {
							return status;
						}
					}

					Map<String, ComponentInstanceProperty> propertyIdToValue = new HashMap<>();
					populateMapperWithPropertyValues(propertyValuesRes, propertyIdToValue);

					List<ComponentInstanceProperty> resourceInstancePropertyList = new ArrayList<>();
					for (PropertyDefinition propertyDefinition : properties) {

						String defaultValue = propertyDefinition.getDefaultValue();
						String value = defaultValue;
						String valueUid = null;

						String propertyId = propertyDefinition.getUniqueId();
						ComponentInstanceProperty valuedProperty = propertyIdToValue.get(propertyId);
						if (valuedProperty != null) {
							String newValue = valuedProperty.getValue();
							// if (newValue != null) {
							value = newValue;
							// }

							valueUid = valuedProperty.getValueUniqueUid();
							log.trace("Found value {} under resource instance which override the default value {}" , value, defaultValue);
						}
						ComponentInstanceProperty resourceInstanceProperty = new ComponentInstanceProperty(propertyDefinition, value, valueUid);

						// TODO: currently ignore constraints since they are not
						// inuse and cause to error in convertion to object.
						resourceInstanceProperty.setConstraints(null);

						resourceInstancePropertyList.add(resourceInstanceProperty);

					}

					resourceInstancesProperties.put(resourceInstanceUid, resourceInstancePropertyList);
				}

			}

			component.setComponentInstancesProperties(resourceInstancesProperties);
		}

		return TitanOperationStatus.OK;
	}

	private void populateMapperWithPropertyValues(Either<List<ComponentInstanceProperty>, TitanOperationStatus> propertyValuesRes, Map<String, ComponentInstanceProperty> propertyIdToValue) {

		if (propertyValuesRes.isLeft()) {
			List<ComponentInstanceProperty> resourceInstanceValues = propertyValuesRes.left().value();
			if (resourceInstanceValues != null) {
				for (ComponentInstanceProperty resourceInstanceProperty : resourceInstanceValues) {
					propertyIdToValue.put(resourceInstanceProperty.getUniqueId(), resourceInstanceProperty);
				}
			}
		}
	}

	public abstract Either<List<ArtifactDefinition>, StorageOperationStatus> getAdditionalArtifacts(String resourceId, boolean recursively, boolean inTransaction);

	protected abstract StorageOperationStatus validateCategories(Component currentComponent, Component component, ComponentMetadataData componentData, NodeTypeEnum type);

	protected abstract <T extends Component> StorageOperationStatus updateDerived(Component component, Component currentComponent, ComponentMetadataData updatedResourceData, Class<T> clazz);

	public abstract Either<Component, StorageOperationStatus> markComponentToDelete(Component componentToDelete, boolean inTransaction);

	protected Either<Component, StorageOperationStatus> internalMarkComponentToDelete(Component componentToDelete, boolean inTransaction) {
		Either<Component, StorageOperationStatus> result = null;

		if ((componentToDelete.getIsDeleted() != null) && componentToDelete.getIsDeleted() && !componentToDelete.isHighestVersion()) {
			// component already marked for delete
			result = Either.left(componentToDelete);
			return result;
		} else {

			ComponentMetadataData componentMetaData = getMetaDataFromComponent(componentToDelete);

			componentMetaData.getMetadataDataDefinition().setIsDeleted(true);
			componentMetaData.getMetadataDataDefinition().setHighestVersion(false);
			componentMetaData.getMetadataDataDefinition().setLastUpdateDate(System.currentTimeMillis());
			try {
				Either<ComponentMetadataData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(componentMetaData, ComponentMetadataData.class);

				StorageOperationStatus updateComponent;
				if (updateNode.isRight()) {
					log.debug("Failed to update component {}. status is {}", componentMetaData.getUniqueId(), updateNode.right().value());
					updateComponent = DaoStatusConverter.convertTitanStatusToStorageStatus(updateNode.right().value());
					result = Either.right(updateComponent);
					return result;
				}

				result = Either.left(componentToDelete);
				return result;
			} finally {

				if (false == inTransaction) {
					if (result == null || result.isRight()) {
						log.error("updateResource operation : Going to execute rollback on graph.");
						titanGenericDao.rollback();
					} else {
						log.debug("updateResource operation : Going to execute commit on graph.");
						titanGenericDao.commit();
					}
				}

			}
		}
	}

	private Either<List<RequirementDefinition>, TitanOperationStatus> convertReqDataListToReqDefList(ComponentInstance componentInstance, List<ImmutablePair<RequirementData, GraphEdge>> requirementData) {
		ConvertDataToDef<RequirementDefinition, RequirementData> convertor = (instance, data, edge) -> convertReqDataToReqDef(instance, data, edge);
		AddOwnerData<RequirementDefinition> dataAdder = (reqDef, compInstance) -> addOwnerDataReq(reqDef, compInstance);
		return convertDataToDefinition(componentInstance, requirementData, convertor, dataAdder);
	}

	private Either<List<CapabilityDefinition>, TitanOperationStatus> convertCapDataListToCapDefList(ComponentInstance componentInstance, List<ImmutablePair<CapabilityData, GraphEdge>> capabilityData) {
		ConvertDataToDef<CapabilityDefinition, CapabilityData> convertor = (instance, data, edge) -> convertCapDataToCapDef(instance, data, edge);
		AddOwnerData<CapabilityDefinition> dataAdder = (capDef, compInstance) -> addOwnerDataCap(capDef, compInstance);
		Either<List<CapabilityDefinition>, TitanOperationStatus> convertationResult = convertDataToDefinition(componentInstance, capabilityData, convertor, dataAdder);
		if (convertationResult.isLeft()) {
			convertationResult = componentInstanceOperation.updateCapDefPropertyValues(componentInstance, convertationResult.left().value());
		}
		return convertationResult;
	}

	private Either<CapabilityDefinition, TitanOperationStatus> convertCapDataToCapDef(ComponentInstance componentInstance, CapabilityData data, GraphEdge edge) {
		Either<CapabilityDefinition, TitanOperationStatus> eitherDef = capabilityOperation.getCapabilityByCapabilityData(data);

		if (eitherDef.isLeft()) {
			CapabilityDefinition capDef = eitherDef.left().value();
			Map<String, Object> properties = edge.getProperties();
			if (properties != null) {
				String name = (String) properties.get(GraphEdgePropertiesDictionary.NAME.getProperty());
				String source = (String) properties.get(GraphEdgePropertiesDictionary.SOURCE.getProperty());
				List<String> sourcesList = new ArrayList<String>();
				capabilityOperation.getCapabilitySourcesList(source, sourcesList);
				capDef.setName(name);
				capDef.setCapabilitySources(sourcesList);
				capDef.setPath(toscaDefinitionPathCalculator.calculateToscaDefinitionPath(componentInstance, edge));

				String requiredOccurrences = (String) properties.get(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty());
				if (requiredOccurrences != null) {
					capDef.setMinOccurrences(requiredOccurrences);
				}
				String leftOccurrences = (String) properties.get(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty());
				if (leftOccurrences != null) {
					capDef.setMaxOccurrences(leftOccurrences);
				}

			}
			eitherDef = Either.left(capDef);
		}
		return eitherDef;
	}

	private Either<RequirementDefinition, TitanOperationStatus> convertReqDataToReqDef(ComponentInstance componentInstance, RequirementData data, GraphEdge edge) {
		Either<RequirementDefinition, TitanOperationStatus> eitherDef = requirementOperation.getRequirement(data.getUniqueId());

		if (eitherDef.isLeft()) {
			RequirementDefinition requirementDef = eitherDef.left().value();
			Map<String, Object> properties = edge.getProperties();
			if (properties != null) {
				String name = (String) properties.get(GraphEdgePropertiesDictionary.NAME.getProperty());
				requirementDef.setName(name);
				String requiredOccurrences = (String) properties.get(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty());
				if (requiredOccurrences != null) {
					requirementDef.setMinOccurrences(requiredOccurrences);
				}
				requirementDef.setPath(toscaDefinitionPathCalculator.calculateToscaDefinitionPath(componentInstance, edge));
				String leftOccurrences = (String) properties.get(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty());
				if (leftOccurrences != null) {
					requirementDef.setMaxOccurrences(leftOccurrences);
				}
			}
			eitherDef = Either.left(requirementDef);
		}
		return eitherDef;
	}

	private <Def, Data> Either<List<Def>, TitanOperationStatus> convertDataToDefinition(ComponentInstance componentInstance, List<ImmutablePair<Data, GraphEdge>> requirementData, ConvertDataToDef<Def, Data> convertor, AddOwnerData<Def> dataAdder) {
		Either<List<Def>, TitanOperationStatus> eitherResult;
		// Convert Data To Definition
		Stream<Either<Def, TitanOperationStatus>> reqDefStream = requirementData.stream().map(e -> convertor.convert(componentInstance, e.left, e.right));

		// Collect But Stop After First Error
		List<Either<Def, TitanOperationStatus>> filteredReqDefList = StreamUtils.takeWhilePlusOne(reqDefStream, p -> p.isLeft()).collect(Collectors.toList());
		Optional<Either<Def, TitanOperationStatus>> optionalError = filteredReqDefList.stream().filter(p -> p.isRight()).findAny();
		if (optionalError.isPresent()) {
			eitherResult = Either.right(optionalError.get().right().value());
		} else {
			// Convert From Either To Definition And Collect
			List<Def> reqDefList = filteredReqDefList.stream().map(e -> e.left().value()).collect(Collectors.toList());
			// Add Owner Data
			reqDefList.forEach(e -> dataAdder.addData(e, componentInstance));
			eitherResult = Either.left(reqDefList);
		}

		return eitherResult;
	}

	interface ConvertDataToDef<Def, Data> {
		Either<Def, TitanOperationStatus> convert(ComponentInstance compInstance, Data d, GraphEdge edge);
	}

	interface AddOwnerData<Def> {
		void addData(Def def, ComponentInstance compInstance);
	}

	private void addOwnerDataCap(CapabilityDefinition capDef, ComponentInstance componentInstance) {
		capDef.setOwnerId(componentInstance.getUniqueId());
		capDef.setOwnerName(componentInstance.getName());
	}

	private void addOwnerDataReq(RequirementDefinition reqDef, ComponentInstance componentInstance) {
		reqDef.setOwnerId(componentInstance.getUniqueId());
		reqDef.setOwnerName(componentInstance.getName());
	}

	public Either<Map<String, List<RequirementDefinition>>, TitanOperationStatus> getRequirements(Component component, NodeTypeEnum nodeTypeEnum, boolean inTransaction) {
		final HashMap<String, List<RequirementDefinition>> emptyMap = new HashMap<>();
		Either<Map<String, List<RequirementDefinition>>, TitanOperationStatus> eitherResult = Either.left(emptyMap);
		try {
			List<ComponentInstance> componentInstances = component.getComponentInstances();
			if (componentInstances != null) {
				Function<ComponentInstance, Either<List<ImmutablePair<RequirementData, GraphEdge>>, TitanOperationStatus>> dataCollector = e -> componentInstanceOperation.getRequirements(e, nodeTypeEnum);
				Either<List<ImmutablePair<ComponentInstance, Either<List<ImmutablePair<RequirementData, GraphEdge>>, TitanOperationStatus>>>, TitanOperationStatus> eitherDataCollected = collectDataFromComponentsInstances(componentInstances,
						dataCollector);
				if (eitherDataCollected.isRight()) {
					eitherResult = Either.right(eitherDataCollected.right().value());
				} else {
					// Converts Data to Def stop if encountered conversion error
					DataDefConvertor<RequirementDefinition, RequirementData> someConvertor = (e1, e2) -> convertReqDataListToReqDefList(e1, e2);
					Either<List<List<RequirementDefinition>>, TitanOperationStatus> fullDefList = convertDataToDefComponentLevel(eitherDataCollected.left().value(), someConvertor);
					if (fullDefList.isRight()) {
						eitherResult = Either.right(fullDefList.right().value());
					} else {
						Stream<RequirementDefinition> defStream = fullDefList.left().value().stream().flatMap(e -> e.stream());
						// Collect to Map and using grouping by
						Map<String, List<RequirementDefinition>> capTypeCapListMap = defStream.collect(Collectors.groupingBy(e -> e.getCapability()));
						eitherResult = Either.left(capTypeCapListMap);
					}

				}

			}
		} finally {
			if (inTransaction == false) {
				titanGenericDao.commit();
			}
		}

		return eitherResult;
	}

	public Either<Map<String, List<CapabilityDefinition>>, TitanOperationStatus> getCapabilities(Component component, NodeTypeEnum nodeTypeEnum, boolean inTransaction) {
		final HashMap<String, List<CapabilityDefinition>> emptyMap = new HashMap<>();
		Either<Map<String, List<CapabilityDefinition>>, TitanOperationStatus> eitherResult = Either.left(emptyMap);
		try {
			List<ComponentInstance> componentInstances = component.getComponentInstances();
			if (componentInstances != null) {
				Function<ComponentInstance, Either<List<ImmutablePair<CapabilityData, GraphEdge>>, TitanOperationStatus>> dataCollector = e -> componentInstanceOperation.getCapabilities(e, nodeTypeEnum);
				Either<List<ImmutablePair<ComponentInstance, Either<List<ImmutablePair<CapabilityData, GraphEdge>>, TitanOperationStatus>>>, TitanOperationStatus> eitherDataCollected = collectDataFromComponentsInstances(componentInstances,
						dataCollector);
				if (eitherDataCollected.isRight()) {
					eitherResult = Either.right(eitherDataCollected.right().value());
				} else {
					// Converts CapData to CapDef removes stop if encountered
					// conversion error
					DataDefConvertor<CapabilityDefinition, CapabilityData> someConvertor = (e1, e2) -> convertCapDataListToCapDefList(e1, e2);
					Either<List<List<CapabilityDefinition>>, TitanOperationStatus> fullDefList = convertDataToDefComponentLevel(eitherDataCollected.left().value(), someConvertor);
					if (fullDefList.isRight()) {
						eitherResult = Either.right(fullDefList.right().value());
					} else {
						Stream<CapabilityDefinition> defStream = fullDefList.left().value().stream().flatMap(e -> e.stream());
						// Collect to Map grouping by Type
						Map<String, List<CapabilityDefinition>> capTypeCapListMap = defStream.collect(Collectors.groupingBy(e -> e.getType()));
						eitherResult = Either.left(capTypeCapListMap);
					}

				}

			}
		} finally {
			if (inTransaction == false) {
				titanGenericDao.commit();
			}
		}

		return eitherResult;
	}

	public <Data> Either<List<ImmutablePair<ComponentInstance, Either<List<ImmutablePair<Data, GraphEdge>>, TitanOperationStatus>>>, TitanOperationStatus> collectDataFromComponentsInstances(List<ComponentInstance> componentInstances,
			Function<ComponentInstance, Either<List<ImmutablePair<Data, GraphEdge>>, TitanOperationStatus>> dataGetter) {
		Either<List<ImmutablePair<ComponentInstance, Either<List<ImmutablePair<Data, GraphEdge>>, TitanOperationStatus>>>, TitanOperationStatus> eitherResult;

		// Get List of Each componentInstance and it's Capabilities Data
		Stream<ImmutablePair<ComponentInstance, Either<List<ImmutablePair<Data, GraphEdge>>, TitanOperationStatus>>> ownerDataStream = componentInstances.stream().map(element -> new ImmutablePair<>(element, dataGetter.apply(element)));
		// Collect but stop after first error
		List<ImmutablePair<ComponentInstance, Either<List<ImmutablePair<Data, GraphEdge>>, TitanOperationStatus>>> ownerCapDataList = StreamUtils
				.takeWhilePlusOne(ownerDataStream, p -> p.right.isLeft() || p.right.isRight() && p.right.right().value() == TitanOperationStatus.NOT_FOUND).collect(Collectors.toList());

		Optional<ImmutablePair<ComponentInstance, Either<List<ImmutablePair<Data, GraphEdge>>, TitanOperationStatus>>> optionalError = ownerCapDataList.stream()
				.filter(p -> p.right.isRight() && p.right.right().value() != TitanOperationStatus.NOT_FOUND).findAny();
		if (optionalError.isPresent()) {
			eitherResult = Either.right(optionalError.get().right.right().value());
		} else {
			eitherResult = Either.left(ownerCapDataList.stream().filter(p -> p.right.isLeft()).collect(Collectors.toList()));
		}

		return eitherResult;
	}

	interface DataDefConvertor<Def, Data> {
		Either<List<Def>, TitanOperationStatus> convertDataToDefComponentInstance(ComponentInstance componentInstance, List<ImmutablePair<Data, GraphEdge>> data);
	}

	public <Def, Data> Either<List<List<Def>>, TitanOperationStatus> convertDataToDefComponentLevel(List<ImmutablePair<ComponentInstance, Either<List<ImmutablePair<Data, GraphEdge>>, TitanOperationStatus>>> ownerCapDataList,
			DataDefConvertor<Def, Data> convertor) {
		// Converts CapData to CapDef removes stop if encountered conversion
		// error
		TitanOperationStatus error = null;
		List<List<Def>> defList = new ArrayList<>();
		for (int i = 0; i < ownerCapDataList.size(); i++) {
			ImmutablePair<ComponentInstance, Either<List<ImmutablePair<Data, GraphEdge>>, TitanOperationStatus>> immutablePair = ownerCapDataList.get(i);
			Either<List<Def>, TitanOperationStatus> convertCapDataListToCapDefList = convertor.convertDataToDefComponentInstance(immutablePair.left, immutablePair.right.left().value());
			if (convertCapDataListToCapDefList.isRight()) {
				error = convertCapDataListToCapDefList.right().value();
				break;
			} else {
				defList.add(convertCapDataListToCapDefList.left().value());
			}

		}
		Either<List<List<Def>>, TitanOperationStatus> eitherResult = (error != null) ? Either.right(error) : Either.left(defList);
		return eitherResult;

	}

	private Map<String, ComponentMetadataData> findLatestVersion(List<ComponentMetadataData> resourceDataList) {
		Map<Pair<String, String>, ComponentMetadataData> latestVersionMap = new HashMap<Pair<String, String>, ComponentMetadataData>();
		for (ComponentMetadataData resourceData : resourceDataList) {
			ComponentMetadataData latestVersionData = resourceData;

			ComponentMetadataDataDefinition metadataDataDefinition = resourceData.getMetadataDataDefinition();
			Pair<String, String> pair = createKeyPair(latestVersionData);
			if (latestVersionMap.containsKey(pair)) {
				latestVersionData = latestVersionMap.get(pair);
				String currentVersion = latestVersionData.getMetadataDataDefinition().getVersion();
				String newVersion = metadataDataDefinition.getVersion();
				if (CommonBeUtils.compareAsdcComponentVersions(newVersion, currentVersion)) {
					latestVersionData = resourceData;
				}
			}
			if (log.isDebugEnabled())
				log.debug("last certified version of resource = {}  version is {}", latestVersionData.getMetadataDataDefinition().getName(), latestVersionData.getMetadataDataDefinition().getVersion());

			latestVersionMap.put(pair, latestVersionData);
		}

		Map<String, ComponentMetadataData> resVersionMap = new HashMap<String, ComponentMetadataData>();
		for (ComponentMetadataData resourceData : latestVersionMap.values()) {
			ComponentMetadataData latestVersionData = resourceData;
			ComponentMetadataDataDefinition metadataDataDefinition = resourceData.getMetadataDataDefinition();
			if (resVersionMap.containsKey(metadataDataDefinition.getUUID())) {
				latestVersionData = resVersionMap.get(metadataDataDefinition.getUUID());
				String currentVersion = latestVersionData.getMetadataDataDefinition().getVersion();
				String newVersion = metadataDataDefinition.getVersion();
				if (CommonBeUtils.compareAsdcComponentVersions(newVersion, currentVersion)) {
					latestVersionData = resourceData;
				}
			}
			if (log.isDebugEnabled())
				log.debug("last uuid version of resource = {}  version is {}", latestVersionData.getMetadataDataDefinition().getName(), latestVersionData.getMetadataDataDefinition().getVersion());
			resVersionMap.put(latestVersionData.getMetadataDataDefinition().getUUID(), latestVersionData);
		}

		return resVersionMap;
	}

	private Pair<String, String> createKeyPair(ComponentMetadataData metadataData) {
		Pair<String, String> pair = null;
		NodeTypeEnum label = NodeTypeEnum.getByName(metadataData.getLabel());
		switch (label) {
		case Resource:
			pair = new ImmutablePair<String, String>(metadataData.getMetadataDataDefinition().getName(), ((ResourceMetadataDataDefinition) metadataData.getMetadataDataDefinition()).getResourceType().name());
			break;
		default:
			pair = new ImmutablePair<String, String>(metadataData.getMetadataDataDefinition().getName(), metadataData.getLabel());
			break;
		}

		return pair;
	}

	public Either<Collection<ComponentMetadataData>, StorageOperationStatus> getLatestVersionNotAbstractComponentsMetadataOnly(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType) {
		try {

			// Map<String, Object> hasPpropertiesToMatch = new HashMap<>();
			// Map<String, Object> hasNotPpropertiesToMatch = new HashMap<>();
			List<ImmutableTriple<QueryType, String, Object>> properties = new ArrayList<>();
			if (componentTypeEnum.equals(ComponentTypeEnum.RESOURCE)) {
				// hasPpropertiesToMatch.put(GraphPropertiesDictionary.IS_ABSTRACT.getProperty(),
				// isAbstract);
				properties.add(new ImmutableTriple<>(QueryType.HAS, GraphPropertiesDictionary.IS_ABSTRACT.getProperty(), isAbstract));

				if (internalComponentType != null) {
					switch (internalComponentType.toLowerCase()) {
					case "vf":
						properties.add(new ImmutableTriple<>(QueryType.HAS_NOT, GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VF.name()));
//						properties.add(new ImmutableTriple<>(QueryType.HAS_NOT, GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VL.name()));
						// hasNotPpropertiesToMatch.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(),
						// ResourceTypeEnum.VF.name());
						break;
					case "service":
						properties.add(new ImmutableTriple<>(QueryType.HAS_NOT, GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VFC.name()));
						properties.add(new ImmutableTriple<>(QueryType.HAS_NOT, GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VFCMT.name()));
						properties.add(new ImmutableTriple<>(QueryType.HAS_NOT, GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.CVFC.name()));
//						properties.add(new ImmutableTriple<>(QueryType.HAS_NOT, GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VL.name()));
						// hasNotPpropertiesToMatch.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(),
						// ResourceTypeEnum.VFC.name());
						break;
					case "vl":
						properties.add(new ImmutableTriple<>(QueryType.HAS, GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VL.name()));
						// hasPpropertiesToMatch.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(),
						// ResourceTypeEnum.VL.name());
						break;
					default:
						break;
					}
				}
			}
			// hasNotPpropertiesToMatch.put(GraphPropertiesDictionary.STATE.getProperty(),
			// LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name());
			properties.add(new ImmutableTriple<>(QueryType.HAS_NOT, GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name()));
			// hasNotPpropertiesToMatch.put(GraphPropertiesDictionary.IS_DELETED.getProperty(),
			// true);
			properties.add(new ImmutableTriple<>(QueryType.HAS_NOT, GraphPropertiesDictionary.IS_DELETED.getProperty(), true));
			// Either<List<ComponentMetadataData>, TitanOperationStatus>
			// resourceNodes = titanGenericDao.getByCriteria(
			// componentTypeEnum.getNodeType(), hasPpropertiesToMatch,
			// hasNotPpropertiesToMatch,
			// ComponentMetadataData.class);
			Either<List<ComponentMetadataData>, TitanOperationStatus> resourceNodes = titanGenericDao.getByCriteria(componentTypeEnum.getNodeType(), ComponentMetadataData.class, properties);
			if (resourceNodes.isRight()) {
				// in case of NOT_FOUND from Titan client return to UI empty
				// list
				if (resourceNodes.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
					return Either.left(new ArrayList<>());
				} else {
					return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resourceNodes.right().value()));
				}
			} else {
				List<ComponentMetadataData> resourceDataList = resourceNodes.left().value();
				Collection<ComponentMetadataData> resCollection = resourceDataList;
				if (isHighest != null && isHighest) {
					Map<String, ComponentMetadataData> latestVersionListMap = findLatestVersion(resourceDataList);
					resCollection = latestVersionListMap.values();
				}
				return Either.left(resCollection);
			}
		} finally {
			titanGenericDao.commit();
		}

	}

	public Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractComponents(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType, List<String> componentUids) {
		try {
			List<Component> result = new ArrayList<>();
			Map<String, ResourceTypeEnum> componentUidsMap = new HashMap<>();
			if (componentUids == null) {
				Either<Collection<ComponentMetadataData>, StorageOperationStatus> resourceNodes = getLatestVersionNotAbstractComponentsMetadataOnly(isAbstract, isHighest, componentTypeEnum, internalComponentType);
				if (resourceNodes.isRight()) {
					return Either.right(resourceNodes.right().value());
				}
				Collection<ComponentMetadataData> collection = resourceNodes.left().value();

				if (collection == null) {
					componentUids = new ArrayList<>();
				} else {
					componentUids = collection.stream().map(p -> p.getMetadataDataDefinition().getUniqueId()).collect(Collectors.toList());
					// collection.forEach(p -> {
					// if (NodeTypeEnum.Resource.getName().equals(p.getLabel()))
					// {
					// componentUidsMap.put(p.getMetadataDataDefinition().getUniqueId(),
					// ((ResourceMetadataDataDefinition)
					// p.getMetadataDataDefinition()).getResourceType());
					// }
					// });

				}

			}
			if (false == componentUids.isEmpty()) {

				Manager manager = new Manager();
				int numberOfWorkers = 5;

				manager.init(numberOfWorkers);
				for (String componentUid : componentUids) {
					ComponentParametersView componentParametersView = buildComponentViewForNotAbstract();
					// ResourceTypeEnum type =
					// componentUidsMap.get(componentUid);
					// if (type != null && ResourceTypeEnum.VL.equals(type)) {
					if (internalComponentType != null && "vl".equalsIgnoreCase(internalComponentType)) {
						componentParametersView.setIgnoreCapabilities(false);
						componentParametersView.setIgnoreRequirements(false);
					}
					manager.addJob(new Job() {
						@Override
						public Either<Component, StorageOperationStatus> doWork() {
							Either<Component, StorageOperationStatus> component = getComponent(componentUid, componentParametersView, false);
							return component;
						}
					});
				}
				LinkedBlockingQueue<Either<Component, StorageOperationStatus>> res = manager.start();

				for (Either<Component, StorageOperationStatus> resource : res) {
					if (resource == null) {
						if (log.isDebugEnabled())
							log.debug("Failed to fetch resource returned null ");
						return Either.right(StorageOperationStatus.GENERAL_ERROR);
					}
					if (resource.isRight()) {
						if (log.isDebugEnabled())
							log.debug("Failed to fetch resource for error is {}", resource.right().value());
						return Either.right(resource.right().value());
					}
					Component component = resource.left().value();
					component.setContactId(null);
					component.setCreationDate(null);
					component.setCreatorUserId(null);
					component.setCreatorFullName(null);
					component.setLastUpdateDate(null);
					component.setLastUpdaterUserId(null);
					component.setLastUpdaterFullName(null);
					component.setNormalizedName(null);
					result.add(resource.left().value());
				}

				if (componentUids.size() != result.size()) {
					if (log.isDebugEnabled())
						log.debug("one of the workers failed to complete job ");
					return Either.right(StorageOperationStatus.GENERAL_ERROR);
				}
			}

			return Either.left(result);

		} finally {
			titanGenericDao.commit();
		}
	}

	private ComponentParametersView buildComponentViewForNotAbstract() {
		ComponentParametersView componentParametersView = new ComponentParametersView();
		componentParametersView.disableAll();
		// componentParametersView.setIgnoreRequirements(false);
		// componentParametersView.setIgnoreCapabilities(false);
		componentParametersView.setIgnoreCategories(false);
		componentParametersView.setIgnoreAllVersions(false);
		componentParametersView.setIgnoreAllVersions(false);
		return componentParametersView;
	}

	protected TitanOperationStatus setCapabilitiesFromGraph(String uniqueId, Component component, NodeTypeEnum nodeType) {
		TitanOperationStatus titanStatus;
		Either<Map<String, List<CapabilityDefinition>>, TitanOperationStatus> eitherCapabilities = getCapabilities(component, nodeType, true);
		if (eitherCapabilities.isLeft()) {
			titanStatus = TitanOperationStatus.OK;
			Map<String, List<CapabilityDefinition>> capabilities = eitherCapabilities.left().value();
			if (capabilities != null && !capabilities.isEmpty()) {
				component.setCapabilities(capabilities);
			}
		} else {
			titanStatus = eitherCapabilities.right().value();
		}
		return titanStatus;
	}

	protected TitanOperationStatus setRequirementsFromGraph(String uniqueId, Component component, NodeTypeEnum nodeType) {
		TitanOperationStatus status;
		Either<Map<String, List<RequirementDefinition>>, TitanOperationStatus> eitherRequirements = getRequirements(component, nodeType, false);
		if (eitherRequirements.isLeft()) {
			status = TitanOperationStatus.OK;
			Map<String, List<RequirementDefinition>> requirements = eitherRequirements.left().value();
			if (requirements != null && !requirements.isEmpty()) {
				component.setRequirements(requirements);
			}
		} else {
			status = eitherRequirements.right().value();
		}
		return status;
	}

	protected boolean isComponentExist(String componentId, NodeTypeEnum nodeType) {
		boolean result = true;
		Either<TitanVertex, TitanOperationStatus> compVertex = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId);
		if (compVertex.isRight()) {
			log.debug("failed to fetch vertex of component data for id {}", componentId);
			result = false;

		}
		return result;
	}

	<T> Either<T, StorageOperationStatus> getLightComponent(String id, NodeTypeEnum nodeType, boolean inTransaction) {

		T component = null;
		try {
			log.debug("Starting to build light component of type {}, id {}", nodeType, id);
			Either<TitanGraph, TitanOperationStatus> graphResult = titanGenericDao.getGraph();
			if (graphResult.isRight()) {
				return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graphResult.right().value()));
			}
			TitanGraph titanGraph = graphResult.left().value();
			Iterable<TitanVertex> vertecies = titanGraph.query().has(UniqueIdBuilder.getKeyByNodeType(nodeType), id).vertices();
			if (vertecies != null) {
				Iterator<TitanVertex> iterator = vertecies.iterator();
				if (iterator != null && iterator.hasNext()) {
					Vertex vertex = iterator.next();
					Map<String, Object> resourceProperties = titanGenericDao.getProperties(vertex);
					ComponentMetadataData componentMetadataData = GraphElementFactory.createElement(nodeType.getName(), GraphElementTypeEnum.Node, resourceProperties, ComponentMetadataData.class);
					component = (T) convertComponentMetadataDataToComponent(componentMetadataData);

					// get creator
					Iterator<Edge> iterCreator = vertex.edges(Direction.IN, GraphEdgeLabels.CREATOR.name());
					if (iterCreator.hasNext() == false) {
						log.debug("no creator was defined for component {}", id);
						return Either.right(StorageOperationStatus.GENERAL_ERROR);
					}
					Vertex vertexCreator = iterCreator.next().outVertex();
					UserData creator = GraphElementFactory.createElement(NodeTypeEnum.User.getName(), GraphElementTypeEnum.Node, titanGenericDao.getProperties(vertexCreator), UserData.class);
					log.debug("Build component : set creator userId to {}", creator.getUserId());
					String fullName = buildFullName(creator);
					log.debug("Build component : set creator full name to {}", fullName);
					((Component) component).setCreatorUserId(creator.getUserId());
					((Component) component).setCreatorFullName(fullName);

					// get modifier
					Iterator<Edge> iterModifier = vertex.edges(Direction.IN, GraphEdgeLabels.LAST_MODIFIER.name());

					if (iterModifier.hasNext() == false) {
						log.debug("no modifier was defined for component {}", id);
						return Either.right(StorageOperationStatus.GENERAL_ERROR);
					}
					Vertex vertexModifier = iterModifier.next().outVertex();
					UserData modifier = GraphElementFactory.createElement(NodeTypeEnum.User.getName(), GraphElementTypeEnum.Node, titanGenericDao.getProperties(vertexModifier), UserData.class);
					log.debug("Build component : set last modifier userId to {}", creator.getUserId());
					fullName = buildFullName(modifier);
					log.debug("Build component : set last modifier full name to {}", fullName);
					((Component) component).setLastUpdaterUserId(modifier.getUserId());
					((Component) component).setLastUpdaterFullName(fullName);

					// get category
					TitanOperationStatus status = setComponentCategoriesFromGraph((Component) component);
					if (status != TitanOperationStatus.OK) {
						return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
					}
				} else {
					// Nothing found
					log.debug("Component with id {} not found", id);
					return Either.right(StorageOperationStatus.NOT_FOUND);
				}
			} else {
				// Nothing found
				log.debug("Component with id {} not found", id);
				return Either.right(StorageOperationStatus.NOT_FOUND);
			}
			log.debug("Ended to build light component of type {}, id {}", nodeType, id);
			return Either.left(component);
		} finally {
			if (false == inTransaction) {
				titanGenericDao.commit();
			}
		}
	}

	Either<Component, StorageOperationStatus> getMetadataComponent(String id, NodeTypeEnum nodeType, boolean inTransaction) {
		Component component = null;
		try {
			log.debug("Starting to build metadata component of type {}, id {}", nodeType, id);
			Either<TitanGraph, TitanOperationStatus> graphResult = titanGenericDao.getGraph();
			if (graphResult.isRight()) {
				return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graphResult.right().value()));
			}
			TitanGraph titanGraph = graphResult.left().value();
			Iterable<TitanVertex> vertecies = titanGraph.query().has(UniqueIdBuilder.getKeyByNodeType(nodeType), id).vertices();
			if (vertecies != null) {
				Iterator<TitanVertex> iterator = vertecies.iterator();
				if (iterator != null && iterator.hasNext()) {
					Vertex vertex = iterator.next();
					Map<String, Object> resourceProperties = titanGenericDao.getProperties(vertex);
					ComponentMetadataData componentMetadataData = GraphElementFactory.createElement(nodeType.getName(), GraphElementTypeEnum.Node, resourceProperties, ComponentMetadataData.class);
					component = convertComponentMetadataDataToComponent(componentMetadataData);
				} else {
					// Nothing found
					log.debug("Component with id {} not found", id);
					return Either.right(StorageOperationStatus.NOT_FOUND);
				}
			} else {
				// Nothing found
				log.debug("Component with id {} not found", id);
				return Either.right(StorageOperationStatus.NOT_FOUND);
			}
			log.debug("Ended to build metadata component of type {}, id {}", nodeType, id);
			return Either.left(component);
		} finally {
			if (false == inTransaction) {
				titanGenericDao.commit();
			}
		}
	}

	public Either<Integer, StorageOperationStatus> getComponentInstanceCoutner(String origServiceId, NodeTypeEnum nodeType) {
		Either<Integer, StorageOperationStatus> result;
		Either<TitanGraph, TitanOperationStatus> graphResult = titanGenericDao.getGraph();
		if (graphResult.isRight()) {
			result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graphResult.right().value()));
			return result;
		}
		Either<TitanVertex, TitanOperationStatus> vertexService = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(nodeType), origServiceId);
		if (vertexService.isRight()) {
			log.debug("failed to fetch vertex of component metadata, nodeType:{} , id: {}", nodeType, origServiceId);
			result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexService.right().value()));
			return result;
		}
		Vertex vertex = vertexService.left().value();
		Integer instanceCounter = vertex.value(GraphPropertiesDictionary.INSTANCE_COUNTER.getProperty());
		return Either.left(instanceCounter);
	}

	protected TitanOperationStatus setComponentInstancesPropertiesFromGraph(Component component) {

		List<ComponentInstance> resourceInstances = component.getComponentInstances();

		Map<String, List<ComponentInstanceProperty>> resourceInstancesProperties = new HashMap<>();

		Map<String, List<PropertyDefinition>> alreadyProcessedResources = new HashMap<>();

		Map<String, List<ComponentInstanceProperty>> alreadyProcessedInstances = new HashMap<>();

		Map<String, ImmutablePair<ComponentInstance, Integer>> processedInstances = new HashMap<>();

		if (resourceInstances != null) {

			for (ComponentInstance resourceInstance : resourceInstances) {

				List<String> path = new ArrayList<>();
				path.add(resourceInstance.getUniqueId());
				Either<List<ComponentInstanceProperty>, TitanOperationStatus> componentInstanceProperties = componentInstanceOperation.getComponentInstanceProperties(resourceInstance, alreadyProcessedResources, alreadyProcessedInstances,
						processedInstances, path);

				if (componentInstanceProperties.isRight()) {
					TitanOperationStatus status = componentInstanceProperties.right().value();
					if (status != TitanOperationStatus.OK) {
						return status;
					}
				}

				List<ComponentInstanceProperty> listOfProps = componentInstanceProperties.left().value();
				String resourceInstanceUid = resourceInstance.getUniqueId();
				resourceInstancesProperties.put(resourceInstanceUid, listOfProps);

				// alreadyProcessedInstances.put(resourceInstance.getUniqueId(),
				// resourceInstance);

				processedInstances.put(resourceInstance.getUniqueId(), new ImmutablePair<ComponentInstance, Integer>(resourceInstance, path.size()));
				path.remove(path.size() - 1);

			}

		}

		Either<Map<String, Map<String, ComponentInstanceProperty>>, TitanOperationStatus> findAllPropertiesValuesOnInstances = componentInstanceOperation.findAllPropertyValueOnInstances(processedInstances);
		// 1. check status
		if (findAllPropertiesValuesOnInstances.isRight()) {
			TitanOperationStatus status = findAllPropertiesValuesOnInstances.right().value();
			if (status != TitanOperationStatus.OK) {
				return status;
			}
		}
		// 2. merge data from rules on properties (resourceInstancesProperties)
		propertyOperation.updatePropertiesByPropertyValues(resourceInstancesProperties, findAllPropertiesValuesOnInstances.left().value());

		component.setComponentInstancesProperties(resourceInstancesProperties);

		return TitanOperationStatus.OK;
	}
	
	protected TitanOperationStatus setComponentInstancesInputsFromGraph(String uniqueId, Component component) {

		Map<String, List<ComponentInstanceInput>> resourceInstancesInputs = new HashMap<>();
		TitanOperationStatus status = TitanOperationStatus.OK;
		List<ComponentInstance> componentInstances = component.getComponentInstances();
		if (componentInstances != null) {
			for (ComponentInstance resourceInstance : componentInstances) {
				Either<List<ComponentInstanceInput>, TitanOperationStatus> eitherRIAttributes = inputOperation.getAllInputsOfResourceInstance(resourceInstance);
				if (eitherRIAttributes.isRight()) {
					if (eitherRIAttributes.right().value() != TitanOperationStatus.NOT_FOUND) {
						status = eitherRIAttributes.right().value();
						break;
					}
				} else {
					resourceInstancesInputs.put(resourceInstance.getUniqueId(), eitherRIAttributes.left().value());
				}
			}
			if (!resourceInstancesInputs.isEmpty())
				component.setComponentInstancesInputs(resourceInstancesInputs);
		}

		return status;
	}

	public Either<String, StorageOperationStatus> getInvariantUUID(NodeTypeEnum nodeType, String componentId, boolean inTransaction) {
		Either<String, StorageOperationStatus> res = null;
		try {
			Either<TitanVertex, TitanOperationStatus> vertexByProperty = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId);
			if (vertexByProperty.isRight()) {
				TitanOperationStatus status = vertexByProperty.right().value();
				if (status == TitanOperationStatus.NOT_FOUND) {
					status = TitanOperationStatus.INVALID_ID;
				}
				res = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
			} else {
				Vertex v = vertexByProperty.left().value();
				String invariantUUID = v.value(GraphPropertiesDictionary.INVARIANT_UUID.getProperty());

				if (invariantUUID == null || invariantUUID.isEmpty()) {

					log.info("The component {} has empty invariant UUID.", componentId);
					res = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.INVALID_ELEMENT));

				}
				res = Either.left(invariantUUID);
			}
		} finally {
			if (false == inTransaction) {
				titanGenericDao.commit();
			}
		}
		return res;
	}

	protected TitanOperationStatus setGroupsFromGraph(String uniqueId, Component component, NodeTypeEnum nodeTypeEnum) {

		Either<List<GroupDefinition>, TitanOperationStatus> res = groupOperation.getAllGroupsFromGraph(uniqueId, nodeTypeEnum);
		if (res.isRight()) {
			TitanOperationStatus status = res.right().value();
			if (status == TitanOperationStatus.NOT_FOUND) {
				return TitanOperationStatus.OK;
			} else {
				return status;
			}
		}
		component.setGroups(res.left().value());

		return TitanOperationStatus.OK;

	}

	protected TitanOperationStatus setComponentInputsFromGraph(String uniqueId, Component component, boolean inTransaction) {

		List<InputDefinition> inputs = new ArrayList<>();
		TitanOperationStatus status = inputsOperation.findAllResourceInputs(uniqueId, inputs);
		if (status == TitanOperationStatus.OK) {
			component.setInputs(inputs);
		}

		return status;

	}

	protected StorageOperationStatus deleteGroups(NodeTypeEnum nodeType, String componentId) {

		Either<List<GroupDefinition>, StorageOperationStatus> deleteRes = groupOperation.deleteAllGroups(componentId, nodeType, true);

		if (deleteRes.isRight()) {
			StorageOperationStatus status = deleteRes.right().value();
			return status;
		}

		return StorageOperationStatus.OK;

	}

	protected StorageOperationStatus removeInputsFromComponent(NodeTypeEnum typeEnum, Component component) {
		Either<Map<String, InputDefinition>, StorageOperationStatus> deleteAllInputsAssociatedToNode = inputsOperation.deleteAllInputsAssociatedToNode(typeEnum, component.getUniqueId());
		return deleteAllInputsAssociatedToNode.isRight() ? deleteAllInputsAssociatedToNode.right().value() : StorageOperationStatus.OK;
	}

	protected TitanOperationStatus associateInputsToComponent(NodeTypeEnum nodeType, ComponentMetadataData resourceData, List<InputDefinition> properties) {

		Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = applicationDataTypeCache.getAll();
		if (allDataTypes.isRight()) {
			TitanOperationStatus status = allDataTypes.right().value();
			log.debug("Cannot find any data type. Status is {}.", status);
			return status;
		}

		Map<String, InputDefinition> convertedProperties = new HashMap<>();

		if (properties != null) {
			for (InputDefinition propertyDefinition : properties) {
				convertedProperties.put(propertyDefinition.getName(), propertyDefinition);
			}

			Either<List<InputDefinition>, TitanOperationStatus> operationStatus = inputsOperation.addInputsToGraph(resourceData.getMetadataDataDefinition().getUniqueId(), nodeType, convertedProperties, allDataTypes.left().value());
			if (operationStatus.isLeft())
				return TitanOperationStatus.OK;
			else
				return operationStatus.right().value();
		}

		return TitanOperationStatus.OK;

	}

	protected TitanOperationStatus associateInputsToComponent(TitanVertex metadataVertex, String componentId, List<InputDefinition> properties) {

		Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = applicationDataTypeCache.getAll();
		if (allDataTypes.isRight()) {
			TitanOperationStatus status = allDataTypes.right().value();
			log.debug("Cannot find any data type. Status is {}.", status);
			return status;
		}

		Map<String, InputDefinition> convertedProperties = new HashMap<>();

		if (properties != null) {
			for (InputDefinition propertyDefinition : properties) {
				convertedProperties.put(propertyDefinition.getName(), propertyDefinition);
			}

			return inputsOperation.addInputsToGraph(metadataVertex, componentId, convertedProperties, allDataTypes.left().value());
		}

		return TitanOperationStatus.OK;

	}

	public Either<List<ComponentInstance>, StorageOperationStatus> getAllComponentInstncesMetadata(String componentId, NodeTypeEnum nodeType) {
		Instant start = Instant.now();
		Either<List<ComponentInstance>, StorageOperationStatus> resourceInstancesOfService = componentInstanceOperation.getAllComponentInstancesMetadataOnly(componentId, nodeType);
		Instant end = Instant.now();
		log.debug("TOTAL TIME BL GET INSTANCES: {}", Duration.between(start, end));
		return resourceInstancesOfService;
	}

	@Deprecated
	public Either<List<Component>, ActionStatus> getComponentsFromCacheForCatalog(Set<String> components, ComponentTypeEnum componentType) {

		Either<ImmutableTriple<List<Component>, List<Component>, Set<String>>, ActionStatus> componentsForCatalog = componentCache.getComponentsForCatalog(components, componentType);
		if (componentsForCatalog.isLeft()) {
			ImmutableTriple<List<Component>, List<Component>, Set<String>> immutableTriple = componentsForCatalog.left().value();
			List<Component> foundComponents = immutableTriple.getLeft();

			if (foundComponents != null) {
				// foundComponents.forEach(p -> result.add((Resource)p));
				log.debug("The number of {}s added to catalog from cache is {}", componentType.name().toLowerCase(), foundComponents.size());

			}
			List<Component> foundDirtyComponents = immutableTriple.getMiddle();
			Set<String> nonCachedComponents = immutableTriple.getRight();
			int numberDirtyResources = foundDirtyComponents == null ? 0 : foundDirtyComponents.size();
			int numberNonCached = nonCachedComponents == null ? 0 : nonCachedComponents.size();
			log.debug("The number of left {}s for catalog is {}", componentType.name().toLowerCase(), numberDirtyResources + numberNonCached);
			return Either.left(foundComponents);
		}

		return Either.right(componentsForCatalog.right().value());
	}

	public <T extends ComponentMetadataData> Either<List<T>, TitanOperationStatus> getListOfHighestComponents(NodeTypeEnum nodeTypeEnum, Class<T> clazz) {

		long startFetchAllStates = System.currentTimeMillis();
		Map<String, Object> propertiesToMatchHigest = new HashMap<>();
		propertiesToMatchHigest.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true);
		Either<List<T>, TitanOperationStatus> allHighestStates = titanGenericDao.getByCriteria(nodeTypeEnum, propertiesToMatchHigest, clazz);
		if (allHighestStates.isRight() && allHighestStates.right().value() != TitanOperationStatus.NOT_FOUND) {
			return Either.right(allHighestStates.right().value());
		}
		long endFetchAllStates = System.currentTimeMillis();

		if (allHighestStates.isRight()) {
			return Either.left(new ArrayList<>());
		}
		List<T> services = allHighestStates.left().value();

		List<T> certifiedHighest = new ArrayList<>();
		List<T> notCertifiedHighest = new ArrayList<>();
		for (T reData : services) {
			if (reData.getMetadataDataDefinition().getState().equals(LifecycleStateEnum.CERTIFIED.name())) {
				certifiedHighest.add(reData);
			} else {
				notCertifiedHighest.add(reData);
			}
		}

		log.debug("Fetch catalog {}s all states: certified {}, noncertified {}", nodeTypeEnum.getName(), certifiedHighest.size(), notCertifiedHighest.size());
		log.debug("Fetch catalog {}s all states from graph took {} ms", nodeTypeEnum.getName(), endFetchAllStates - startFetchAllStates);

		HashMap<String, String> serviceNames = new HashMap<>();
		for (T data : notCertifiedHighest) {
			String serviceName = data.getMetadataDataDefinition().getName();
			serviceNames.put(serviceName, serviceName);
		}

		for (T data : certifiedHighest) {
			String serviceName = data.getMetadataDataDefinition().getName();
			if (!serviceNames.containsKey(serviceName)) {
				notCertifiedHighest.add(data);
			}
		}

		return Either.left(notCertifiedHighest);
	}

	protected <T extends Component> Either<T, ActionStatus> getComponentFromCacheIfUpToDate(String uniqueId, ComponentMetadataData componentMetadataData, ComponentParametersView componentParametersView, Class<T> clazz,
			ComponentTypeEnum componentTypeEnum) {

		long start = System.currentTimeMillis();
		try {

			long lastModificationTime = componentMetadataData.getMetadataDataDefinition().getLastUpdateDate();
			Either<Component, ActionStatus> cacheComponentRes = this.componentCache.getComponent(uniqueId, lastModificationTime);
			if (cacheComponentRes.isLeft()) {
				Component cachedComponent = cacheComponentRes.left().value();

				// Must calculate allVersions
				if (false == componentParametersView.isIgnoreAllVersions()) {
					Class<? extends ComponentMetadataData> clazz1 = null;
					switch (componentTypeEnum) {
					case RESOURCE:
						clazz1 = ResourceMetadataData.class;
						break;
					case SERVICE:
						clazz1 = ServiceMetadataData.class;
						break;
					case PRODUCT:
						clazz1 = ProductMetadataData.class;
						break;
					default:
						break;
					}
					if (clazz1 != null) {
						Either<Map<String, String>, TitanOperationStatus> versionList = getVersionList(componentTypeEnum.getNodeType(), cachedComponent.getVersion(), cachedComponent.getUUID(), cachedComponent.getSystemName(), clazz1);
						if (versionList.isRight()) {
							return Either.right(ActionStatus.GENERAL_ERROR);
						}

						Map<String, String> allVersions = versionList.left().value();
						cachedComponent.setAllVersions(allVersions);
					} else {
						return Either.right(ActionStatus.GENERAL_ERROR);
					}
				}
				if (componentParametersView != null) {
					cachedComponent = componentParametersView.filter(cachedComponent, componentTypeEnum);
				}
				return Either.left(clazz.cast(cachedComponent));
			}

			return Either.right(cacheComponentRes.right().value());

		} finally {
			log.trace("Fetch component {} with uid {} from cache took {} ms", componentTypeEnum.name().toLowerCase(), uniqueId, System.currentTimeMillis() - start);
		}
	}

	public Either<ImmutablePair<List<Component>, Set<String>>, ActionStatus> getComponentsFromCacheForCatalog(Map<String, Long> components, ComponentTypeEnum componentType) {

		Either<ImmutablePair<List<Component>, Set<String>>, ActionStatus> componentsForCatalog = componentCache.getComponentsForCatalog(components, componentType);
		if (componentsForCatalog.isLeft()) {
			ImmutablePair<List<Component>, Set<String>> immutablePair = componentsForCatalog.left().value();
			List<Component> foundComponents = immutablePair.getLeft();

			if (foundComponents != null) {
				// foundComponents.forEach(p -> result.add((Resource)p));
				log.debug("The number of {}s added to catalog from cache is {}", componentType.name().toLowerCase(), foundComponents.size());
			}
			Set<String> leftComponents = immutablePair.getRight();
			int numberNonCached = leftComponents == null ? 0 : leftComponents.size();
			log.debug("The number of left {}s for catalog is {}", componentType.name().toLowerCase(), numberNonCached);

			ImmutablePair<List<Component>, Set<String>> result = new ImmutablePair<List<Component>, Set<String>>(foundComponents, leftComponents);
			return Either.left(result);
		}

		return Either.right(componentsForCatalog.right().value());
	}

	/**
	 * 
	 * @param component
	 * @param inTransaction
	 * @param titanGenericDao
	 * @param clazz
	 * @return
	 */
	public <T> Either<T, StorageOperationStatus> updateComponentFilterResult(Component component, boolean inTransaction, TitanGenericDao titanGenericDao, Class<T> clazz, NodeTypeEnum type, ComponentParametersView filterResult) {
		Either<T, StorageOperationStatus> result = null;

		try {

			log.debug("In updateComponent. received component uid = {}", (component == null ? null : component.getUniqueId()));
			if (component == null) {
				log.error("Service object is null");
				result = Either.right(StorageOperationStatus.BAD_REQUEST);
				return result;
			}

			ComponentMetadataData componentData = getMetaDataFromComponent(component);

			log.debug("After converting component to componentData. ComponentData = {}", componentData);

			if (componentData.getUniqueId() == null) {
				log.error("Resource id is missing in the request.");
				return Either.right(StorageOperationStatus.BAD_REQUEST);
			}

			Either<Integer, StorageOperationStatus> counterStatus = this.getComponentInstanceCoutner(component.getUniqueId(), component.getComponentType().getNodeType());

			if (counterStatus.isRight()) {

				log.error("Cannot find componentInstanceCounter for component {} in the graph. status is {}", componentData.getUniqueId(), counterStatus);
				// result = sendError(status,
				// StorageOperationStatus.USER_NOT_FOUND);
				return result;
			}

			componentData.setComponentInstanceCounter(counterStatus.left().value());

			String modifierUserId = component.getLastUpdaterUserId();
			if (modifierUserId == null || modifierUserId.isEmpty()) {
				log.error("UserId is missing in the request.");
				result = Either.right(StorageOperationStatus.BAD_REQUEST);
				return result;
			}
			Either<UserData, TitanOperationStatus> findUser = findUser(modifierUserId);

			if (findUser.isRight()) {
				TitanOperationStatus status = findUser.right().value();
				log.error("Cannot find user {} in the graph. status is {}", modifierUserId, status);
				// result = sendError(status,
				// StorageOperationStatus.USER_NOT_FOUND);
				return result;
			}

			UserData modifierUserData = findUser.left().value();
			String resourceId = component.getUniqueId();

			ComponentParametersView componentParametersView = new ComponentParametersView();
			componentParametersView.disableAll();
			componentParametersView.setIgnoreUsers(false);
			componentParametersView.setIgnoreCategories(false);
			componentParametersView.setIgnoreDerivedFrom(false);
			componentParametersView.setIgnoreArtifacts(false);
			Either<T, StorageOperationStatus> currentComponentResult = this.getComponent(resourceId, componentParametersView, inTransaction);
			if (currentComponentResult.isRight()) {
				log.error("Cannot find resource with id {} in the graph.", resourceId);
				result = Either.right(currentComponentResult.right().value());
				return result;
			}

			Component currentComponent = (Component) currentComponentResult.left().value();
			String currentModifier = currentComponent.getLastUpdaterUserId();

			if (currentModifier.equals(modifierUserData.getUniqueId())) {
				log.debug("Graph LAST MODIFIER edge should not be changed since the modifier is the same as the last modifier.");
			} else {
				log.debug("Going to update the last modifier user of the resource from {} to {}", currentModifier, modifierUserId);
				StorageOperationStatus status = moveLastModifierEdge(component, componentData, modifierUserData, type);
				log.debug("Finish to update the last modifier user of the resource from {} to {}. status is {}", currentModifier, modifierUserId, status);
				if (status != StorageOperationStatus.OK) {
					result = Either.right(status);
					return result;
				}
			}
			final long currentTimeMillis = System.currentTimeMillis();
			log.debug("Going to update the last Update Date of the resource from {} to {}", component.getLastUpdateDate(), currentTimeMillis);
			component.setLastUpdateDate(currentTimeMillis);

			StorageOperationStatus checkCategories = validateCategories(currentComponent, component, componentData, type);
			if (checkCategories != StorageOperationStatus.OK) {
				result = Either.right(checkCategories);
				return result;
			}

			List<String> tags = component.getTags();
			if (tags != null && false == tags.isEmpty()) {
				Either<List<TagData>, StorageOperationStatus> tagsResult = createNewTagsList(tags);
				if (tagsResult.isRight()) {
					result = Either.right(tagsResult.right().value());
					return result;
				}
				List<TagData> tagsToCreate = tagsResult.left().value();
				if (tagsToCreate != null && !tagsToCreate.isEmpty()) {
					tagsToCreate = ImmutableSet.copyOf(tagsToCreate).asList();
					for (TagData tagData : tagsToCreate) {
						log.debug("Before creating tag {}", tagData);
						Either<TagData, TitanOperationStatus> createTagResult = titanGenericDao.createNode(tagData, TagData.class);
						if (createTagResult.isRight()) {
							TitanOperationStatus status = createTagResult.right().value();
							log.error("Cannot find tag {} in the graph. status is {}", tagData, status);
							result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
							return result;
						}
						log.debug("After creating tag {}", tagData);
					}
				}
			}

			Either<ComponentMetadataData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(componentData, ComponentMetadataData.class);

			if (updateNode.isRight()) {
				log.error("Failed to update resource {}. status is {}", component.getUniqueId(), updateNode.right().value());
				result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateNode.right().value()));
				return result;
			}

			ComponentMetadataData updatedResourceData = updateNode.left().value();
			log.debug("ComponentData After update is {}", updatedResourceData);

			// DE230195 in case resource name changed update TOSCA artifacts
			// file names accordingly
			String newSystemName = updatedResourceData.getMetadataDataDefinition().getSystemName();
			String prevSystemName = currentComponent.getSystemName();
			if (newSystemName != null && !newSystemName.equals(prevSystemName)) {
				Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
				if (toscaArtifacts != null) {
					for (Entry<String, ArtifactDefinition> artifact : toscaArtifacts.entrySet()) {
						Either<ArtifactData, StorageOperationStatus> updateName = generateAndUpdateToscaFileName(component.getComponentType().getValue().toLowerCase(), newSystemName, updatedResourceData.getMetadataDataDefinition().getUniqueId(),
								type, artifact.getValue());
						if (updateName.isRight()) {
							result = Either.right(updateName.right().value());
							return result;
						}
					}
				}
				//TODO call to new Artifact operation in order to update list of artifacts 
				
		     //US833308 VLI in service - specific network_role property value logic
				if (ComponentTypeEnum.SERVICE == component.getComponentType()) {
					//update method logs success/error and returns boolean (true if nothing fails)
					updateServiceNameInVLIsNetworkRolePropertyValues(component, prevSystemName, newSystemName);
				}
			}
			

			if (component.getComponentType().equals(ComponentTypeEnum.RESOURCE)) {
				updateDerived(component, currentComponent, componentData, component.getClass());
			}

			Either<T, StorageOperationStatus> updatedResource = getComponent(component.getUniqueId(), filterResult, inTransaction);
			if (updatedResource.isRight()) {
				log.error("Resource id is missing in the request. status is {}", updatedResource.right().value());
				result = Either.right(StorageOperationStatus.BAD_REQUEST);
				return result;
			}

			T updatedResourceValue = updatedResource.left().value();
			result = Either.left(updatedResourceValue);

			return result;
		} finally {

			if (false == inTransaction) {
				if (result == null || result.isRight()) {
					log.error("updateComponent operation : Going to execute rollback on graph.");
					titanGenericDao.rollback();
				} else {
					log.debug("updateComponent operation : Going to execute commit on graph.");
					titanGenericDao.commit();
				}
			}
		}
	}
	
	private boolean updateServiceNameInVLIsNetworkRolePropertyValues (Component component, String prevSystemName, String newSystemName) {
		// find VLIs in service
		boolean res = true;
		if(null == component.getComponentInstances() || component.getComponentInstances().isEmpty()){
			return res;
		}
		
		List <ComponentInstance> vlInstances = 
				component.getComponentInstances().stream()
				.filter(p -> OriginTypeEnum.VL == p.getOriginType())
				.collect(Collectors.toList());
		if (!vlInstances.isEmpty()) {
			for (ComponentInstance vlInstance : vlInstances){
				// find network_role property 
				Optional <ComponentInstanceProperty> networkRoleProperty = component.getComponentInstancesProperties().get(vlInstance.getUniqueId()).stream()
						.filter(p -> PropertyNames.NETWORK_ROLE.getPropertyName().equalsIgnoreCase(p.getName()))
						.findAny();	
				res = res && updateNetworkRolePropertyValue(prevSystemName, newSystemName, vlInstance, networkRoleProperty);		
			}	
		}
		return res;	
	}

	private boolean updateNetworkRolePropertyValue(String prevSystemName, String newSystemName, ComponentInstance vlInstance, Optional<ComponentInstanceProperty> networkRoleProperty) {
		if (networkRoleProperty.isPresent() && !StringUtils.isEmpty(networkRoleProperty.get().getValue()) ) {
			ComponentInstanceProperty property = networkRoleProperty.get();
			String updatedValue = property.getValue().replaceFirst(prevSystemName, newSystemName);
			property.setValue(updatedValue);
			StorageOperationStatus updateCustomizationUUID;
			//disregard property value rule 
			property.setRules(null);
			Either<ComponentInstanceProperty, StorageOperationStatus> result = componentInstanceOperation.updatePropertyValueInResourceInstance(property, vlInstance.getUniqueId(), true);
			if (result.isLeft()) {
				log.debug("Property value {} was updated on graph.", property.getValueUniqueUid());
				updateCustomizationUUID = componentInstanceOperation.updateCustomizationUUID(vlInstance.getUniqueId());
			} else {
				updateCustomizationUUID = StorageOperationStatus.EXEUCTION_FAILED;
				log.debug("Failed to update property value: {} in resource instance {}", updatedValue, vlInstance.getUniqueId());
			}
			return result.isLeft() && StorageOperationStatus.OK == updateCustomizationUUID;
		}
		return true;
	}

	public Either<ComponentMetadataData, StorageOperationStatus> updateComponentLastUpdateDateAndLastModifierOnGraph( Component component, User modifier, NodeTypeEnum componentType, boolean inTransaction) {
		
		log.debug("Going to update last update date and last modifier info of component {}. ", component.getName());
		Either<ComponentMetadataData, StorageOperationStatus> result = null;
		try{
			String modifierUserId = modifier.getUserId();
			ComponentMetadataData componentData = getMetaDataFromComponent(component);
			String currentUser = component.getLastUpdaterUserId();
			UserData modifierUserData = new UserData();
			modifierUserData.setUserId(modifierUserId);
			if (currentUser.equals(modifierUserId)) {
				log.debug("Graph last modifier edge should not be changed since the modifier is the same as the last modifier.");
			} else {
				log.debug("Going to update the last modifier user of the component from {} to {}", currentUser, modifierUserId);
				StorageOperationStatus status = moveLastModifierEdge(component, componentData, modifierUserData, componentType);
				log.debug("Finish to update the last modifier user of the resource from {} to {}. status is {}", currentUser, modifierUserId, status);
				if (status != StorageOperationStatus.OK) {
					result = Either.right(status);
				}
			}
			Either<ComponentMetadataData, TitanOperationStatus> updateNode = null;
			if(result == null){
				log.debug("Going to update the component {} with new last update date. ", component.getName());
				componentData.getMetadataDataDefinition().setLastUpdateDate(System.currentTimeMillis());
				updateNode = titanGenericDao.updateNode(componentData, ComponentMetadataData.class);
				if (updateNode.isRight()) {
					log.error("Failed to update component {}. status is {}", component.getUniqueId(), updateNode.right().value());
					result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateNode.right().value()));
				}
			}
			if(result == null){
				result = Either.left(updateNode.left().value());
			}
		}catch(Exception e){
			log.error("Exception occured during  update last update date and last modifier info of component {}. The message is {}. ", component.getName(), e.getMessage());
		}finally {
			if(!inTransaction){
				if (result == null || result.isRight()) {
					log.error("Going to execute rollback on graph.");
					titanGenericDao.rollback();
				} else {
					log.debug("Going to execute commit on graph.");
					titanGenericDao.commit();
				}
			}
		}
		return result;
	}
	/**
	 * updates component lastUpdateDate on graph node
	 * @param component
	 * @param componentType
	 * @param lastUpdateDate
	 * @param inTransaction
	 * @return
	 */
	public Either<ComponentMetadataData, StorageOperationStatus> updateComponentLastUpdateDateOnGraph( Component component, NodeTypeEnum componentType, Long lastUpdateDate, boolean inTransaction) {
		
		log.debug("Going to update last update date of component {}. ", component.getName());
		Either<ComponentMetadataData, StorageOperationStatus> result = null;
		try{
			ComponentMetadataData componentData = getMetaDataFromComponent(component);
			Either<ComponentMetadataData, TitanOperationStatus> updateNode = null;
			if(result == null){
				log.debug("Going to update the component {} with new last update date. ", component.getName());
				componentData.getMetadataDataDefinition().setLastUpdateDate(lastUpdateDate);
				updateNode = titanGenericDao.updateNode(componentData, ComponentMetadataData.class);
				if (updateNode.isRight()) {
					log.error("Failed to update component {}. status is {}", component.getUniqueId(), updateNode.right().value());
					result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateNode.right().value()));
				}
			}
			if(result == null){
				result = Either.left(updateNode.left().value());
			}
		}catch(Exception e){
			log.error("Exception occured during  update last update date of component {}. The message is {}. ", component.getName(), e.getMessage());
		}finally {
			if(!inTransaction){
				if (result == null || result.isRight()) {
					log.error("Going to execute rollback on graph.");
					titanGenericDao.rollback();
				} else {
					log.debug("Going to execute commit on graph.");
					titanGenericDao.commit();
				}
			}
		}
		return result;
	}
}