aboutsummaryrefslogtreecommitdiffstats
path: root/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaOperationFacade.java
blob: 50b2ae45b44c00f79df08da0c20f100afc4cbeeb (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
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
/*-
 * ============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.jsonjanusgraph.operations;

import fj.data.Either;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.openecomp.sdc.be.config.Configuration;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.model.jsonjanusgraph.config.ContainerInstanceTypesData;
import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
import org.openecomp.sdc.be.dao.jsongraph.HealingJanusGraphDao;
import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
import org.openecomp.sdc.be.datatypes.elements.*;
import org.openecomp.sdc.be.datatypes.elements.MapInterfaceDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.*;
import org.openecomp.sdc.be.model.*;
import org.openecomp.sdc.be.datatypes.elements.MapCapabilityProperty;
import org.openecomp.sdc.be.datatypes.elements.MapListCapabilityDataDefinition;
import org.openecomp.sdc.be.model.CatalogUpdateTimestamp;
import org.openecomp.sdc.be.model.catalog.CatalogComponent;
import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.TopologyTemplate;
import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElement;
import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter;
import org.openecomp.sdc.be.model.operations.StorageException;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
import org.openecomp.sdc.be.model.utils.GroupUtils;
import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.common.util.ValidationUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;
import java.util.Map.Entry;
import java.util.function.BiPredicate;
import java.util.stream.Collectors;

import static java.util.Objects.requireNonNull;
import static org.apache.commons.collections.CollectionUtils.isEmpty;
import static org.apache.commons.collections.CollectionUtils.isNotEmpty;


@org.springframework.stereotype.Component("tosca-operation-facade")
public class ToscaOperationFacade {

    // region - Fields

    private static final String COULDNT_FETCH_A_COMPONENT_WITH_AND_UNIQUE_ID_ERROR = "Couldn't fetch a component with and UniqueId {}, error: {}";
    private static final String FAILED_TO_FIND_RECENTLY_ADDED_PROPERTY_ON_THE_RESOURCE_STATUS_IS = "Failed to find recently added property {} on the resource {}. Status is {}. ";
    private static final String FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS = "Failed to get updated resource {}. Status is {}. ";
    private static final String FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS = "Failed to add the property {} to the resource {}. Status is {}. ";
    private static final String SERVICE = "service";
    private static final String NOT_SUPPORTED_COMPONENT_TYPE = "Not supported component type {}";
    private static final String COMPONENT_CREATED_SUCCESSFULLY = "Component created successfully!!!";
    private static final String COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR = "Couldn't fetch component with and unique id {}, error: {}";
    @Autowired
    private NodeTypeOperation nodeTypeOperation;
    @Autowired
    private TopologyTemplateOperation topologyTemplateOperation;
    @Autowired
    private NodeTemplateOperation nodeTemplateOperation;
    @Autowired
    private GroupsOperation groupsOperation;
    @Autowired
    private HealingJanusGraphDao janusGraphDao;
    @Autowired
    private ContainerInstanceTypesData containerInstanceTypesData;

    private static final Logger log = Logger.getLogger(ToscaOperationFacade.class.getName());
    // endregion

    // region - ToscaElement - GetById
    public static final String PROXY_SUFFIX = "_proxy";

    public <T extends Component> Either<T, StorageOperationStatus> getToscaFullElement(String componentId) {
        ComponentParametersView filters = new ComponentParametersView();
        filters.setIgnoreCapabiltyProperties(false);
        filters.setIgnoreForwardingPath(false);
        return getToscaElement(componentId, filters);
    }

    public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId) {

        return getToscaElement(componentId, JsonParseFlagEnum.ParseAll);

    }

    public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId, ComponentParametersView filters) {

        Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
            .getVertexById(componentId, filters.detectParseFlag());
        if (getVertexEither.isRight()) {
            log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
            return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));

        }
        return getToscaElementByOperation(getVertexEither.left().value(), filters);
    }

    public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId, JsonParseFlagEnum parseFlag) {

        Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
            .getVertexById(componentId, parseFlag);
        if (getVertexEither.isRight()) {
            log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
            return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));

        }
        return getToscaElementByOperation(getVertexEither.left().value());
    }

    public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(GraphVertex componentVertex) {
        return getToscaElementByOperation(componentVertex);
    }

    public Either<Boolean, StorageOperationStatus> validateComponentExists(String componentId) {

        Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
            .getVertexById(componentId, JsonParseFlagEnum.NoParse);
        if (getVertexEither.isRight()) {
            JanusGraphOperationStatus status = getVertexEither.right().value();
            if (status == JanusGraphOperationStatus.NOT_FOUND) {
                return Either.left(false);
            } else {
                log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
                return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
            }
        }
        return Either.left(true);
    }

    public <T extends Component> Either<T, StorageOperationStatus> findLastCertifiedToscaElementByUUID(T component) {
        Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
        props.put(GraphPropertyEnum.UUID, component.getUUID());
        props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
        props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);

        Either<List<GraphVertex>, JanusGraphOperationStatus> getVertexEither = janusGraphDao
            .getByCriteria(ModelConverter.getVertexType(component), props);
        if (getVertexEither.isRight()) {
            log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, component.getUniqueId(), getVertexEither.right().value());
            return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));

        }
        return getToscaElementByOperation(getVertexEither.left().value().get(0));
    }

    // endregion
    // region - ToscaElement - GetByOperation
    private <T extends Component> Either<T, StorageOperationStatus> getToscaElementByOperation(GraphVertex componentV) {
        return getToscaElementByOperation(componentV, new ComponentParametersView());
    }

    private <T extends Component> Either<T, StorageOperationStatus> getToscaElementByOperation(GraphVertex componentV,
        ComponentParametersView filters) {
        if (componentV == null) {
            log.debug("Unexpected null value for `componentV`");
            return Either.right(StorageOperationStatus.GENERAL_ERROR);
        } else {
            VertexTypeEnum label = componentV.getLabel();

            ToscaElementOperation toscaOperation = getToscaElementOperation(componentV);
            if (toscaOperation != null) {
                log.debug("getToscaElementByOperation: toscaOperation={}", toscaOperation.getClass());
            }

            Either<ToscaElement, StorageOperationStatus> toscaElement;
            String componentId = componentV.getUniqueId();
            if (toscaOperation != null) {
                log.debug("Need to fetch tosca element for id {}", componentId);
                toscaElement = toscaOperation.getToscaElement(componentV, filters);
            } else {
                log.debug("not supported tosca type {} for id {}", label, componentId);
                toscaElement = Either.right(StorageOperationStatus.BAD_REQUEST);
            }
            return toscaElement.left().map(ModelConverter::convertFromToscaElement);
        }
    }

    // endregion
    private ToscaElementOperation getToscaElementOperation(GraphVertex componentV) {
        VertexTypeEnum label = componentV.getLabel();
        switch (label) {
            case NODE_TYPE:
                return nodeTypeOperation;
            case TOPOLOGY_TEMPLATE:
                return topologyTemplateOperation;
            default:
                return null;
        }
    }

    public <T extends Component> Either<T, StorageOperationStatus> createToscaComponent(T resource) {
        ToscaElement toscaElement = ModelConverter.convertToToscaElement(resource);

        ToscaElementOperation toscaElementOperation = getToscaElementOperation(resource);
        Either<ToscaElement, StorageOperationStatus> createToscaElement = toscaElementOperation.createToscaElement(toscaElement);
        if (createToscaElement.isLeft()) {
            log.debug(COMPONENT_CREATED_SUCCESSFULLY);
            T dataModel = ModelConverter.convertFromToscaElement(createToscaElement.left().value());
            return Either.left(dataModel);
        }
        return Either.right(createToscaElement.right().value());
    }

    // region - ToscaElement Delete
    public StorageOperationStatus markComponentToDelete(Component componentToDelete) {

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

            Either<GraphVertex, JanusGraphOperationStatus> getResponse = janusGraphDao
                .getVertexById(componentToDelete.getUniqueId(), JsonParseFlagEnum.ParseAll);
            if (getResponse.isRight()) {
                log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentToDelete.getUniqueId(), getResponse.right().value());
                return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getResponse.right().value());

            }
            GraphVertex componentV = getResponse.left().value();

            // same operation for node type and topology template operations
            Either<GraphVertex, StorageOperationStatus> result = nodeTypeOperation.markComponentToDelete(componentV);
            if (result.isRight()) {
                return result.right().value();
            }
            return StorageOperationStatus.OK;
        }
    }

    public <T extends Component> Either<T, StorageOperationStatus> deleteToscaComponent(String componentId) {

        Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
            .getVertexById(componentId, JsonParseFlagEnum.ParseAll);
        if (getVertexEither.isRight()) {
            log.debug("Couldn't fetch component vertex with and unique id {}, error: {}", componentId, getVertexEither.right().value());
            return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));

        }
        Either<ToscaElement, StorageOperationStatus> deleteElement = deleteToscaElement(getVertexEither.left().value());
        if (deleteElement.isRight()) {
            log.debug("Failed to delete component with and unique id {}, error: {}", componentId, deleteElement.right().value());
            return Either.right(deleteElement.right().value());
        }
        T dataModel = ModelConverter.convertFromToscaElement(deleteElement.left().value());

        return Either.left(dataModel);
    }

    private Either<ToscaElement, StorageOperationStatus> deleteToscaElement(GraphVertex componentV) {
        VertexTypeEnum label = componentV.getLabel();
        Either<ToscaElement, StorageOperationStatus> toscaElement;
        Object componentId = componentV.getUniqueId();
        switch (label) {
            case NODE_TYPE:
                log.debug("Need to fetch node type for id {}", componentId);
                toscaElement = nodeTypeOperation.deleteToscaElement(componentV);
                break;
            case TOPOLOGY_TEMPLATE:
                log.debug("Need to fetch topology template for id {}", componentId);
                toscaElement = topologyTemplateOperation.deleteToscaElement(componentV);
                break;
            default:
                log.debug("not supported tosca type {} for id {}", label, componentId);
                toscaElement = Either.right(StorageOperationStatus.BAD_REQUEST);
                break;
        }
        return toscaElement;
    }
    // endregion

    private ToscaElementOperation getToscaElementOperation(Component component) {
        return ModelConverter.isAtomicComponent(component) ? nodeTypeOperation : topologyTemplateOperation;
    }

    public <T extends Component> Either<T, StorageOperationStatus> getLatestByToscaResourceName(String toscaResourceName) {
        return getLatestByName(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName);
    }

    public <T extends Component> Either<T, StorageOperationStatus> getFullLatestComponentByToscaResourceName(String toscaResourceName) {
        ComponentParametersView fetchAllFilter = new ComponentParametersView();
        fetchAllFilter.setIgnoreForwardingPath(true);
        fetchAllFilter.setIgnoreCapabiltyProperties(false);
        return getLatestByName(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName, JsonParseFlagEnum.ParseAll, fetchAllFilter);
    }

    public <T extends Component> Either<T, StorageOperationStatus> getLatestByName(String resourceName) {
        return getLatestByName(GraphPropertyEnum.NAME, resourceName);

    }

    public StorageOperationStatus validateCsarUuidUniqueness(String csarUUID) {

        Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
        properties.put(GraphPropertyEnum.CSAR_UUID, csarUUID);

        Either<List<GraphVertex>, JanusGraphOperationStatus> resources = janusGraphDao
            .getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata);

        if (resources.isRight()) {
            if (resources.right().value() == JanusGraphOperationStatus.NOT_FOUND) {
                return StorageOperationStatus.OK;
            } else {
                log.debug("failed to get resources from graph with property name: {}", csarUUID);
                return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(resources.right().value());
            }
        }
        return StorageOperationStatus.ENTITY_ALREADY_EXISTS;

    }

    public <T extends Component> Either<Set<T>, StorageOperationStatus> getFollowed(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates, ComponentTypeEnum componentType) {
        Either<List<ToscaElement>, StorageOperationStatus> followedResources;
        if (componentType == ComponentTypeEnum.RESOURCE) {
            followedResources = nodeTypeOperation.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType);
        } else {
            followedResources = topologyTemplateOperation.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType);
        }

        Set<T> components = new HashSet<>();
        if (followedResources.isRight() && followedResources.right().value() != StorageOperationStatus.NOT_FOUND) {
            return Either.right(followedResources.right().value());
        }
        if (followedResources.isLeft()) {
            List<ToscaElement> toscaElements = followedResources.left().value();
            toscaElements.forEach(te -> {
                T component = ModelConverter.convertFromToscaElement(te);
                components.add(component);
            });
        }
        return Either.left(components);
    }

    public Either<Resource, StorageOperationStatus> getLatestCertifiedNodeTypeByToscaResourceName(String toscaResourceName) {

        return getLatestCertifiedByToscaResourceName(toscaResourceName, VertexTypeEnum.NODE_TYPE, JsonParseFlagEnum.ParseMetadata);
    }

    public Either<Resource, StorageOperationStatus> getLatestCertifiedByToscaResourceName(String toscaResourceName,
        VertexTypeEnum vertexType, JsonParseFlagEnum parseFlag) {

        Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
        props.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName);
        props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
        props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
        Either<List<GraphVertex>, JanusGraphOperationStatus> getLatestRes = janusGraphDao
            .getByCriteria(vertexType, props, parseFlag);

        return getLatestRes
            .right().map(
                status -> {
                    CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch {} with name {}. status={} ",
                        vertexType, toscaResourceName, status);
                    return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status);
                }
            )
            .left().bind(
                resources -> {
                    double version = 0.0;
                    GraphVertex highestResource = null;
                    for (GraphVertex resource : resources) {
                        double resourceVersion = Double
                            .parseDouble((String) resource.getJsonMetadataField(JsonPresentationFields.VERSION));
                        if (resourceVersion > version) {
                            version = resourceVersion;
                            highestResource = resource;
                        }
                    }
                    if (highestResource != null) {
                        return getToscaFullElement(highestResource.getUniqueId());
                    } else {
                        log.debug("The vertex with the highest version could not be found for {}", toscaResourceName);
                        return Either.right(StorageOperationStatus.GENERAL_ERROR);
                    }
                }
            );
    }
	
	public Either<Resource, StorageOperationStatus> getLatestResourceByToscaResourceName(String toscaResourceName) {
    	if (toscaResourceName != null && toscaResourceName.contains("org.openecomp.resource.vf"))
    		return getLatestResourceByToscaResourceName(toscaResourceName, VertexTypeEnum.TOPOLOGY_TEMPLATE, JsonParseFlagEnum.ParseMetadata);
    	else
    		return getLatestResourceByToscaResourceName(toscaResourceName, VertexTypeEnum.NODE_TYPE, JsonParseFlagEnum.ParseMetadata);
    }

    public Either<Resource, StorageOperationStatus> getLatestResourceByToscaResourceName(String toscaResourceName, VertexTypeEnum vertexType, JsonParseFlagEnum parseFlag) {

        Either<Resource, StorageOperationStatus> result = null;
        Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
        props.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName);
        props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
        if (!toscaResourceName.contains("org.openecomp.resource.vf")) {
            props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
        }

        Either<List<GraphVertex>, JanusGraphOperationStatus> getLatestRes = janusGraphDao.getByCriteria(vertexType, props, parseFlag);

        if (getLatestRes.isRight()) {
            JanusGraphOperationStatus status = getLatestRes.right().value();
            CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch {} with name {}. status={} ", vertexType, toscaResourceName, status);
            result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
        }
        if (result == null) {
            List<GraphVertex> resources = getLatestRes.left().value();
            double version = 0.0;
            GraphVertex highestResource = null;
            for (GraphVertex resource : resources) {
                double resourceVersion = Double.parseDouble((String) resource.getJsonMetadataField(JsonPresentationFields.VERSION));
                if (resourceVersion > version) {
                    version = resourceVersion;
                    highestResource = resource;
                }
            }

            if (highestResource != null) {
                result = getToscaFullElement(highestResource.getUniqueId());
            } else {
                log.debug("The vertex with the highest version could not be found for {}", toscaResourceName);
                result = Either.right(StorageOperationStatus.GENERAL_ERROR);
            }
        }
        return result;
    }

    public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExists(String templateName) {
        Either<Boolean, StorageOperationStatus> validateUniquenessRes = validateToscaResourceNameUniqueness(templateName);
        if (validateUniquenessRes.isLeft()) {
            return Either.left(!validateUniquenessRes.left().value());
        }
        return validateUniquenessRes;
    }

    public Either<RequirementCapabilityRelDef, StorageOperationStatus> dissociateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) {
        return nodeTemplateOperation.dissociateResourceInstances(componentId, requirementDef);
    }

    /**
     * Allows to get fulfilled requirement by relation and received predicate
     */
    public Either<RequirementDataDefinition, StorageOperationStatus> getFulfilledRequirementByRelation(String componentId, String instanceId, RequirementCapabilityRelDef relation, BiPredicate<RelationshipInfo, RequirementDataDefinition> predicate) {
        return nodeTemplateOperation.getFulfilledRequirementByRelation(componentId, instanceId, relation, predicate);
    }

    /**
     * Allows to get fulfilled capability by relation and received predicate
     */
    public Either<CapabilityDataDefinition, StorageOperationStatus> getFulfilledCapabilityByRelation(String componentId, String instanceId, RequirementCapabilityRelDef relation, BiPredicate<RelationshipInfo, CapabilityDataDefinition> predicate) {
        return nodeTemplateOperation.getFulfilledCapabilityByRelation(componentId, instanceId, relation, predicate);
    }

    public Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> associateResourceInstances(Component component, String componentId, List<RequirementCapabilityRelDef> relations) {
        Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> reqAndCapListEither = nodeTemplateOperation.associateResourceInstances(component, componentId, relations);
        if (component != null) {
            updateInstancesCapAndReqOnComponentFromDB(component);
        }
        return reqAndCapListEither;

    }

    protected Either<Boolean, StorageOperationStatus> validateToscaResourceNameUniqueness(String name) {

        Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
        properties.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, name);

        Either<List<GraphVertex>, JanusGraphOperationStatus> resources = janusGraphDao
            .getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata);

        if (resources.isRight() && resources.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
            log.debug("failed to get resources from graph with property name: {}", name);
            return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(resources.right().value()));
        }
        List<GraphVertex> resourceList = (resources.isLeft() ? resources.left().value() : null);
        if (isNotEmpty(resourceList)) {
            if (log.isDebugEnabled()) {
                StringBuilder builder = new StringBuilder();
                for (GraphVertex resourceData : resourceList) {
                    builder.append(resourceData.getUniqueId() + "|");
                }
                log.debug("resources  with property name:{} exists in graph. found {}", name, builder);
            }
            return Either.left(false);
        } else {
            log.debug("resources  with property name:{} does not exists in graph", name);
            return Either.left(true);
        }

    }

    // region - Component Update

    public Either<Resource, StorageOperationStatus> overrideComponent(Resource newComponent, Resource oldComponent) {

        copyArtifactsToNewComponent(newComponent, oldComponent);

        Either<GraphVertex, JanusGraphOperationStatus> componentVEither = janusGraphDao
            .getVertexById(oldComponent.getUniqueId(), JsonParseFlagEnum.NoParse);
        if (componentVEither.isRight()) {
            log.debug("Failed to fetch component {} error {}", oldComponent.getUniqueId(), componentVEither.right().value());
            return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(componentVEither.right().value()));
        }
        GraphVertex componentv = componentVEither.left().value();
        Either<GraphVertex, JanusGraphOperationStatus> parentVertexEither = janusGraphDao.getParentVertex(componentv, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse);
        if (parentVertexEither.isRight() && parentVertexEither.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
            log.debug("Failed to fetch parent version for component {} error {}", oldComponent.getUniqueId(), parentVertexEither.right().value());
            return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(parentVertexEither.right().value()));
        }

        Either<ToscaElement, StorageOperationStatus> deleteToscaComponent = deleteToscaElement(componentv);
        if (deleteToscaComponent.isRight()) {
            log.debug("Failed to remove old component {} error {}", oldComponent.getUniqueId(), deleteToscaComponent.right().value());
            return Either.right(deleteToscaComponent.right().value());
        }
        Either<Resource, StorageOperationStatus> createToscaComponent = createToscaComponent(newComponent);
        if (createToscaComponent.isRight()) {
            log.debug("Failed to create tosca element component {} error {}", newComponent.getUniqueId(), createToscaComponent.right().value());
            return Either.right(createToscaComponent.right().value());
        }
        Resource newElement = createToscaComponent.left().value();
        Either<GraphVertex, JanusGraphOperationStatus> newVersionEither = janusGraphDao
            .getVertexById(newElement.getUniqueId(), JsonParseFlagEnum.NoParse);
        if (newVersionEither.isRight()) {
            log.debug("Failed to fetch new tosca element component {} error {}", newComponent.getUniqueId(), newVersionEither.right().value());
            return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(newVersionEither.right().value()));
        }
        if (parentVertexEither.isLeft()) {
            GraphVertex previousVersionV = parentVertexEither.left().value();
            JanusGraphOperationStatus createEdge = janusGraphDao.createEdge(previousVersionV, newVersionEither.left().value(), EdgeLabelEnum.VERSION, null);
            if (createEdge != JanusGraphOperationStatus.OK) {
                log.debug("Failed to associate to previous version {} new version {} error {}", previousVersionV.getUniqueId(), newVersionEither.right().value(), createEdge);
                return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(createEdge));
            }
        }
        return Either.left(newElement);
    }

    void copyArtifactsToNewComponent(Resource newComponent, Resource oldComponent) {
        // TODO - check if required
        Map<String, ArtifactDefinition> toscaArtifacts = oldComponent.getToscaArtifacts();
        if (toscaArtifacts != null && !toscaArtifacts.isEmpty()) {
            toscaArtifacts.values().stream().forEach(a -> a.setDuplicated(Boolean.TRUE));
        }
        newComponent.setToscaArtifacts(toscaArtifacts);

        Map<String, ArtifactDefinition> artifacts = oldComponent.getArtifacts();
        if (artifacts != null && !artifacts.isEmpty()) {
            artifacts.values().stream().forEach(a -> a.setDuplicated(Boolean.TRUE));
        }
        newComponent.setArtifacts(artifacts);

        Map<String, ArtifactDefinition> depArtifacts = oldComponent.getDeploymentArtifacts();
        if (depArtifacts != null && !depArtifacts.isEmpty()) {
            depArtifacts.values().stream().forEach(a -> a.setDuplicated(Boolean.TRUE));
        }
        newComponent.setDeploymentArtifacts(depArtifacts);


        newComponent.setLastUpdateDate(null);
        newComponent.setHighestVersion(true);
    }

    public <T extends Component> Either<T, StorageOperationStatus> updateToscaElement(T componentToUpdate) {
        return updateToscaElement(componentToUpdate, new ComponentParametersView());
    }

    public <T extends Component> Either<T, StorageOperationStatus> updateToscaElement(T componentToUpdate, ComponentParametersView filterResult) {
        String componentId = componentToUpdate.getUniqueId();
        Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
            .getVertexById(componentId, JsonParseFlagEnum.ParseAll);
        if (getVertexEither.isRight()) {
            log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
            return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
        }
        GraphVertex elementV = getVertexEither.left().value();
        ToscaElementOperation toscaElementOperation = getToscaElementOperation(elementV);

        ToscaElement toscaElementToUpdate = ModelConverter.convertToToscaElement(componentToUpdate);
        Either<ToscaElement, StorageOperationStatus> updateToscaElement = null;
        if (toscaElementOperation != null) {
            updateToscaElement = toscaElementOperation.updateToscaElement(toscaElementToUpdate, elementV, filterResult);
        } else {
            log.debug("Null value returned by `getToscaElementOperation` with value {}", elementV);
            updateToscaElement = Either.right(StorageOperationStatus.GENERAL_ERROR);
        }

        return updateToscaElement.bimap(
            ModelConverter::convertFromToscaElement,
            status -> {
                log.debug("Failed to update tosca element {} error {}", componentId, status);
                return status;
            });
    }

    private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName, JsonParseFlagEnum parseFlag) {
        return getLatestByName(property, nodeName, parseFlag, new ComponentParametersView());
    }

    private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName, JsonParseFlagEnum parseFlag, ComponentParametersView filter) {
        Either<T, StorageOperationStatus> result;

        Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
        Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);

        propertiesToMatch.put(property, nodeName);
        propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);

        propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);

        Either<List<GraphVertex>, JanusGraphOperationStatus> highestResources = janusGraphDao
            .getByCriteria(null, propertiesToMatch, propertiesNotToMatch, parseFlag);
        if (highestResources.isRight()) {
            JanusGraphOperationStatus status = highestResources.right().value();
            log.debug("failed to find resource with name {}. status={} ", nodeName, status);
            result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
            return result;
        }

        List<GraphVertex> resources = highestResources.left().value();
        double version = 0.0;
        GraphVertex highestResource = null;
        for (GraphVertex vertex : resources) {
            Object versionObj = vertex.getMetadataProperty(GraphPropertyEnum.VERSION);
            double resourceVersion = Double.parseDouble((String) versionObj);
            if (resourceVersion > version) {
                version = resourceVersion;
                highestResource = vertex;
            }
        }
        return getToscaElementByOperation(highestResource, filter);
    }

    // endregion
    // region - Component Get By ..
    private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName) {
        return getLatestByName(property, nodeName, JsonParseFlagEnum.ParseMetadata);
    }

    public <T extends Component> Either<List<T>, StorageOperationStatus> getBySystemName(ComponentTypeEnum componentType, String systemName) {

        Either<List<T>, StorageOperationStatus> result = null;
        Either<T, StorageOperationStatus> getComponentRes;
        List<T> components = new ArrayList<>();
        List<GraphVertex> componentVertices;
        Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
        Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);

        propertiesToMatch.put(GraphPropertyEnum.SYSTEM_NAME, systemName);
        if (componentType != null)
            propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());

        propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);

        Either<List<GraphVertex>, JanusGraphOperationStatus> getComponentsRes = janusGraphDao
            .getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
        if (getComponentsRes.isRight()) {
            JanusGraphOperationStatus status = getComponentsRes.right().value();
            log.debug("Failed to fetch the component with system name {}. Status is {} ", systemName, status);
            result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
        }
        if (result == null) {
            componentVertices = getComponentsRes.left().value();
            for (GraphVertex componentVertex : componentVertices) {
                getComponentRes = getToscaElementByOperation(componentVertex);
                if (getComponentRes.isRight()) {
                    log.debug("Failed to get the component {}. Status is {} ", componentVertex.getJsonMetadataField(JsonPresentationFields.NAME), getComponentRes.right().value());
                    result = Either.right(getComponentRes.right().value());
                    break;
                }
                T componentBySystemName = getComponentRes.left().value();
                log.debug("Found component, id: {}", componentBySystemName.getUniqueId());
                components.add(componentBySystemName);
            }
        }
        if (result == null) {
            result = Either.left(components);
        }
        return result;
    }

    public <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVersion(ComponentTypeEnum componentType, String name, String version) {
        return getComponentByNameAndVersion(componentType, name, version, JsonParseFlagEnum.ParseAll);
    }

    public <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVersion(ComponentTypeEnum componentType, String name, String version, JsonParseFlagEnum parseFlag) {
        Either<T, StorageOperationStatus> result;

        Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
        Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class);

        hasProperties.put(GraphPropertyEnum.NAME, name);
        hasProperties.put(GraphPropertyEnum.VERSION, version);
        hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true);
        if (componentType != null) {
            hasProperties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
        }
        Either<List<GraphVertex>, JanusGraphOperationStatus> getResourceRes = janusGraphDao
            .getByCriteria(null, hasProperties, hasNotProperties, parseFlag);
        if (getResourceRes.isRight()) {
            JanusGraphOperationStatus status = getResourceRes.right().value();
            log.debug("failed to find resource with name {}, version {}. Status is {} ", name, version, status);
            result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
            return result;
        }
        return getToscaElementByOperation(getResourceRes.left().value().get(0));
    }

    public Either<List<CatalogComponent>, StorageOperationStatus> getCatalogOrArchiveComponents(boolean isCatalog, List<OriginTypeEnum> excludeTypes) {
        List<ResourceTypeEnum> excludedResourceTypes = Optional.ofNullable(excludeTypes).orElse(Collections.emptyList()).stream().filter(type -> !type.equals(OriginTypeEnum.SERVICE)).map(type -> ResourceTypeEnum.getTypeByName(type.name()))
                .collect(Collectors.toList());
        return topologyTemplateOperation.getElementCatalogData(isCatalog, excludedResourceTypes);
    }

    // endregion
    public <T extends Component> Either<List<T>, StorageOperationStatus> getCatalogComponents(ComponentTypeEnum componentType, List<OriginTypeEnum> excludeTypes, boolean isHighestVersions) {
        List<T> components = new ArrayList<>();
        Either<List<ToscaElement>, StorageOperationStatus> catalogDataResult;
        List<ToscaElement> toscaElements = new ArrayList<>();
        List<ResourceTypeEnum> excludedResourceTypes = Optional.ofNullable(excludeTypes).orElse(Collections.emptyList()).stream().filter(type -> !type.equals(OriginTypeEnum.SERVICE)).map(type -> ResourceTypeEnum.getTypeByName(type.name()))
                .collect(Collectors.toList());

        switch (componentType) {
            case RESOURCE:
                catalogDataResult = nodeTypeOperation.getElementCatalogData(ComponentTypeEnum.RESOURCE, excludedResourceTypes, isHighestVersions);
                if (catalogDataResult.isRight()) {
                    return Either.right(catalogDataResult.right().value());
                }
                toscaElements = catalogDataResult.left().value();
                break;
            case SERVICE:
                if (excludeTypes != null && excludeTypes.contains(OriginTypeEnum.SERVICE)) {
                    break;
                }
                catalogDataResult = topologyTemplateOperation.getElementCatalogData(ComponentTypeEnum.SERVICE, null, isHighestVersions);
                if (catalogDataResult.isRight()) {
                    return Either.right(catalogDataResult.right().value());
                }
                toscaElements = catalogDataResult.left().value();
                break;
            default:
                log.debug(NOT_SUPPORTED_COMPONENT_TYPE, componentType);
                return Either.right(StorageOperationStatus.BAD_REQUEST);
        }
        toscaElements.forEach(te -> {
            T component = ModelConverter.convertFromToscaElement(te);
            components.add(component);
        });
        return Either.left(components);
    }

    public Either<List<String>, StorageOperationStatus> deleteMarkedElements(ComponentTypeEnum componentType) {
        Either<List<GraphVertex>, StorageOperationStatus> allComponentsMarkedForDeletion;
        switch (componentType) {
            case RESOURCE:
                allComponentsMarkedForDeletion = nodeTypeOperation.getAllComponentsMarkedForDeletion(componentType);
                break;
            case SERVICE:
            case PRODUCT:
                allComponentsMarkedForDeletion = topologyTemplateOperation.getAllComponentsMarkedForDeletion(componentType);
                break;
            default:
                log.debug(NOT_SUPPORTED_COMPONENT_TYPE, componentType);
                return Either.right(StorageOperationStatus.BAD_REQUEST);
        }
        if (allComponentsMarkedForDeletion.isRight()) {
            return Either.right(allComponentsMarkedForDeletion.right().value());
        }
        List<GraphVertex> allMarked = allComponentsMarkedForDeletion.left().value();
        return Either.left(checkIfInUseAndDelete(allMarked));
    }

    private List<String> checkIfInUseAndDelete(List<GraphVertex> allMarked) {
        final List<EdgeLabelEnum> forbiddenEdgeLabelEnums = Arrays.asList(EdgeLabelEnum.INSTANCE_OF, EdgeLabelEnum.PROXY_OF, EdgeLabelEnum.ALLOTTED_OF);
        List<String> deleted = new ArrayList<>();

        for (GraphVertex elementV : allMarked) {
            boolean isAllowedToDelete = true;

            for (EdgeLabelEnum edgeLabelEnum : forbiddenEdgeLabelEnums) {
                Either<Edge, JanusGraphOperationStatus> belongingEdgeByCriteria = janusGraphDao
                    .getBelongingEdgeByCriteria(elementV, edgeLabelEnum, null);
                if (belongingEdgeByCriteria.isLeft()) {
                    log.debug("Marked element {} in use. don't delete it", elementV.getUniqueId());
                    isAllowedToDelete = false;
                    break;
                }
            }

            if (isAllowedToDelete) {
                Either<ToscaElement, StorageOperationStatus> deleteToscaElement = deleteToscaElement(elementV);
                if (deleteToscaElement.isRight()) {
                    log.debug("Failed to delete marked element UniqueID {}, Name {}, error {}", elementV.getUniqueId(), elementV.getMetadataProperties().get(GraphPropertyEnum.NAME), deleteToscaElement.right().value());
                    continue;
                }
                deleted.add(elementV.getUniqueId());
            }
        }
        return deleted;
    }

    public Either<List<String>, StorageOperationStatus> getAllComponentsMarkedForDeletion(ComponentTypeEnum componentType) {
        Either<List<GraphVertex>, StorageOperationStatus> allComponentsMarkedForDeletion;
        switch (componentType) {
            case RESOURCE:
                allComponentsMarkedForDeletion = nodeTypeOperation.getAllComponentsMarkedForDeletion(componentType);
                break;
            case SERVICE:
            case PRODUCT:
                allComponentsMarkedForDeletion = topologyTemplateOperation.getAllComponentsMarkedForDeletion(componentType);
                break;
            default:
                log.debug(NOT_SUPPORTED_COMPONENT_TYPE, componentType);
                return Either.right(StorageOperationStatus.BAD_REQUEST);
        }
        if (allComponentsMarkedForDeletion.isRight()) {
            return Either.right(allComponentsMarkedForDeletion.right().value());
        }
        return Either.left(allComponentsMarkedForDeletion.left().value().stream().map(GraphVertex::getUniqueId).collect(Collectors.toList()));
    }

    // region - Component Update
    public Either<ImmutablePair<Component, String>, StorageOperationStatus> addComponentInstanceToTopologyTemplate(Component containerComponent, Component origComponent, ComponentInstance componentInstance, boolean allowDeleted, User user) {

        Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
        Either<ToscaElement, StorageOperationStatus> updateContainerComponentRes = null;
        if (StringUtils.isEmpty(componentInstance.getIcon())) {
            componentInstance.setIcon(origComponent.getIcon());
        }
        String nameToFindForCounter;
        switch (componentInstance.getOriginType()) {
            case ServiceProxy:
                nameToFindForCounter = ValidationUtils.normaliseComponentName(componentInstance.getSourceModelName()) + PROXY_SUFFIX;
                break;
            case ServiceSubstitution:
                nameToFindForCounter = ValidationUtils.normaliseComponentName(componentInstance.getSourceModelName());
                break;
            default: 
        	    nameToFindForCounter = origComponent.getName();
        }
        String nextComponentInstanceCounter = getNextComponentInstanceCounter(containerComponent, nameToFindForCounter);
        Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> addResult = nodeTemplateOperation.addComponentInstanceToTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent),
                ModelConverter.convertToToscaElement(origComponent), nextComponentInstanceCounter, componentInstance, allowDeleted, user);

        if (addResult.isRight()) {
            CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the component instance {} to container component {}. ", componentInstance.getName(), containerComponent.getName());
            result = Either.right(addResult.right().value());
        }
        if (result == null) {
            updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponent.getUniqueId());
            if (updateContainerComponentRes.isRight()) {
                CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} with updated component instance {}. ", containerComponent.getName(), componentInstance.getName());
                result = Either.right(updateContainerComponentRes.right().value());
            }
        }
        if (result == null) {
            Component updatedComponent = ModelConverter.convertFromToscaElement(updateContainerComponentRes.left().value());
            String createdInstanceId = addResult.left().value().getRight();
            CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been added to container component {}. ", createdInstanceId, updatedComponent.getName());
            result = Either.left(new ImmutablePair<>(updatedComponent, createdInstanceId));
        }
        return result;
    }

    public void associateComponentInstancesToComponent(Component containerComponent, Map<ComponentInstance, Resource> resourcesInstancesMap, boolean allowDeleted, boolean isUpdateCsar) {
        CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Going to add component instances to component {}", containerComponent.getUniqueId());

        Either<GraphVertex, JanusGraphOperationStatus> metadataVertex = janusGraphDao
            .getVertexById(containerComponent.getUniqueId(), JsonParseFlagEnum.ParseAll);
        if (metadataVertex.isRight()) {
            JanusGraphOperationStatus status = metadataVertex.right().value();
            if (status == JanusGraphOperationStatus.NOT_FOUND) {
                status = JanusGraphOperationStatus.INVALID_ID;
            }
            throw new StorageException(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
        }

        Map<String, ComponentInstanceDataDefinition> compnentInstancesMap = nodeTemplateOperation.associateComponentInstancesToComponent(containerComponent, resourcesInstancesMap, metadataVertex.left().value(), allowDeleted, isUpdateCsar);

        containerComponent.setComponentInstances(ModelConverter.getComponentInstancesFromMapObject(compnentInstancesMap, containerComponent));

    }

    public Either<ImmutablePair<Component, String>, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent, Component origComponent, ComponentInstance componentInstance) {

        Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;

        CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(), containerComponent.getName());
        componentInstance.setIcon(origComponent.getIcon());
        Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> updateResult = nodeTemplateOperation.updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent),
                ModelConverter.convertToToscaElement(origComponent), componentInstance);
        if (updateResult.isRight()) {
            CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(), containerComponent.getName());
            result = Either.right(updateResult.right().value());
        }
        if (result == null) {
            Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value().getLeft());
            String createdInstanceId = updateResult.left().value().getRight();
            CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The metadata of the component instance {} has been updated to container component {}. ", createdInstanceId, updatedComponent.getName());
            result = Either.left(new ImmutablePair<>(updatedComponent, createdInstanceId));
        }
        return result;
    }

    public Either<Component, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent) {
        return updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, new ComponentParametersView());
    }

    public Either<Component, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent, ComponentParametersView filter) {

        Either<Component, StorageOperationStatus> result = null;

        CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update the metadata  belonging to container component {}. ", containerComponent.getName());

        Either<TopologyTemplate, StorageOperationStatus> updateResult = nodeTemplateOperation.updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), filter);
        if (updateResult.isRight()) {
            CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the metadata  belonging to container component {}. ", containerComponent.getName());
            result = Either.right(updateResult.right().value());
        }
        if (result == null) {
            Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value());
            CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The metadata has been updated to container component {}. ", updatedComponent.getName());
            result = Either.left(updatedComponent);
        }
        return result;
    }
    // endregion

    public Either<ImmutablePair<Component, String>, StorageOperationStatus> deleteComponentInstanceFromTopologyTemplate(Component containerComponent, String resourceInstanceId) {

        Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;

        CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to delete the component instance {} belonging to container component {}. ", resourceInstanceId, containerComponent.getName());

        Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> updateResult = nodeTemplateOperation.deleteComponentInstanceFromTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), resourceInstanceId);
        if (updateResult.isRight()) {
            CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete the component instance {} belonging to container component {}. ", resourceInstanceId, containerComponent.getName());
            result = Either.right(updateResult.right().value());
        }
        if (result == null) {
            Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value().getLeft());
            String deletedInstanceId = updateResult.left().value().getRight();
            CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been deleted from container component {}. ", deletedInstanceId, updatedComponent.getName());
            result = Either.left(new ImmutablePair<>(updatedComponent, deletedInstanceId));
        }
        return result;
    }

    private String getNextComponentInstanceCounter(Component containerComponent, String originResourceName) {
        Integer nextCounter = 0;
        if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) {
            String normalizedName = ValidationUtils.normalizeComponentInstanceName(originResourceName);
            Integer maxCounter = getMaxCounterFromNamesAndIds(containerComponent, normalizedName);
            if (maxCounter != null) {
                nextCounter = maxCounter + 1;
            }
        }
        return nextCounter.toString();
    }

    /**
     * @return max counter of component instance Id's, null if not found
     */
    private Integer getMaxCounterFromNamesAndIds(Component containerComponent, String normalizedName) {
        List<String> countersInNames = containerComponent.getComponentInstances().stream()
                .filter(ci -> ci.getNormalizedName() != null && ci.getNormalizedName().startsWith(normalizedName))
                .map(ci -> ci.getNormalizedName().split(normalizedName)[1])
                .collect(Collectors.toList());
        List<String> countersInIds = containerComponent.getComponentInstances().stream()
                .filter(ci -> ci.getUniqueId() != null && ci.getUniqueId().contains(normalizedName))
                .map(ci -> ci.getUniqueId().split(normalizedName)[1])
                .collect(Collectors.toList());
        List<String> namesAndIdsList = new ArrayList<>(countersInNames);
        namesAndIdsList.addAll(countersInIds);
        return getMaxInteger(namesAndIdsList);
    }

    private Integer getMaxInteger(List<String> counters) {
        Integer maxCounter = 0;
        Integer currCounter = null;
        for (String counter : counters) {
            try {
                currCounter = Integer.parseInt(counter);
                if (maxCounter < currCounter) {
                    maxCounter = currCounter;
                }
            } catch (NumberFormatException e) {
                continue;
            }
        }
        return currCounter == null ? null : maxCounter;
    }

    public Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances(Component component, String componentId, RequirementCapabilityRelDef requirementDef) {
        return nodeTemplateOperation.associateResourceInstances(component, componentId, requirementDef);

    }

    public Either<List<InputDefinition>, StorageOperationStatus> createAndAssociateInputs(Map<String, InputDefinition> inputs, String componentId) {

        Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
            .getVertexById(componentId, JsonParseFlagEnum.NoParse);
        if (getVertexEither.isRight()) {
            log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
            return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));

        }

        GraphVertex vertex = getVertexEither.left().value();
        Map<String, PropertyDataDefinition> inputsMap = inputs.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDataDefinition(e.getValue())));

        StorageOperationStatus status = topologyTemplateOperation.associateInputsToComponent(vertex, inputsMap, componentId);

        if (StorageOperationStatus.OK == status) {
            log.debug(COMPONENT_CREATED_SUCCESSFULLY);
            List<InputDefinition> inputsResList = null;
            if (inputsMap != null && !inputsMap.isEmpty()) {
                inputsResList = inputsMap.values().stream()
                        .map(InputDefinition::new)
                        .collect(Collectors.toList());
            }
            return Either.left(inputsResList);
        }
        return Either.right(status);

    }

    public Either<List<InputDefinition>, StorageOperationStatus> addInputsToComponent(Map<String, InputDefinition> inputs, String componentId) {

        Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
            .getVertexById(componentId, JsonParseFlagEnum.NoParse);
        if (getVertexEither.isRight()) {
            log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
            return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));

        }

        GraphVertex vertex = getVertexEither.left().value();
		Map<String, PropertyDefinition> inputsMap = inputs.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDefinition(e.getValue())));

        StorageOperationStatus status = topologyTemplateOperation.addToscaDataToToscaElement(vertex, EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputsMap, JsonPresentationFields.NAME);

        if (StorageOperationStatus.OK == status) {
            log.debug(COMPONENT_CREATED_SUCCESSFULLY);
            List<InputDefinition> inputsResList = null;
            if (inputsMap != null && !inputsMap.isEmpty()) {
                inputsResList = inputsMap.values().stream().map(InputDefinition::new).collect(Collectors.toList());
            }
            return Either.left(inputsResList);
        }
        return Either.right(status);

    }

    /**
     * Add data types into a Component.
     *
     * @param dataTypes   datatypes to be added. the key should be each name of data type.
     * @param componentId unique ID of Component.
     * @return list of data types.
     */
    public Either<List<DataTypeDefinition>, StorageOperationStatus> addDataTypesToComponent(Map<String, DataTypeDefinition> dataTypes, String componentId) {

        log.trace("#addDataTypesToComponent - enter, componentId={}", componentId);

        /* get component vertex */
        Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
            .getVertexById(componentId, JsonParseFlagEnum.NoParse);
        if (getVertexEither.isRight()) {
            /* not found / error */
            log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
            return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
        }
        GraphVertex vertex = getVertexEither.left().value();
        log.trace("#addDataTypesToComponent - get vertex ok");

        // convert DataTypeDefinition to DataTypeDataDefinition
        Map<String, DataTypeDataDefinition> dataTypeDataMap = dataTypes.entrySet().stream()
                .collect(Collectors.toMap(Map.Entry::getKey, e -> convertDataTypeToDataTypeData(e.getValue())));

        // add datatype(s) to the Component.
        // if child vertex does not exist, it will be created.
        StorageOperationStatus status = topologyTemplateOperation.addToscaDataToToscaElement(vertex,
                EdgeLabelEnum.DATA_TYPES, VertexTypeEnum.DATA_TYPES, dataTypeDataMap, JsonPresentationFields.NAME);

        if (StorageOperationStatus.OK == status) {
            log.debug(COMPONENT_CREATED_SUCCESSFULLY);
            List<DataTypeDefinition> inputsResList = null;
            if (!dataTypes.isEmpty()) {
                inputsResList = new ArrayList<>(dataTypes.values());
            }
            return Either.left(inputsResList);
        }

        log.trace("#addDataTypesToComponent - leave");
        return Either.right(status);
    }

    private DataTypeDataDefinition convertDataTypeToDataTypeData(DataTypeDefinition dataType) {
        DataTypeDataDefinition dataTypeData = new DataTypeDataDefinition(dataType);
        if (CollectionUtils.isNotEmpty(dataType.getProperties())) {
            List<PropertyDataDefinition> propertyDataList = dataType.getProperties().stream()
                    .map(PropertyDataDefinition::new).collect(Collectors.toList());
            dataTypeData.setPropertiesData(propertyDataList);
        }

        // if "derivedFrom" data_type exists, copy the name to "derivedFromName"
        if (dataType.getDerivedFrom() != null && StringUtils.isNotEmpty(dataType.getDerivedFrom().getName())) {
            // if names are different, log it
            if (!StringUtils.equals(dataTypeData.getDerivedFromName(), dataType.getDerivedFrom().getName())) {
                log.debug("#convertDataTypeToDataTypeData - derivedFromName(={}) overwritten by derivedFrom.name(={})",
                        dataType.getDerivedFromName(), dataType.getDerivedFrom().getName());
            }
            dataTypeData.setDerivedFromName(dataType.getDerivedFrom().getName());
        }

        // supply "name" field to toscaPresentationValue in each datatype object for DAO operations
        dataTypeData.setToscaPresentationValue(JsonPresentationFields.NAME, dataType.getName());
        return dataTypeData;
    }


    public Either<List<InputDefinition>, StorageOperationStatus> getComponentInputs(String componentId) {

		Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
        .getVertexById(componentId, JsonParseFlagEnum.NoParse);
		if (getVertexEither.isRight()) {
			log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
			return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));

		}

		Either<ToscaElement, StorageOperationStatus> toscaElement =
				topologyTemplateOperation.getToscaElement(componentId);
		if(toscaElement.isRight()) {
			return Either.right(toscaElement.right().value());
		}

		TopologyTemplate topologyTemplate = (TopologyTemplate) toscaElement.left().value();

		Map<String, PropertyDataDefinition> inputsMap = topologyTemplate.getInputs();

		List<InputDefinition> inputs = new ArrayList<>();
		if(MapUtils.isNotEmpty(inputsMap)) {
			inputs =
					inputsMap.values().stream().map(p -> new InputDefinition(p)).collect(Collectors.toList());
		}

		return Either.left(inputs);
	}

	public Either<List<InputDefinition>, StorageOperationStatus> updateInputsToComponent(List<InputDefinition> inputs, String componentId) {

        Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
            .getVertexById(componentId, JsonParseFlagEnum.NoParse);
        if (getVertexEither.isRight()) {
            log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
            return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));

        }

        GraphVertex vertex = getVertexEither.left().value();
        List<PropertyDataDefinition> inputsAsDataDef = inputs.stream().map(PropertyDataDefinition::new).collect(Collectors.toList());

        StorageOperationStatus status = topologyTemplateOperation.updateToscaDataOfToscaElement(vertex, EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputsAsDataDef, JsonPresentationFields.NAME);

        if (StorageOperationStatus.OK == status) {
            log.debug(COMPONENT_CREATED_SUCCESSFULLY);
            List<InputDefinition> inputsResList = null;
            if (inputsAsDataDef != null && !inputsAsDataDef.isEmpty()) {
                inputsResList = inputsAsDataDef.stream().map(InputDefinition::new).collect(Collectors.toList());
            }
            return Either.left(inputsResList);
        }
        return Either.right(status);

    }

    // region - ComponentInstance
    public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> associateComponentInstancePropertiesToComponent(Map<String, List<ComponentInstanceProperty>> instProperties, String componentId) {

        Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
            .getVertexById(componentId, JsonParseFlagEnum.NoParse);
        if (getVertexEither.isRight()) {
            log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
            return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));

        }

        GraphVertex vertex = getVertexEither.left().value();
        Map<String, MapPropertiesDataDefinition> instPropsMap = new HashMap<>();
        if (instProperties != null) {

            MapPropertiesDataDefinition propertiesMap;
            for (Entry<String, List<ComponentInstanceProperty>> entry : instProperties.entrySet()) {
                propertiesMap = new MapPropertiesDataDefinition();

                propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, e -> e)));

                instPropsMap.put(entry.getKey(), propertiesMap);
            }
        }

        StorageOperationStatus status = topologyTemplateOperation.associateInstPropertiesToComponent(vertex, instPropsMap);

        if (StorageOperationStatus.OK == status) {
            log.debug(COMPONENT_CREATED_SUCCESSFULLY);
            return Either.left(instProperties);
        }
        return Either.right(status);

    }

    /**
     * saves the instInputs as the updated instance inputs of the component container in DB
     */
    public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> updateComponentInstanceInputsToComponent(Map<String, List<ComponentInstanceInput>> instInputs, String componentId) {
        if (instInputs == null || instInputs.isEmpty()) {
            return Either.left(instInputs);
        }
        StorageOperationStatus status;
        for (Entry<String, List<ComponentInstanceInput>> inputsPerIntance : instInputs.entrySet()) {
            List<ComponentInstanceInput> toscaDataListPerInst = inputsPerIntance.getValue();
            List<String> pathKeysPerInst = new ArrayList<>();
            pathKeysPerInst.add(inputsPerIntance.getKey());
            status = topologyTemplateOperation.updateToscaDataDeepElementsOfToscaElement(componentId, EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, toscaDataListPerInst, pathKeysPerInst, JsonPresentationFields.NAME);
            if (status != StorageOperationStatus.OK) {
                log.debug("Failed to update component instance inputs for instance {} in component {} edge type {} error {}", inputsPerIntance.getKey(), componentId, EdgeLabelEnum.INST_INPUTS, status);
                return Either.right(status);
            }
        }

        return Either.left(instInputs);
    }

    /**
     * saves the instProps as the updated instance properties of the component container in DB
     */
    public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> updateComponentInstancePropsToComponent(Map<String, List<ComponentInstanceProperty>> instProps, String componentId) {
        if (instProps == null || instProps.isEmpty()) {
            return Either.left(instProps);
        }
        StorageOperationStatus status;
        for (Entry<String, List<ComponentInstanceProperty>> propsPerIntance : instProps.entrySet()) {
            List<ComponentInstanceProperty> toscaDataListPerInst = propsPerIntance.getValue();
            List<String> pathKeysPerInst = new ArrayList<>();
            pathKeysPerInst.add(propsPerIntance.getKey());
            status = topologyTemplateOperation.updateToscaDataDeepElementsOfToscaElement(componentId, EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, toscaDataListPerInst, pathKeysPerInst, JsonPresentationFields.NAME);
            if (status != StorageOperationStatus.OK) {
                log.debug("Failed to update component instance inputs for instance {} in component {} edge type {} error {}", propsPerIntance.getKey(), componentId, EdgeLabelEnum.INST_PROPERTIES, status);
                return Either.right(status);
            }
        }

        return Either.left(instProps);
    }

    public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> associateComponentInstanceInputsToComponent(Map<String, List<ComponentInstanceInput>> instInputs, String componentId) {

        Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
            .getVertexById(componentId, JsonParseFlagEnum.NoParse);
        if (getVertexEither.isRight()) {
            log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
            return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));

        }
        GraphVertex vertex = getVertexEither.left().value();
        Map<String, MapPropertiesDataDefinition> instPropsMap = new HashMap<>();
        if (instInputs != null) {

            MapPropertiesDataDefinition propertiesMap;
            for (Entry<String, List<ComponentInstanceInput>> entry : instInputs.entrySet()) {
                propertiesMap = new MapPropertiesDataDefinition();

                propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, e -> e)));

                instPropsMap.put(entry.getKey(), propertiesMap);
            }
        }

        StorageOperationStatus status = topologyTemplateOperation.associateInstInputsToComponent(vertex, instPropsMap);

        if (StorageOperationStatus.OK == status) {
            log.debug(COMPONENT_CREATED_SUCCESSFULLY);
            return Either.left(instInputs);
        }
        return Either.right(status);

    }

    public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addComponentInstanceInputsToComponent(Component containerComponent, Map<String, List<ComponentInstanceInput>> instProperties) {
        requireNonNull(instProperties);
        StorageOperationStatus status;
        for (Entry<String, List<ComponentInstanceInput>> entry : instProperties.entrySet()) {
            List<ComponentInstanceInput> props = entry.getValue();
            String componentInstanceId = entry.getKey();
            if (!isEmpty(props)) {
                for (ComponentInstanceInput property : props) {
                    List<ComponentInstanceInput> componentInstancesInputs = containerComponent.getComponentInstancesInputs().get(componentInstanceId);
                    Optional<ComponentInstanceInput> instanceProperty = componentInstancesInputs.stream()
                            .filter(p -> p.getName().equals(property.getName()))
                            .findAny();
                    if (instanceProperty.isPresent()) {
                        status = updateComponentInstanceInput(containerComponent, componentInstanceId, property);
                    } else {
                        status = addComponentInstanceInput(containerComponent, componentInstanceId, property);
                    }
                    if (status != StorageOperationStatus.OK) {
                        log.debug("Failed to update instance input {} for instance {} error {} ", property, componentInstanceId, status);
                        return Either.right(status);
                    } else {
                        log.trace("instance input {} for instance {} updated", property, componentInstanceId);
                    }
                }
            }
        }
        return Either.left(instProperties);
    }

    public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addComponentInstancePropertiesToComponent(Component containerComponent, Map<String, List<ComponentInstanceProperty>> instProperties) {
        requireNonNull(instProperties);
        for (Entry<String, List<ComponentInstanceProperty>> entry : instProperties.entrySet()) {
            List<ComponentInstanceProperty> props = entry.getValue();
            String componentInstanceId = entry.getKey();
            List<ComponentInstanceProperty> originalComponentInstProps =
                containerComponent.getComponentInstancesProperties().get(componentInstanceId);
            Map<String, List<CapabilityDefinition>> containerComponentCapabilities = containerComponent.getCapabilities();

            if(isEmpty(props)) {
                continue;
            }
            for (ComponentInstanceProperty property : props) {
                StorageOperationStatus status = null;
                String propertyParentUniqueId = property.getParentUniqueId();
                Optional<CapabilityDefinition>
                        capPropDefinition = getPropertyCapability(propertyParentUniqueId, containerComponent);
                if(capPropDefinition.isPresent() && MapUtils.isNotEmpty(containerComponentCapabilities)) {
                    status = populateAndUpdateInstanceCapProperty(containerComponent, componentInstanceId,
                            containerComponentCapabilities, property, capPropDefinition.get());
                }
                if(status == null) {
                    status = updateOrAddComponentInstanceProperty(containerComponent, componentInstanceId,
                        originalComponentInstProps, property);
                }
                if(status != StorageOperationStatus.OK) {
                    return Either.right(status);
                }
            }
        }
        return Either.left(instProperties);
    }

    private StorageOperationStatus populateAndUpdateInstanceCapProperty(Component containerComponent, String componentInstanceId,
                                                                        Map<String, List<CapabilityDefinition>> containerComponentCapabilities,
                                                                        ComponentInstanceProperty property,
                                                                        CapabilityDefinition capabilityDefinition) {
        List<CapabilityDefinition> capabilityDefinitions = containerComponentCapabilities.get(capabilityDefinition.getType());
        if(CollectionUtils.isEmpty(capabilityDefinitions)) {
            return null;
        }
        Optional<CapabilityDefinition> capDefToGetProp = capabilityDefinitions.stream()
                .filter(cap -> cap.getUniqueId().equals(capabilityDefinition.getUniqueId()) && cap.getPath().size() == 1).findAny();
        if(capDefToGetProp.isPresent()) {
            return updateInstanceCapabilityProperty(containerComponent, componentInstanceId, property, capDefToGetProp.get());
        }
        return null;
    }

    private static Optional<CapabilityDefinition> getPropertyCapability(String propertyParentUniqueId,
                                                                        Component containerComponent) {

        Map<String, List<CapabilityDefinition>> componentCapabilities = containerComponent.getCapabilities();
        if(MapUtils.isEmpty(componentCapabilities)){
            return Optional.empty();
        }
        List<CapabilityDefinition> capabilityDefinitionList = componentCapabilities.values()
                .stream().flatMap(Collection::stream).collect(Collectors.toList());
        if(CollectionUtils.isEmpty(capabilityDefinitionList)){
            return Optional.empty();
        }
        return capabilityDefinitionList.stream()
                .filter(capabilityDefinition -> capabilityDefinition.getUniqueId().equals(propertyParentUniqueId))
                .findAny();
    }

    private StorageOperationStatus updateOrAddComponentInstanceProperty(Component containerComponent,
        String componentInstanceId, List<ComponentInstanceProperty> originalComponentInstProps,
        ComponentInstanceProperty property)
    {
        StorageOperationStatus status;
        // check if the property already exists or not
        Optional<ComponentInstanceProperty> instanceProperty = originalComponentInstProps.stream()
                .filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
        if (instanceProperty.isPresent()) {
            status = updateComponentInstanceProperty(containerComponent, componentInstanceId, property);
        } else {
            status = addComponentInstanceProperty(containerComponent, componentInstanceId, property);
        }
        if (status != StorageOperationStatus.OK) {
            log.debug("Failed to update instance property {} for instance {} error {} ",
                property, componentInstanceId, status);
        }
        return status;
    }

    public StorageOperationStatus updateInstanceCapabilityProperty(Component containerComponent, String componentInstanceId,
                                                                   ComponentInstanceProperty property,
                                                                   CapabilityDefinition capabilityDefinition) {
        Optional<ComponentInstance> fetchedCIOptional = containerComponent.getComponentInstanceById(componentInstanceId);
        if(!fetchedCIOptional.isPresent()) {
            return StorageOperationStatus.GENERAL_ERROR;
        }
        Either<Component, StorageOperationStatus> getComponentRes =
                getToscaFullElement(fetchedCIOptional.get().getComponentUid());
        if(getComponentRes.isRight()) {
            return StorageOperationStatus.GENERAL_ERROR;
        }
        Optional<Component> componentOptional = isNodeServiceProxy(getComponentRes.left().value());
        String propOwner;
        if(!componentOptional.isPresent()) {
            propOwner = componentInstanceId;
        } else {
            propOwner = fetchedCIOptional.get().getSourceModelUid();
        }
        StorageOperationStatus status;
        StringBuilder sb = new StringBuilder(componentInstanceId);
        sb.append(ModelConverter.CAP_PROP_DELIM).append(propOwner).append(ModelConverter.CAP_PROP_DELIM)
                .append(capabilityDefinition.getType()).append(ModelConverter.CAP_PROP_DELIM).append(capabilityDefinition.getName());
        String capKey = sb.toString();
        status = updateComponentInstanceCapabiltyProperty(containerComponent, componentInstanceId, capKey, property);
        if (status != StorageOperationStatus.OK) {
            log.debug("Failed to update instance capability property {} for instance {} error {} ", property,
                    componentInstanceId, status);
            return status;
        }
        return StorageOperationStatus.OK;
    }

    private Optional<Component> isNodeServiceProxy(Component component) {
        if (component.getComponentType().equals(ComponentTypeEnum.SERVICE)) {
            return Optional.empty();
        }
        Resource resource = (Resource) component;
        ResourceTypeEnum resType = resource.getResourceType();
        if(resType.equals(ResourceTypeEnum.ServiceProxy))  {
            return Optional.of(component);
        }
        return Optional.empty();
    }

    public StorageOperationStatus associateCapabilitiesToService(Map<String,ListCapabilityDataDefinition> capabilities, String componentId) {

        Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
        if (getVertexEither.isRight()) {
            log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
            return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value());

        }

        GraphVertex vertex = getVertexEither.left().value();
        if(MapUtils.isNotEmpty(capabilities)) {
            Either<GraphVertex, StorageOperationStatus> associateElementToData = topologyTemplateOperation.
                    associateElementToData(vertex, VertexTypeEnum.CAPABILITIES,
                            EdgeLabelEnum.CAPABILITIES, capabilities);
            if (associateElementToData.isRight()) {
                return associateElementToData.right().value();
            }
        }


        return StorageOperationStatus.OK;

    }

    public StorageOperationStatus associateRequirementsToService(Map<String, ListRequirementDataDefinition> requirements, String componentId) {

        Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
        if (getVertexEither.isRight()) {
            log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
            return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value());

        }

        GraphVertex vertex = getVertexEither.left().value();
        if(MapUtils.isNotEmpty(requirements)) {
            Either<GraphVertex, StorageOperationStatus> associateElementToData = topologyTemplateOperation.
                    associateElementToData(vertex, VertexTypeEnum.REQUIREMENTS,
                            EdgeLabelEnum.REQUIREMENTS, requirements);
            if (associateElementToData.isRight()) {
                return associateElementToData.right().value();
            }
        }

        return StorageOperationStatus.OK;

    }
	
    public StorageOperationStatus associateDeploymentArtifactsToInstances(Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts, Component component, User user) {

        Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse);
        if (getVertexEither.isRight()) {
            log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, component.getUniqueId(), getVertexEither.right().value());
            return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value());

        }

        GraphVertex vertex = getVertexEither.left().value();
        Map<String, MapArtifactDataDefinition> instArtMap = new HashMap<>();
        if (instDeploymentArtifacts != null) {

            MapArtifactDataDefinition artifactsMap;
            for (Entry<String, Map<String, ArtifactDefinition>> entry : instDeploymentArtifacts.entrySet()) {
                Map<String, ArtifactDefinition> artList = entry.getValue();
                Map<String, ArtifactDataDefinition> artifacts = artList.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
                artifactsMap = nodeTemplateOperation.prepareInstDeploymentArtifactPerInstance(artifacts, entry.getKey(), user, NodeTemplateOperation.HEAT_VF_ENV_NAME);

                instArtMap.put(entry.getKey(), artifactsMap);
            }
        }
        ModelConverter.setComponentInstancesDeploymentArtifactsToComponent(instArtMap, component);
        return topologyTemplateOperation.associateInstDeploymentArtifactsToComponent(vertex, instArtMap);
    }

    public StorageOperationStatus associateArtifactsToInstances(Map<String, Map<String, ArtifactDefinition>> instArtifacts, Component component) {

        Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse);
        if (getVertexEither.isRight()) {
            log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, component.getUniqueId(), getVertexEither.right().value());
            return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value());

        }

        GraphVertex vertex = getVertexEither.left().value();
        Map<String, MapArtifactDataDefinition> instArtMap = new HashMap<>();
        if (instArtifacts != null) {

            MapArtifactDataDefinition artifactsMap;
            for (Entry<String, Map<String, ArtifactDefinition>> entry : instArtifacts.entrySet()) {
                Map<String, ArtifactDefinition> artList = entry.getValue();
                Map<String, ArtifactDataDefinition> artifacts = artList.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
                artifactsMap = new MapArtifactDataDefinition(artifacts);

                instArtMap.put(entry.getKey(), artifactsMap);
            }
        }
        ModelConverter.setComponentInstancesInformationalArtifactsToComponent(instArtMap, component);
        return topologyTemplateOperation.associateInstArtifactsToComponent(vertex, instArtMap);

    }

    public StorageOperationStatus associateInstAttributeToComponentToInstances(Map<String, List<AttributeDataDefinition>> instArttributes, Component component) {

        Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse);
        if (getVertexEither.isRight()) {
            log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, component.getUniqueId(), getVertexEither.right().value());
            return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value());

        }

        GraphVertex vertex = getVertexEither.left().value();
        Map<String, MapAttributesDataDefinition> instAttr = new HashMap<>();
        if (instArttributes != null) {

            MapAttributesDataDefinition attributesMap;
            for (Entry<String, List<AttributeDataDefinition>> entry : instArttributes.entrySet()) {
                final List<AttributeDataDefinition> value = entry.getValue();
                attributesMap = new MapAttributesDataDefinition();
                attributesMap.setMapToscaDataDefinition(value.stream().map(AttributeDataDefinition::new).collect(Collectors.toMap(AttributeDataDefinition::getName, e -> e)));
                instAttr.put(entry.getKey(), attributesMap);
            }
        }
        setComponentInstanceAttributesOnComponent(component, instAttr);
        return topologyTemplateOperation.associateInstAttributeToComponent(vertex, instAttr);
    }
    // endregion

    private void setComponentInstanceAttributesOnComponent(Component resource, Map<String, MapAttributesDataDefinition> instAttr) {
        Map<String, List<ComponentInstanceAttribute>> componentInstancesAttributes = resource.getComponentInstancesAttributes();
        if (componentInstancesAttributes == null)
            componentInstancesAttributes = new HashMap<>();
        componentInstancesAttributes.putAll(ModelConverter.getComponentInstancesAttributes(instAttr));
        resource.setComponentInstancesAttributes(componentInstancesAttributes);
    }

    public StorageOperationStatus associateOrAddCalculatedCapReq(Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties, Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instReg, Component component) {
        Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse);
        if (getVertexEither.isRight()) {
            log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, component.getUniqueId(), getVertexEither.right().value());
            return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value());

        }

        GraphVertex vertex = getVertexEither.left().value();

        Map<String, MapListRequirementDataDefinition> calcRequirements = new HashMap<>();

        Map<String, MapListCapabilityDataDefinition> calcCapabilty = new HashMap<>();
        Map<String, MapCapabilityProperty> calculatedCapabilitiesProperties = new HashMap<>();
        if (instCapabilties != null) {
            for (Entry<ComponentInstance, Map<String, List<CapabilityDefinition>>> entry : instCapabilties.entrySet()) {

                Map<String, List<CapabilityDefinition>> caps = entry.getValue();
                Map<String, ListCapabilityDataDefinition> mapToscaDataDefinition = new HashMap<>();
                for (Entry<String, List<CapabilityDefinition>> instCapability : caps.entrySet()) {
                    mapToscaDataDefinition.put(instCapability.getKey(), new ListCapabilityDataDefinition(instCapability.getValue().stream().map(CapabilityDataDefinition::new).collect(Collectors.toList())));
                }

                ComponentInstanceDataDefinition componentInstance = new ComponentInstanceDataDefinition(entry.getKey());
                MapListCapabilityDataDefinition capMap = nodeTemplateOperation.prepareCalculatedCapabiltyForNodeType(mapToscaDataDefinition, componentInstance);

                MapCapabilityProperty mapCapabilityProperty = ModelConverter.convertToMapOfMapCapabiltyProperties(caps, componentInstance.getUniqueId(), true);

                calcCapabilty.put(entry.getKey().getUniqueId(), capMap);
                calculatedCapabilitiesProperties.put(entry.getKey().getUniqueId(), mapCapabilityProperty);
            }
        }

        if (instReg != null) {
            for (Entry<ComponentInstance, Map<String, List<RequirementDefinition>>> entry : instReg.entrySet()) {

                Map<String, List<RequirementDefinition>> req = entry.getValue();
                Map<String, ListRequirementDataDefinition> mapToscaDataDefinition = new HashMap<>();
                for (Entry<String, List<RequirementDefinition>> instReq : req.entrySet()) {
                    mapToscaDataDefinition.put(instReq.getKey(), new ListRequirementDataDefinition(instReq.getValue().stream().map(RequirementDataDefinition::new).collect(Collectors.toList())));
                }

                MapListRequirementDataDefinition reqMap = nodeTemplateOperation.prepareCalculatedRequirementForNodeType(mapToscaDataDefinition, new ComponentInstanceDataDefinition(entry.getKey()));

                String componentInstanceId = entry.getKey().getUniqueId();
                calcRequirements.put(componentInstanceId, reqMap);
            }
        }

        StorageOperationStatus storageOperationStatus = topologyTemplateOperation.associateOrAddCalcCapReqToComponent(vertex, calcRequirements, calcCapabilty, calculatedCapabilitiesProperties);
        updateInstancesCapAndReqOnComponentFromDB(component);
        return storageOperationStatus;
    }

    private void updateInstancesCapAndReqOnComponentFromDB(Component component) {
        ComponentParametersView componentParametersView = new ComponentParametersView(true);
        componentParametersView.setIgnoreCapabilities(false);
        componentParametersView.setIgnoreRequirements(false);
        componentParametersView.setIgnoreCapabiltyProperties(false);
        componentParametersView.setIgnoreComponentInstances(false);
        Either<Component, StorageOperationStatus> componentEither = getToscaElement(component.getUniqueId(), componentParametersView);
        if (componentEither.isRight()) {
            throw new StorageException(StorageOperationStatus.NOT_FOUND);
        }
        Component updatedComponent = componentEither.left().value();
        component.setCapabilities(updatedComponent.getCapabilities());
        component.setRequirements(updatedComponent.getRequirements());
        component.setComponentInstances(updatedComponent.getComponentInstances());
    }

    private Either<List<Service>, StorageOperationStatus> getLatestVersionNonCheckoutServicesMetadataOnly(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps) {
        List<Service> services = new ArrayList<>();
        List<LifecycleStateEnum> states = new ArrayList<>();
        // include props
        hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
        hasProps.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);

        // exclude props
        states.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
        hasNotProps.put(GraphPropertyEnum.STATE, states);
        hasNotProps.put(GraphPropertyEnum.IS_DELETED, true);
        hasNotProps.put(GraphPropertyEnum.IS_ARCHIVED, true);
        return fetchServicesByCriteria(services, hasProps, hasNotProps);
    }

    private Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractToscaElementsMetadataOnly(boolean isAbstract, ComponentTypeEnum componentTypeEnum, String internalComponentType, VertexTypeEnum vertexType) {
        List<Service> services = null;
        Map<GraphPropertyEnum, Object> hasProps = new EnumMap<>(GraphPropertyEnum.class);
        Map<GraphPropertyEnum, Object> hasNotProps = new EnumMap<>(GraphPropertyEnum.class);
        fillPropsMap(hasProps, hasNotProps, internalComponentType, componentTypeEnum, isAbstract, vertexType);
        Either<List<GraphVertex>, JanusGraphOperationStatus> getRes = janusGraphDao
            .getByCriteria(vertexType, hasProps, hasNotProps, JsonParseFlagEnum.ParseMetadata);
        if (getRes.isRight()) {
            if (getRes.right().value().equals(JanusGraphOperationStatus.NOT_FOUND)) {
                return Either.left(new ArrayList<>());
            } else {
                return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getRes.right().value()));
            }
        }
        // region -> Fetch non checked-out services
        if (internalComponentType != null && internalComponentType.toLowerCase().trim().equals(SERVICE) && VertexTypeEnum.NODE_TYPE == vertexType) {
            Either<List<Service>, StorageOperationStatus> result = getLatestVersionNonCheckoutServicesMetadataOnly(new EnumMap<>(GraphPropertyEnum.class), new EnumMap<>(GraphPropertyEnum.class));
            if (result.isRight()) {
                log.debug("Failed to fetch services for");
                return Either.right(result.right().value());
            }
            services = result.left().value();
            if (log.isTraceEnabled() && isEmpty(services))
                log.trace("No relevant services available");
        }
        // endregion
        List<Component> nonAbstractLatestComponents = new ArrayList<>();
        ComponentParametersView params = new ComponentParametersView(true);
        params.setIgnoreAllVersions(false);
        for (GraphVertex vertexComponent : getRes.left().value()) {
            Either<ToscaElement, StorageOperationStatus> componentRes = topologyTemplateOperation.getLightComponent(vertexComponent, componentTypeEnum, params);
            if (componentRes.isRight()) {
                log.debug("Failed to fetch light element for {} error {}", vertexComponent.getUniqueId(), componentRes.right().value());
                return Either.right(componentRes.right().value());
            } else {
                Component component = ModelConverter.convertFromToscaElement(componentRes.left().value());
                nonAbstractLatestComponents.add(component);
            }
        }
        if (CollectionUtils.isNotEmpty(services)) {
            nonAbstractLatestComponents.addAll(services);
        }
        return Either.left(nonAbstractLatestComponents);
    }

    public Either<ComponentMetadataData, StorageOperationStatus> getLatestComponentMetadataByUuid(String componentUuid, JsonParseFlagEnum parseFlag, Boolean isHighest) {

        Either<ComponentMetadataData, StorageOperationStatus> result;
        Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
        hasProperties.put(GraphPropertyEnum.UUID, componentUuid);
        if (isHighest != null) {
            hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, isHighest);
        }
        Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
        propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
        propertiesNotToMatch.put(GraphPropertyEnum.IS_ARCHIVED, true); //US382674, US382683

        Either<List<GraphVertex>, JanusGraphOperationStatus> getRes = janusGraphDao
            .getByCriteria(null, hasProperties, propertiesNotToMatch, parseFlag);
        if (getRes.isRight()) {
            result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getRes.right().value()));
        } else {
            List<ComponentMetadataData> latestVersionList = getRes.left().value().stream().map(ModelConverter::convertToComponentMetadata).collect(Collectors.toList());
            ComponentMetadataData 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();
            result = Either.left(latestVersion);
        }
        return result;
    }

    public Either<ComponentMetadataData, StorageOperationStatus> getComponentMetadata(String componentId) {
        Either<ComponentMetadataData, StorageOperationStatus> result;
        Either<GraphVertex, JanusGraphOperationStatus> getRes = janusGraphDao
            .getVertexById(componentId, JsonParseFlagEnum.ParseMetadata);
        if (getRes.isRight()) {
            result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getRes.right().value()));
        } else {
            ComponentMetadataData componentMetadata = ModelConverter.convertToComponentMetadata(getRes.left().value());
            result = Either.left(componentMetadata);
        }
        return result;
    }

    public Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractComponents(boolean isAbstract, ComponentTypeEnum componentTypeEnum,
                                                                                                 String internalComponentType, List<String> componentUids) {

        List<Component> components = new ArrayList<>();
        if (componentUids == null) {
            Either<List<String>, StorageOperationStatus> componentUidsRes = getComponentUids(isAbstract, componentTypeEnum, internalComponentType);
            if (componentUidsRes.isRight()) {
                return Either.right(componentUidsRes.right().value());
            }
            componentUids = componentUidsRes.left().value();
        }
        if (!isEmpty(componentUids)) {
            for (String componentUid : componentUids) {
                ComponentParametersView componentParametersView = buildComponentViewForNotAbstract();
                if ("vl".equalsIgnoreCase(internalComponentType)) {
                    componentParametersView.setIgnoreCapabilities(false);
                    componentParametersView.setIgnoreRequirements(false);
                }
                Either<ToscaElement, StorageOperationStatus> getToscaElementRes = nodeTemplateOperation.getToscaElementOperation(componentTypeEnum).getLightComponent(componentUid, componentTypeEnum, componentParametersView);
                if (getToscaElementRes.isRight()) {
                    log.debug("Failed to fetch resource for error is {}", getToscaElementRes.right().value());
                    return Either.right(getToscaElementRes.right().value());
                }
                Component component = ModelConverter.convertFromToscaElement(getToscaElementRes.left().value());
                nullifySomeComponentProperties(component);
                components.add(component);
            }
        }
        return Either.left(components);
    }

    public void nullifySomeComponentProperties(Component component) {
        component.setContactId(null);
        component.setCreationDate(null);
        component.setCreatorUserId(null);
        component.setCreatorFullName(null);
        component.setLastUpdateDate(null);
        component.setLastUpdaterUserId(null);
        component.setLastUpdaterFullName(null);
        component.setNormalizedName(null);
    }

    private Either<List<String>, StorageOperationStatus> getComponentUids(boolean isAbstract, ComponentTypeEnum componentTypeEnum, String internalComponentType) {

        Either<List<Component>, StorageOperationStatus> getToscaElementsRes = getLatestVersionNotAbstractMetadataOnly(isAbstract, componentTypeEnum, internalComponentType);
        if (getToscaElementsRes.isRight()) {
            return Either.right(getToscaElementsRes.right().value());
        }
        List<Component> collection = getToscaElementsRes.left().value();
        List<String> componentUids;
        if (collection == null) {
            componentUids = new ArrayList<>();
        } else {
            componentUids = collection.stream()
                    .map(Component::getUniqueId)
                    .collect(Collectors.toList());
        }
        return Either.left(componentUids);
    }

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

    public Either<Boolean, StorageOperationStatus> validateComponentNameExists(String name, ResourceTypeEnum resourceType, ComponentTypeEnum componentType) {
        Either<Boolean, StorageOperationStatus> result = validateComponentNameUniqueness(name, resourceType, componentType);
        if (result.isLeft()) {
            result = Either.left(!result.left().value());
        }
        return result;
    }

    public Either<Boolean, StorageOperationStatus> validateComponentNameUniqueness(String name, ResourceTypeEnum resourceType, ComponentTypeEnum componentType) {
        VertexTypeEnum vertexType = ModelConverter.isAtomicComponent(resourceType) ? VertexTypeEnum.NODE_TYPE : VertexTypeEnum.TOPOLOGY_TEMPLATE;
        String normalizedName = ValidationUtils.normaliseComponentName(name);
        Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
        properties.put(GraphPropertyEnum.NORMALIZED_NAME, normalizedName);
        properties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());

        Either<List<GraphVertex>, JanusGraphOperationStatus> vertexEither = janusGraphDao
            .getByCriteria(vertexType, properties, JsonParseFlagEnum.NoParse);
        if (vertexEither.isRight() && vertexEither.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
            log.debug("failed to get vertex from graph with property normalizedName: {}", normalizedName);
            return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexEither.right().value()));
        }
        List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
        if (vertexList != null && !vertexList.isEmpty()) {
            return Either.left(false);
        } else {
            return Either.left(true);
        }
    }

    private void fillNodeTypePropsMap(final Map<GraphPropertyEnum, Object> hasProps,
                                      final Map<GraphPropertyEnum, Object> hasNotProps,
                                      final String internalComponentType) {
        final Configuration configuration = ConfigurationManager.getConfigurationManager().getConfiguration();
        final List<String> allowedTypes;

        if (ComponentTypeEnum.SERVICE.getValue().equalsIgnoreCase(internalComponentType)) {
            allowedTypes = containerInstanceTypesData.getComponentAllowedList(ComponentTypeEnum.SERVICE, null);
        } else {
            final ResourceTypeEnum resourceType = ResourceTypeEnum.getTypeIgnoreCase(internalComponentType);
            allowedTypes = containerInstanceTypesData.getComponentAllowedList(ComponentTypeEnum.RESOURCE, resourceType);
        }
        final List<String> allResourceTypes = configuration.getResourceTypes();
        if (allowedTypes == null) {
            hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, allResourceTypes);
            return;
        }

        if (ResourceTypeEnum.VL.getValue().equalsIgnoreCase(internalComponentType)) {
            hasProps.put(GraphPropertyEnum.RESOURCE_TYPE, allowedTypes);
        } else {
            final List<String> notAllowedTypes = allResourceTypes.stream().filter(s -> !allowedTypes.contains(s))
                .collect(Collectors.toList());
            hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, notAllowedTypes);
        }
    }

    private void fillTopologyTemplatePropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, ComponentTypeEnum componentTypeEnum) {
        switch (componentTypeEnum) {
            case RESOURCE:
                hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
                break;
            case SERVICE:
                hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
                break;
            default:
                break;
        }
        hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.CVFC.name());
    }

    private void fillPropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, String internalComponentType, ComponentTypeEnum componentTypeEnum, boolean isAbstract, VertexTypeEnum internalVertexType) {
        hasNotProps.put(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name());

        hasNotProps.put(GraphPropertyEnum.IS_DELETED, true);
        hasNotProps.put(GraphPropertyEnum.IS_ARCHIVED, true);
        hasProps.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
        if (VertexTypeEnum.NODE_TYPE == internalVertexType) {
            hasProps.put(GraphPropertyEnum.IS_ABSTRACT, isAbstract);
            if (internalComponentType != null) {
                fillNodeTypePropsMap(hasProps, hasNotProps, internalComponentType);
            }
        } else {
            fillTopologyTemplatePropsMap(hasProps, hasNotProps, componentTypeEnum);
        }
    }

    private List<VertexTypeEnum> getInternalVertexTypes(ComponentTypeEnum componentTypeEnum, String internalComponentType) {
        List<VertexTypeEnum> internalVertexTypes = new ArrayList<>();
        if (ComponentTypeEnum.RESOURCE == componentTypeEnum) {
            internalVertexTypes.add(VertexTypeEnum.NODE_TYPE);
        }
        if (ComponentTypeEnum.SERVICE == componentTypeEnum || SERVICE.equalsIgnoreCase(internalComponentType)) {
            internalVertexTypes.add(VertexTypeEnum.TOPOLOGY_TEMPLATE);
        }
        return internalVertexTypes;
    }

    public Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractMetadataOnly(boolean isAbstract, ComponentTypeEnum componentTypeEnum, String internalComponentType) {
        List<VertexTypeEnum> internalVertexTypes = getInternalVertexTypes(componentTypeEnum, internalComponentType);
        List<Component> result = new ArrayList<>();
        for (VertexTypeEnum vertexType : internalVertexTypes) {
            Either<List<Component>, StorageOperationStatus> listByVertexType = getLatestVersionNotAbstractToscaElementsMetadataOnly(isAbstract, componentTypeEnum, internalComponentType, vertexType);
            if (listByVertexType.isRight()) {
                return listByVertexType;
            }
            result.addAll(listByVertexType.left().value());
        }
        return Either.left(result);

    }

    private Either<List<Component>, StorageOperationStatus> getLatestComponentListByUuid(String componentUuid, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
        Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
        if (additionalPropertiesToMatch != null) {
            propertiesToMatch.putAll(additionalPropertiesToMatch);
        }
        propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
        return getComponentListByUuid(componentUuid, propertiesToMatch);
    }

    public Either<Component, StorageOperationStatus> getComponentByUuidAndVersion(String componentUuid, String version) {
        Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);

        propertiesToMatch.put(GraphPropertyEnum.UUID, componentUuid);
        propertiesToMatch.put(GraphPropertyEnum.VERSION, version);

        Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
        propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
        Either<List<GraphVertex>, JanusGraphOperationStatus> vertexEither = janusGraphDao
            .getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
        if (vertexEither.isRight()) {
            return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexEither.right().value()));
        }

        List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
        if (vertexList == null || vertexList.isEmpty() || vertexList.size() > 1) {
            return Either.right(StorageOperationStatus.NOT_FOUND);
        }

        return getToscaElementByOperation(vertexList.get(0));
    }

    public Either<List<Component>, StorageOperationStatus> getComponentListByUuid(String componentUuid, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {

        Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);

        if (additionalPropertiesToMatch != null) {
            propertiesToMatch.putAll(additionalPropertiesToMatch);
        }

        propertiesToMatch.put(GraphPropertyEnum.UUID, componentUuid);

        Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
        propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
        propertiesNotToMatch.put(GraphPropertyEnum.IS_ARCHIVED, true); //US382674, US382683

        Either<List<GraphVertex>, JanusGraphOperationStatus> vertexEither = janusGraphDao
            .getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);

        if (vertexEither.isRight()) {
            log.debug("Couldn't fetch metadata for component with uuid {}, error: {}", componentUuid, vertexEither.right().value());
            return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexEither.right().value()));
        }
        List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;

        if (vertexList == null || vertexList.isEmpty()) {
            log.debug("Component with uuid {} was not found", componentUuid);
            return Either.right(StorageOperationStatus.NOT_FOUND);
        }

        ArrayList<Component> latestComponents = new ArrayList<>();
        for (GraphVertex vertex : vertexList) {
            Either<Component, StorageOperationStatus> toscaElementByOperation = getToscaElementByOperation(vertex);

            if (toscaElementByOperation.isRight()) {
                log.debug("Could not fetch the following Component by UUID {}", vertex.getUniqueId());
                return Either.right(toscaElementByOperation.right().value());
            }

            latestComponents.add(toscaElementByOperation.left().value());
        }

        if (latestComponents.size() > 1) {
            for (Component component : latestComponents) {
                if (component.isHighestVersion()) {
                    LinkedList<Component> highestComponent = new LinkedList<>();
                    highestComponent.add(component);
                    return Either.left(highestComponent);
                }
            }
        }

        return Either.left(latestComponents);
    }

    public Either<Component, StorageOperationStatus> getLatestServiceByUuid(String serviceUuid) {
        Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
        propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
        return getLatestComponentByUuid(serviceUuid, propertiesToMatch);
    }

    public Either<Component, StorageOperationStatus> getLatestComponentByUuid(String componentUuid) {
        return getLatestComponentByUuid(componentUuid, null);
    }

    public Either<Component, StorageOperationStatus> getLatestComponentByUuid(String componentUuid, Map<GraphPropertyEnum, Object> propertiesToMatch) {

        Either<List<Component>, StorageOperationStatus> latestVersionListEither = getLatestComponentListByUuid(componentUuid, propertiesToMatch);

        if (latestVersionListEither.isRight()) {
            return Either.right(latestVersionListEither.right().value());
        }

        List<Component> latestVersionList = latestVersionListEither.left().value();

        if (latestVersionList.isEmpty()) {
            return Either.right(StorageOperationStatus.NOT_FOUND);
        }
        Component component = latestVersionList.size() == 1 ? latestVersionList.get(0) : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getVersion()), Double.parseDouble(c2.getVersion()))).get();

        return Either.left(component);
    }

    public Either<List<Resource>, StorageOperationStatus> getAllCertifiedResources(boolean isAbstract, Boolean isHighest) {

        List<Resource> resources = new ArrayList<>();
        Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
        Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);

        propertiesToMatch.put(GraphPropertyEnum.IS_ABSTRACT, isAbstract);
        if (isHighest != null) {
            propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, isHighest);
        }
        propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
        propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
        propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);

        Either<List<GraphVertex>, JanusGraphOperationStatus> getResourcesRes = janusGraphDao
            .getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);

        if (getResourcesRes.isRight()) {
            log.debug("Failed to fetch all certified resources. Status is {}", getResourcesRes.right().value());
            return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getResourcesRes.right().value()));
        }
        List<GraphVertex> resourceVerticies = getResourcesRes.left().value();
        for (GraphVertex resourceV : resourceVerticies) {
            Either<Resource, StorageOperationStatus> getResourceRes = getToscaElement(resourceV);
            if (getResourceRes.isRight()) {
                return Either.right(getResourceRes.right().value());
            }
            resources.add(getResourceRes.left().value());
        }
        return Either.left(resources);
    }

    public <T extends Component> Either<T, StorageOperationStatus> getLatestByNameAndVersion(String name, String version, JsonParseFlagEnum parseFlag) {
        Either<T, StorageOperationStatus> result;

        Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
        Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class);

        hasProperties.put(GraphPropertyEnum.NAME, name);
        hasProperties.put(GraphPropertyEnum.VERSION, version);
        hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);

        hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true);

        Either<List<GraphVertex>, JanusGraphOperationStatus> getResourceRes = janusGraphDao
            .getByCriteria(null, hasProperties, hasNotProperties, parseFlag);
        if (getResourceRes.isRight()) {
            JanusGraphOperationStatus status = getResourceRes.right().value();
            log.debug("failed to find resource with name {}, version {}. Status is {} ", name, version, status);
            result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
            return result;
        }
        return getToscaElementByOperation(getResourceRes.left().value().get(0));
    }

    public Either<Resource, StorageOperationStatus> getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID, String systemName) {
        return getLatestComponentByCsarOrName(componentType, csarUUID, systemName, JsonParseFlagEnum.ParseAll);
    }

    public Either<Resource, StorageOperationStatus> getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID, String systemName, JsonParseFlagEnum parseFlag) {
        Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
        Map<GraphPropertyEnum, Object> propsHasNot = new EnumMap<>(GraphPropertyEnum.class);
        props.put(GraphPropertyEnum.CSAR_UUID, csarUUID);
        props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
        if (componentType != null) {
            props.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
        }
        propsHasNot.put(GraphPropertyEnum.IS_DELETED, true);

        GraphVertex resourceMetadataData = null;
        List<GraphVertex> resourceMetadataDataList = null;
        Either<List<GraphVertex>, JanusGraphOperationStatus> byCsar = janusGraphDao
            .getByCriteria(null, props, propsHasNot, JsonParseFlagEnum.ParseMetadata);
        if (byCsar.isRight()) {
            if (JanusGraphOperationStatus.NOT_FOUND == byCsar.right().value()) {
                // Fix Defect DE256036
                if (StringUtils.isEmpty(systemName)) {
                    return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(
                        JanusGraphOperationStatus.NOT_FOUND));
                }

                props.clear();
                props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
                props.put(GraphPropertyEnum.SYSTEM_NAME, systemName);
                Either<List<GraphVertex>, JanusGraphOperationStatus> bySystemname = janusGraphDao
                    .getByCriteria(null, props, JsonParseFlagEnum.ParseMetadata);
                if (bySystemname.isRight()) {
                    log.debug("getLatestResourceByCsarOrName - Failed to find by system name {}  error {} ", systemName, bySystemname.right().value());
                    return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(bySystemname.right().value()));
                }
                if (bySystemname.left().value().size() > 2) {
                    log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) must return only 2 latest version, but was returned - {}", bySystemname.left().value().size());
                    return Either.right(StorageOperationStatus.GENERAL_ERROR);
                }
                resourceMetadataDataList = bySystemname.left().value();
                if (resourceMetadataDataList.size() == 1) {
                    resourceMetadataData = resourceMetadataDataList.get(0);
                } else {
                    for (GraphVertex curResource : resourceMetadataDataList) {
                        if (!((String) curResource.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals("CERTIFIED")) {
                            resourceMetadataData = curResource;
                            break;
                        }
                    }
                }
                if (resourceMetadataData == null) {
                    log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) returned 2 latest CERTIFIED versions");
                    return Either.right(StorageOperationStatus.GENERAL_ERROR);
                }
                if (resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID) != null && !((String) resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID)).equals(csarUUID)) {
                    log.debug("getLatestResourceByCsarOrName - same system name {} but different csarUUID. exist {} and new {} ", systemName, resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID), csarUUID);
                    // correct error will be returned from create flow. with all
                    // correct audit records!!!!!
                    return Either.right(StorageOperationStatus.NOT_FOUND);
                }
                return getToscaElement((String) resourceMetadataData.getUniqueId());
            }
        } else {
            resourceMetadataDataList = byCsar.left().value();
            if (resourceMetadataDataList.size() > 2) {
                log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) must return only 2 latest version, but was returned - {}", byCsar.left().value().size());
                return Either.right(StorageOperationStatus.GENERAL_ERROR);
            }
            if (resourceMetadataDataList.size() == 1) {
                resourceMetadataData = resourceMetadataDataList.get(0);
            } else {
                for (GraphVertex curResource : resourceMetadataDataList) {
                    if (!((String) curResource.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals("CERTIFIED")) {
                        resourceMetadataData = curResource;
                        break;
                    }
                }
            }
            if (resourceMetadataData == null) {
                log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) returned 2 latest CERTIFIED versions");
                return Either.right(StorageOperationStatus.GENERAL_ERROR);
            }
            return getToscaElement((String) resourceMetadataData.getJsonMetadataField(JsonPresentationFields.UNIQUE_ID), parseFlag);
        }
        return null;
    }

    public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExtends(String templateNameCurrent, String templateNameExtends) {

        String currentTemplateNameChecked = templateNameExtends;

        while (currentTemplateNameChecked != null && !currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) {
            Either<Resource, StorageOperationStatus> latestByToscaResourceName = getLatestByToscaResourceName(currentTemplateNameChecked);

            if (latestByToscaResourceName.isRight()) {
                return latestByToscaResourceName.right().value() == StorageOperationStatus.NOT_FOUND ? Either.left(false) : Either.right(latestByToscaResourceName.right().value());
            }

            Resource value = latestByToscaResourceName.left().value();

            if (value.getDerivedFrom() != null) {
                currentTemplateNameChecked = value.getDerivedFrom().get(0);
            } else {
                currentTemplateNameChecked = null;
            }
        }

        return (currentTemplateNameChecked != null && currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) ? Either.left(true) : Either.left(false);
    }

    public Either<List<Component>, StorageOperationStatus> fetchMetaDataByResourceType(String resourceType, ComponentParametersView filterBy) {
        Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
        props.put(GraphPropertyEnum.RESOURCE_TYPE, resourceType);
        props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
        Map<GraphPropertyEnum, Object> propsHasNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
        propsHasNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
        Either<List<GraphVertex>, JanusGraphOperationStatus> resourcesByTypeEither = janusGraphDao
            .getByCriteria(null, props, propsHasNotToMatch, JsonParseFlagEnum.ParseMetadata);

        if (resourcesByTypeEither.isRight()) {
            return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(resourcesByTypeEither.right().value()));
        }

        List<GraphVertex> vertexList = resourcesByTypeEither.left().value();
        List<Component> components = new ArrayList<>();

        for (GraphVertex vertex : vertexList) {
            components.add(getToscaElementByOperation(vertex, filterBy).left().value());
        }

        return Either.left(components);
    }

    public void commit() {
        janusGraphDao.commit();
    }

    public Either<Service, StorageOperationStatus> updateDistributionStatus(Service service, User user, DistributionStatusEnum distributionStatus) {
        Either<GraphVertex, StorageOperationStatus> updateDistributionStatus = topologyTemplateOperation.updateDistributionStatus(service.getUniqueId(), user, distributionStatus);
        if (updateDistributionStatus.isRight()) {
            return Either.right(updateDistributionStatus.right().value());
        }
        GraphVertex serviceV = updateDistributionStatus.left().value();
        service.setDistributionStatus(distributionStatus);
        service.setLastUpdateDate((Long) serviceV.getJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE));
        return Either.left(service);
    }

    public Either<ComponentMetadataData, StorageOperationStatus> updateComponentLastUpdateDateOnGraph(Component component) {

        Either<ComponentMetadataData, StorageOperationStatus> result = null;
        GraphVertex serviceVertex;
        Either<GraphVertex, JanusGraphOperationStatus> updateRes = null;
        Either<GraphVertex, JanusGraphOperationStatus> getRes = janusGraphDao
            .getVertexById(component.getUniqueId(), JsonParseFlagEnum.ParseMetadata);
        if (getRes.isRight()) {
            JanusGraphOperationStatus status = getRes.right().value();
            log.error("Failed to fetch component {}. status is {}", component.getUniqueId(), status);
            result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
        }
        if (result == null) {
            serviceVertex = getRes.left().value();
            long lastUpdateDate = System.currentTimeMillis();
            serviceVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, lastUpdateDate);
            component.setLastUpdateDate(lastUpdateDate);
            updateRes = janusGraphDao.updateVertex(serviceVertex);
            if (updateRes.isRight()) {
                result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateRes.right().value()));
            }
        }
        if (result == null) {
            result = Either.left(ModelConverter.convertToComponentMetadata(updateRes.left().value()));
        }
        return result;
    }

    public HealingJanusGraphDao getJanusGraphDao() {
        return janusGraphDao;
    }

    public Either<List<Service>, StorageOperationStatus> getCertifiedServicesWithDistStatus(Set<DistributionStatusEnum> distStatus) {
        Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
        propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());

        return getServicesWithDistStatus(distStatus, propertiesToMatch);
    }

    public Either<List<Service>, StorageOperationStatus> getServicesWithDistStatus(Set<DistributionStatusEnum> distStatus, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {

        List<Service> servicesAll = new ArrayList<>();

        Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
        Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);

        if (additionalPropertiesToMatch != null && !additionalPropertiesToMatch.isEmpty()) {
            propertiesToMatch.putAll(additionalPropertiesToMatch);
        }

        propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());

        propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);

        if (distStatus != null && !distStatus.isEmpty()) {
            for (DistributionStatusEnum state : distStatus) {
                propertiesToMatch.put(GraphPropertyEnum.DISTRIBUTION_STATUS, state.name());
                Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria = fetchServicesByCriteria(servicesAll, propertiesToMatch, propertiesNotToMatch);
                if (fetchServicesByCriteria.isRight()) {
                    return fetchServicesByCriteria;
                } else {
                    servicesAll = fetchServicesByCriteria.left().value();
                }
            }
            return Either.left(servicesAll);
        } else {
            return fetchServicesByCriteria(servicesAll, propertiesToMatch, propertiesNotToMatch);
        }
    }

    private Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria(List<Service> servicesAll, Map<GraphPropertyEnum, Object> propertiesToMatch, Map<GraphPropertyEnum, Object> propertiesNotToMatch) {
        Either<List<GraphVertex>, JanusGraphOperationStatus> getRes = janusGraphDao
            .getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
        if (getRes.isRight()) {
            if (getRes.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
                CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified services by match properties {} not match properties {} . Status is {}. ", propertiesToMatch, propertiesNotToMatch, getRes.right().value());
                return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getRes.right().value()));
            }
        } else {
            for (GraphVertex vertex : getRes.left().value()) {
                Either<ToscaElement, StorageOperationStatus> getServiceRes = topologyTemplateOperation.getLightComponent(vertex, ComponentTypeEnum.SERVICE, new ComponentParametersView(true));

                if (getServiceRes.isRight()) {
                    CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified service {}. Status is {}. ", vertex.getJsonMetadataField(JsonPresentationFields.NAME), getServiceRes.right().value());
                    return Either.right(getServiceRes.right().value());
                } else {
                    servicesAll.add(ModelConverter.convertFromToscaElement(getServiceRes.left().value()));
                }
            }
        }
        return Either.left(servicesAll);
    }

    public void rollback() {
        janusGraphDao.rollback();
    }

    public StorageOperationStatus addDeploymentArtifactsToInstance(String componentId, ComponentInstance componentInstance, Map<String, ArtifactDefinition> finalDeploymentArtifacts) {
        Map<String, ArtifactDataDefinition> instDeplArtifacts = finalDeploymentArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));

        return nodeTemplateOperation.addDeploymentArtifactsToInstance(componentId, componentInstance.getUniqueId(), instDeplArtifacts);
    }

    public StorageOperationStatus addInformationalArtifactsToInstance(String componentId, ComponentInstance componentInstance, Map<String, ArtifactDefinition> artifacts) {
        StorageOperationStatus status = StorageOperationStatus.OK;
        if (MapUtils.isNotEmpty(artifacts)) {
            Map<String, ArtifactDataDefinition> instDeplArtifacts = artifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
            status = nodeTemplateOperation.addInformationalArtifactsToInstance(componentId, componentInstance.getUniqueId(), instDeplArtifacts);
        }
        return status;
    }

    public StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId) {
        return nodeTemplateOperation.generateCustomizationUUIDOnInstance(componentId, instanceId);
    }

    public StorageOperationStatus generateCustomizationUUIDOnInstanceGroup(String componentId, String instanceId, List<String> groupInstances) {
        return nodeTemplateOperation.generateCustomizationUUIDOnInstanceGroup(componentId, instanceId, groupInstances);
    }

    public Either<PropertyDefinition, StorageOperationStatus> addPropertyToComponent(String propertyName,
																					 PropertyDefinition newPropertyDefinition,
																					 Component component) {
		newPropertyDefinition.setName(propertyName);

		StorageOperationStatus status = getToscaElementOperation(component)
				.addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition, JsonPresentationFields.NAME);
		if (status != StorageOperationStatus.OK) {
			CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the component {}. Status is {}. ", propertyName, component.getName(), status);
            return Either.right(status);
		}

        ComponentParametersView filter = new ComponentParametersView(true);
        filter.setIgnoreProperties(false);
        filter.setIgnoreInputs(false);
        Either<Component, StorageOperationStatus> getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
        if (getUpdatedComponentRes.isRight()) {
            CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated component {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value());
            return Either.right(status);
        }

        PropertyDefinition newProperty = null;
        List<PropertyDefinition> properties =
                (getUpdatedComponentRes.left().value()).getProperties();
        if (CollectionUtils.isNotEmpty(properties)) {
            Optional<PropertyDefinition> propertyOptional = properties.stream().filter(
                    propertyEntry -> propertyEntry.getName().equals(propertyName)).findAny();
            if (propertyOptional.isPresent()) {
                newProperty = propertyOptional.get();
            }
        }
        if (newProperty == null) {
            CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the component {}. Status is {}. ", propertyName, component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
            return Either.right(StorageOperationStatus.NOT_FOUND);
        }

        return Either.left(newProperty);
	}

	public StorageOperationStatus deletePropertyOfComponent(Component component, String propertyName) {
		return getToscaElementOperation(component).deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, propertyName, JsonPresentationFields.NAME);
	}

	public StorageOperationStatus deleteAttributeOfResource(Component component, String attributeName) {
		return getToscaElementOperation(component).deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, attributeName, JsonPresentationFields.NAME);
	}

    public StorageOperationStatus deleteInputOfResource(Component resource, String inputName) {
        return getToscaElementOperation(resource).deleteToscaDataElement(resource.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputName, JsonPresentationFields.NAME);
    }

    /**
     * Deletes a data type from a component.
     * @param component the container which has the data type
     * @param dataTypeName the data type name to be deleted
     * @return Operation result.
     */
    public StorageOperationStatus deleteDataTypeOfComponent(Component component, String dataTypeName) {
        return getToscaElementOperation(component).deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.DATA_TYPES, VertexTypeEnum.DATA_TYPES, dataTypeName, JsonPresentationFields.NAME);
    }

	public Either<PropertyDefinition, StorageOperationStatus> updatePropertyOfComponent(Component component,
																						PropertyDefinition newPropertyDefinition) {

		Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
		Either<PropertyDefinition, StorageOperationStatus> result = null;
		StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition, JsonPresentationFields.NAME);
		if (status != StorageOperationStatus.OK) {
			CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", newPropertyDefinition.getName(), component.getName(), status);
			result = Either.right(status);
		}
		if (result == null) {
			ComponentParametersView filter = new ComponentParametersView(true);
			filter.setIgnoreProperties(false);
			getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
			if (getUpdatedComponentRes.isRight()) {
				CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value());
				result = Either.right(status);
			}
		}
		if (result == null) {
			Optional<PropertyDefinition> newProperty = (getUpdatedComponentRes.left().value())
					.getProperties().stream().filter(p -> p.getName().equals(newPropertyDefinition.getName())).findAny();
			if (newProperty.isPresent()) {
				result = Either.left(newProperty.get());
			} else {
				CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", newPropertyDefinition.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
				result = Either.right(StorageOperationStatus.NOT_FOUND);
			}
		}
		return result;
	}


	public Either<AttributeDataDefinition, StorageOperationStatus> addAttributeOfResource(Component component, AttributeDataDefinition newAttributeDef) {

        Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
        Either<AttributeDataDefinition, StorageOperationStatus> result = null;
        if (newAttributeDef.getUniqueId() == null || newAttributeDef.getUniqueId().isEmpty()) {
            String attUniqueId = UniqueIdBuilder.buildAttributeUid(component.getUniqueId(), newAttributeDef.getName());
            newAttributeDef.setUniqueId(attUniqueId);
        }

        StorageOperationStatus status = getToscaElementOperation(component).addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef, JsonPresentationFields.NAME);
        if (status != StorageOperationStatus.OK) {
            CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS, newAttributeDef.getName(), component.getName(), status);
            result = Either.right(status);
        }
        if (result == null) {
            ComponentParametersView filter = new ComponentParametersView(true);
            filter.setIgnoreAttributesFrom(false);
            getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
            if (getUpdatedComponentRes.isRight()) {
                CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(), getUpdatedComponentRes.right().value());
                result = Either.right(status);
            }
        }
        if (result == null) {
            Optional<AttributeDataDefinition> newAttribute = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream().filter(p -> p.getName().equals(newAttributeDef.getName())).findAny();
            if (newAttribute.isPresent()) {
                result = Either.left(newAttribute.get());
            } else {
                CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FIND_RECENTLY_ADDED_PROPERTY_ON_THE_RESOURCE_STATUS_IS, newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
                result = Either.right(StorageOperationStatus.NOT_FOUND);
            }
        }
        return result;
    }

    public Either<AttributeDataDefinition, StorageOperationStatus> updateAttributeOfResource(Component component, AttributeDataDefinition newAttributeDef) {

        Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
        Either<AttributeDataDefinition, StorageOperationStatus> result = null;
        StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef, JsonPresentationFields.NAME);
        if (status != StorageOperationStatus.OK) {
            CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS, newAttributeDef.getName(), component.getName(), status);
            result = Either.right(status);
        }
        if (result == null) {
            ComponentParametersView filter = new ComponentParametersView(true);
            filter.setIgnoreAttributesFrom(false);
            getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
            if (getUpdatedComponentRes.isRight()) {
                CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(), getUpdatedComponentRes.right().value());
                result = Either.right(status);
            }
        }
        if (result == null) {
            Optional<AttributeDataDefinition> newProperty = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream().filter(p -> p.getName().equals(newAttributeDef.getName())).findAny();
            if (newProperty.isPresent()) {
                result = Either.left(newProperty.get());
            } else {
                CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FIND_RECENTLY_ADDED_PROPERTY_ON_THE_RESOURCE_STATUS_IS, newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
                result = Either.right(StorageOperationStatus.NOT_FOUND);
            }
        }
        return result;
    }

    public Either<InputDefinition, StorageOperationStatus> updateInputOfComponent(Component component, InputDefinition newInputDefinition) {

        Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
        Either<InputDefinition, StorageOperationStatus> result = null;
        StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, newInputDefinition, JsonPresentationFields.NAME);
        if (status != StorageOperationStatus.OK) {
            CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the input {} to the component {}. Status is {}. ", newInputDefinition.getName(), component.getName(), status);
            result = Either.right(status);
        }
        if (result == null) {
            ComponentParametersView filter = new ComponentParametersView(true);
            filter.setIgnoreInputs(false);
            getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
            if (getUpdatedComponentRes.isRight()) {
                CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(), getUpdatedComponentRes.right().value());
                result = Either.right(status);
            }
        }
        if (result == null) {
            Optional<InputDefinition> updatedInput = getUpdatedComponentRes.left().value().getInputs().stream().filter(p -> p.getName().equals(newInputDefinition.getName())).findAny();
            if (updatedInput.isPresent()) {
                result = Either.left(updatedInput.get());
            } else {
                CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently updated inputs {} on the resource {}. Status is {}. ", newInputDefinition.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
                result = Either.right(StorageOperationStatus.NOT_FOUND);
            }
        }
        return result;
    }

    /**
     * method - ename the group instances after referenced container name renamed flow - VF rename -(triggers)-> Group rename
     *
     * @param containerComponent  - container such as service
     * @param componentInstance   - context component
     * @param componentInstanceId - id
     * @return - successfull/failed status
     **/
    public Either<StorageOperationStatus, StorageOperationStatus> cleanAndAddGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, String componentInstanceId) {
        String uniqueId = componentInstance.getUniqueId();
        StorageOperationStatus status = nodeTemplateOperation.deleteToscaDataDeepElementsBlockOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS, uniqueId);
        if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
            CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete group instances for container {}. error {] ", componentInstanceId, status);
            return Either.right(status);
        }
        if (componentInstance.getGroupInstances() != null) {
            status = addGroupInstancesToComponentInstance(containerComponent, componentInstance, componentInstance.getGroupInstances());
            if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
                CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add group instances for container {}. error {] ", componentInstanceId, status);
                return Either.right(status);
            }
        }
        return Either.left(status);
    }

    public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List<GroupDefinition> groups, Map<String, List<ArtifactDefinition>> groupInstancesArtifacts) {
        return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groups, groupInstancesArtifacts);
    }

    public Either<List<GroupDefinition>, StorageOperationStatus> updateGroupsOnComponent(Component component, List<GroupDataDefinition> updatedGroups) {
        return groupsOperation.updateGroups(component, updatedGroups, PromoteVersionEnum.MINOR);
    }

    public Either<List<GroupInstance>, StorageOperationStatus> updateGroupInstancesOnComponent(Component component, String instanceId, List<GroupInstance> updatedGroupInstances) {
        return groupsOperation.updateGroupInstances(component, instanceId, updatedGroupInstances);
    }

    public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List<GroupInstance> groupInstances) {
        return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groupInstances);
    }

    public StorageOperationStatus addDeploymentArtifactsToComponentInstance(Component containerComponent, ComponentInstance componentInstance, Map<String, ArtifactDefinition> deploymentArtifacts) {
        return nodeTemplateOperation.addDeploymentArtifactsToComponentInstance(containerComponent, componentInstance, deploymentArtifacts);
    }

    public StorageOperationStatus updateComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) {
        return nodeTemplateOperation.updateComponentInstanceProperty(containerComponent, componentInstanceId, property);
    }

    public StorageOperationStatus updateComponentInstanceProperties(Component containerComponent, String componentInstanceId, List<ComponentInstanceProperty> properties) {
        return nodeTemplateOperation.updateComponentInstanceProperties(containerComponent, componentInstanceId, properties);
    }


    public StorageOperationStatus addComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) {
        return nodeTemplateOperation.addComponentInstanceProperty(containerComponent, componentInstanceId, property);
    }

    public StorageOperationStatus updateComponentInstanceAttribute(Component containerComponent, String componentInstanceId, ComponentInstanceAttribute property){
        return nodeTemplateOperation.updateComponentInstanceAttribute(containerComponent, componentInstanceId, property);
    }

    public StorageOperationStatus addComponentInstanceAttribute(Component containerComponent, String componentInstanceId, ComponentInstanceAttribute attribute){
        return nodeTemplateOperation.addComponentInstanceAttribute(containerComponent, componentInstanceId, attribute);
    }

    public StorageOperationStatus updateComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) {
        return nodeTemplateOperation.updateComponentInstanceInput(containerComponent, componentInstanceId, property);
    }

    public StorageOperationStatus updateComponentInstanceInputs(Component containerComponent, String componentInstanceId, List<ComponentInstanceInput> instanceInputs) {
        return nodeTemplateOperation.updateComponentInstanceInputs(containerComponent, componentInstanceId, instanceInputs);
    }

    public StorageOperationStatus addComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) {
        return nodeTemplateOperation.addComponentInstanceInput(containerComponent, componentInstanceId, property);
    }

    public void setNodeTypeOperation(NodeTypeOperation nodeTypeOperation) {
        this.nodeTypeOperation = nodeTypeOperation;
    }

    public void setTopologyTemplateOperation(TopologyTemplateOperation topologyTemplateOperation) {
        this.topologyTemplateOperation = topologyTemplateOperation;
    }

    public StorageOperationStatus deleteComponentInstanceInputsFromTopologyTemplate(Component containerComponent, List<InputDefinition> inputsToDelete) {
        return topologyTemplateOperation.deleteToscaDataElements(containerComponent.getUniqueId(), EdgeLabelEnum.INPUTS, inputsToDelete.stream().map(PropertyDataDefinition::getName).collect(Collectors.toList()));
    }

    public StorageOperationStatus updateComponentInstanceCapabiltyProperty(Component containerComponent, String componentInstanceUniqueId, String capabilityPropertyKey, ComponentInstanceProperty property) {
        return nodeTemplateOperation.updateComponentInstanceCapabilityProperty(containerComponent, componentInstanceUniqueId, capabilityPropertyKey, property);
    }

    public StorageOperationStatus updateComponentInstanceCapabilityProperties(Component containerComponent, String componentInstanceUniqueId) {
        return convertComponentInstanceProperties(containerComponent, componentInstanceUniqueId)
                .map(instanceCapProps -> topologyTemplateOperation.updateComponentInstanceCapabilityProperties(containerComponent, componentInstanceUniqueId, instanceCapProps))
                .orElse(StorageOperationStatus.NOT_FOUND);
    }
    
    public StorageOperationStatus updateComponentInstanceRequirement(String containerComponentId, String componentInstanceUniqueId, RequirementDataDefinition requirementDataDefinition) {
        return nodeTemplateOperation.updateComponentInstanceRequirement(containerComponentId, componentInstanceUniqueId, requirementDataDefinition);
    }

    public StorageOperationStatus updateComponentInstanceInterfaces(Component containerComponent, String componentInstanceUniqueId) {
        MapInterfaceDataDefinition mapInterfaceDataDefinition =
                convertComponentInstanceInterfaces(containerComponent, componentInstanceUniqueId);
        return topologyTemplateOperation
                .updateComponentInstanceInterfaces(containerComponent, componentInstanceUniqueId, mapInterfaceDataDefinition);
    }

	public StorageOperationStatus updateComponentCalculatedCapabilitiesProperties(Component containerComponent) {
		Map<String, MapCapabilityProperty> mapCapabiltyPropertyMap =
        convertComponentCapabilitiesProperties(containerComponent);
		return nodeTemplateOperation.overrideComponentCapabilitiesProperties(containerComponent, mapCapabiltyPropertyMap);
	}

    public StorageOperationStatus deleteAllCalculatedCapabilitiesRequirements(String topologyTemplateId) {
        StorageOperationStatus status = topologyTemplateOperation.removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES);
        if (status == StorageOperationStatus.OK) {
            status = topologyTemplateOperation.removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS);
        }
        if (status == StorageOperationStatus.OK) {
            status = topologyTemplateOperation.removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES);
        }
        return status;
    }

    public Either<Component, StorageOperationStatus> shouldUpgradeToLatestDerived(Resource clonedResource) {
        String componentId = clonedResource.getUniqueId();
        Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
            .getVertexById(componentId, JsonParseFlagEnum.NoParse);
        if (getVertexEither.isRight()) {
            log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
            return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));

        }
        GraphVertex nodeTypeV = getVertexEither.left().value();

        ToscaElement toscaElementToUpdate = ModelConverter.convertToToscaElement(clonedResource);

        Either<ToscaElement, StorageOperationStatus> shouldUpdateDerivedVersion = nodeTypeOperation.shouldUpdateDerivedVersion(toscaElementToUpdate, nodeTypeV);
        if (shouldUpdateDerivedVersion.isRight() && StorageOperationStatus.OK != shouldUpdateDerivedVersion.right().value()) {
            log.debug("Failed to update derived version for node type {} derived {}, error: {}", componentId, clonedResource.getDerivedFrom().get(0), shouldUpdateDerivedVersion.right().value());
            return Either.right(shouldUpdateDerivedVersion.right().value());
        }
        if (shouldUpdateDerivedVersion.isLeft()) {
            return Either.left(ModelConverter.convertFromToscaElement(shouldUpdateDerivedVersion.left().value()));
        }
        return Either.left(clonedResource);
    }

    /**
     * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name, type and ownerId
     */
    public Either<List<ComponentInstanceProperty>, StorageOperationStatus> getComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityName, String capabilityType, String ownerId) {
        return topologyTemplateOperation.getComponentInstanceCapabilityProperties(componentId, instanceId, capabilityName, capabilityType, ownerId);
    }

	private MapInterfaceDataDefinition convertComponentInstanceInterfaces(Component currComponent,
																																				String componentInstanceId) {
		MapInterfaceDataDefinition mapInterfaceDataDefinition = new MapInterfaceDataDefinition();
		List<ComponentInstanceInterface> componentInterface = currComponent.getComponentInstancesInterfaces().get(componentInstanceId);

		if(CollectionUtils.isNotEmpty(componentInterface)) {
			componentInterface.stream().forEach(interfaceDef -> mapInterfaceDataDefinition.put
					(interfaceDef.getUniqueId(), interfaceDef));
		}

		return mapInterfaceDataDefinition;
	}

  private Map<String, MapCapabilityProperty> convertComponentCapabilitiesProperties(Component currComponent) {
    Map<String, MapCapabilityProperty> map = ModelConverter.extractCapabilityPropertiesFromGroups(currComponent.getGroups(), true);
    map.putAll(ModelConverter.extractCapabilityProperteisFromInstances(currComponent.getComponentInstances(), true));
    return map;
  }

    private Optional<MapCapabilityProperty> convertComponentInstanceProperties(Component component, String instanceId) {
        return component.fetchInstanceById(instanceId)
                .map(ci -> ModelConverter.convertToMapOfMapCapabilityProperties(ci.getCapabilities(), instanceId, ci.getOriginType().isAtomicType()));
    }

    public Either<PolicyDefinition, StorageOperationStatus> associatePolicyToComponent(String componentId, PolicyDefinition policyDefinition, int counter) {
        Either<PolicyDefinition, StorageOperationStatus> result = null;
        Either<GraphVertex, JanusGraphOperationStatus> getVertexEither;
        getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata);
        if (getVertexEither.isRight()) {
            log.error(COULDNT_FETCH_A_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
            result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
        } else {
            if (getVertexEither.left().value().getLabel() != VertexTypeEnum.TOPOLOGY_TEMPLATE) {
                log.error("Policy association to component of Tosca type {} is not allowed. ", getVertexEither.left().value().getLabel());
                result = Either.right(StorageOperationStatus.BAD_REQUEST);
            }
        }
        if (result == null) {
            StorageOperationStatus status = topologyTemplateOperation.addPolicyToToscaElement(getVertexEither.left().value(), policyDefinition, counter);
            if (status != StorageOperationStatus.OK) {
                return Either.right(status);
            }
        }
        if (result == null) {
            result = Either.left(policyDefinition);
        }
        return result;
    }

    public StorageOperationStatus associatePoliciesToComponent(String componentId, List<PolicyDefinition> policies) {
        log.debug("#associatePoliciesToComponent - associating policies for component {}.", componentId);
        return janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata)
                .either(containerVertex -> topologyTemplateOperation.addPoliciesToToscaElement(containerVertex, policies),
                        DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
    }

    public Either<PolicyDefinition, StorageOperationStatus> updatePolicyOfComponent(String componentId, PolicyDefinition policyDefinition, PromoteVersionEnum promoteVersionEnum) {
        Either<PolicyDefinition, StorageOperationStatus> result = null;
        Either<GraphVertex, JanusGraphOperationStatus> getVertexEither;
        getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
        if (getVertexEither.isRight()) {
            log.error(COULDNT_FETCH_A_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
            result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()));
        }
        if (result == null) {
            policyDefinition.setVersion(GroupUtils.updateVersion(promoteVersionEnum, policyDefinition.getVersion()));
            StorageOperationStatus status = topologyTemplateOperation.updatePolicyOfToscaElement(getVertexEither.left().value(), policyDefinition);
            if (status != StorageOperationStatus.OK) {
                return Either.right(status);
            }
        }
        if (result == null) {
            result = Either.left(policyDefinition);
        }
        return result;
    }

    public StorageOperationStatus updatePoliciesOfComponent(String componentId, List<PolicyDefinition> policyDefinition) {
        log.debug("#updatePoliciesOfComponent - updating policies for component {}", componentId);
        return janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse)
                .right()
                .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus)
                .either(containerVertex -> topologyTemplateOperation.updatePoliciesOfToscaElement(containerVertex, policyDefinition),
                        err -> err);
    }

    public StorageOperationStatus removePolicyFromComponent(String componentId, String policyId) {
        StorageOperationStatus status = null;
        Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao
            .getVertexById(componentId, JsonParseFlagEnum.NoParse);
        if (getVertexEither.isRight()) {
            log.error(COULDNT_FETCH_A_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value());
            status = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value());
        }
        if (status == null) {
            status = topologyTemplateOperation.removePolicyFromToscaElement(getVertexEither.left().value(), policyId);
        }
        return status;
    }

    public boolean canAddGroups(String componentId) {
        GraphVertex vertex = janusGraphDao.getVertexById(componentId)
                .left()
                .on(this::onJanusGraphError);
        return topologyTemplateOperation.hasEdgeOfType(vertex, EdgeLabelEnum.GROUPS);
    }

    GraphVertex onJanusGraphError(JanusGraphOperationStatus toe) {
        throw new StorageException(
                DaoStatusConverter.convertJanusGraphStatusToStorageStatus(toe));
    }

    public CatalogUpdateTimestamp updateCatalogTimes() {
        long now = System.currentTimeMillis();

        GraphVertex catalogRoot = janusGraphDao.getVertexByLabel(VertexTypeEnum.CATALOG_ROOT)
                .left()
                .on(this::onJanusGraphError);

        Long currentTime = (Long) catalogRoot.getMetadataProperty(GraphPropertyEnum.CURRENT_CATALOG_UPDATE_TIME);
        catalogRoot.addMetadataProperty(GraphPropertyEnum.PREV_CATALOG_UPDATE_TIME, currentTime);
        catalogRoot.addMetadataProperty(GraphPropertyEnum.CURRENT_CATALOG_UPDATE_TIME, now);

        janusGraphDao.updateVertex(catalogRoot).left().on(this::onJanusGraphError);

        return new CatalogUpdateTimestamp(currentTime, now);
    }

    public CatalogUpdateTimestamp getCatalogTimes() {


        GraphVertex catalogRoot = janusGraphDao.getVertexByLabel(VertexTypeEnum.CATALOG_ROOT)
                .left()
                .on(this::onJanusGraphError);

        Long currentTime = (Long) catalogRoot.getMetadataProperty(GraphPropertyEnum.CURRENT_CATALOG_UPDATE_TIME);
        Long prevTime = (Long) catalogRoot.getMetadataProperty(GraphPropertyEnum.PREV_CATALOG_UPDATE_TIME);

        return new CatalogUpdateTimestamp(prevTime == null ? 0 : prevTime.longValue(), currentTime == null ? 0 : currentTime.longValue());
    }

    public void updateNamesOfCalculatedCapabilitiesRequirements(String componentId) {
        topologyTemplateOperation
                .updateNamesOfCalculatedCapabilitiesRequirements(componentId, getTopologyTemplate(componentId));
    }

    public void revertNamesOfCalculatedCapabilitiesRequirements(String componentId) {
        topologyTemplateOperation
                .revertNamesOfCalculatedCapabilitiesRequirements(componentId, getTopologyTemplate(componentId));
    }

    private TopologyTemplate getTopologyTemplate(String componentId) {
        return (TopologyTemplate) topologyTemplateOperation
                .getToscaElement(componentId, getFilterComponentWithCapProperties())
                .left()
                .on(this::throwStorageException);
    }

    private ComponentParametersView getFilterComponentWithCapProperties() {
        ComponentParametersView filter = new ComponentParametersView();
        filter.setIgnoreCapabiltyProperties(false);
        return filter;
    }

    private ToscaElement throwStorageException(StorageOperationStatus status) {
        throw new StorageException(status);
    }

    public Either<Boolean, StorageOperationStatus> isComponentInUse(String componentId) {
        final List<EdgeLabelEnum> forbiddenEdgeLabelEnums = Arrays.asList(EdgeLabelEnum.INSTANCE_OF, EdgeLabelEnum.PROXY_OF, EdgeLabelEnum.ALLOTTED_OF);
        Either<GraphVertex, JanusGraphOperationStatus> vertexById = janusGraphDao.getVertexById(componentId);
        if (vertexById.isLeft()) {
            for (EdgeLabelEnum edgeLabelEnum : forbiddenEdgeLabelEnums) {
                Iterator<Edge> edgeItr = vertexById.left().value().getVertex().edges(Direction.IN, edgeLabelEnum.name());
                if(edgeItr != null && edgeItr.hasNext()){
                    return Either.left(true);
                }
            }
        }
        return Either.left(false);
    }

	public Either<List<Component>, StorageOperationStatus> getComponentListByInvariantUuid
			(String componentInvariantUuid, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {

		Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
		if (MapUtils.isNotEmpty(additionalPropertiesToMatch)) {
			propertiesToMatch.putAll(additionalPropertiesToMatch);
		}
		propertiesToMatch.put(GraphPropertyEnum.INVARIANT_UUID, componentInvariantUuid);

		Either<List<GraphVertex>, JanusGraphOperationStatus> vertexEither = janusGraphDao
        .getByCriteria(null, propertiesToMatch, JsonParseFlagEnum.ParseMetadata);

		if (vertexEither.isRight()) {
			log.debug("Couldn't fetch metadata for component with type {} and invariantUUId {}, error: {}", componentInvariantUuid, vertexEither.right().value());
			return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexEither.right().value()));
		}
		List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;

		if (vertexList == null || vertexList.isEmpty()) {
			log.debug("Component with invariantUUId {} was not found", componentInvariantUuid);
			return Either.right(StorageOperationStatus.NOT_FOUND);
		}

		ArrayList<Component> components = new ArrayList<>();
		for (GraphVertex vertex : vertexList) {
			Either<Component, StorageOperationStatus> toscaElementByOperation = getToscaElementByOperation(vertex);
			if (toscaElementByOperation.isRight()) {
				log.debug("Could not fetch the following Component by Invariant UUID {}", vertex.getUniqueId());
				return Either.right(toscaElementByOperation.right().value());
			}
			components.add(toscaElementByOperation.left().value());
		}

		return Either.left(components);
	}

    public Either<List<Component>, StorageOperationStatus> getParentComponents(String componentId) {
        List<Component> parentComponents = new ArrayList<>();
        final List<EdgeLabelEnum> relationEdgeLabelEnums = Arrays.asList(EdgeLabelEnum.INSTANCE_OF, EdgeLabelEnum.PROXY_OF);
        Either<GraphVertex, JanusGraphOperationStatus> vertexById = janusGraphDao.getVertexById(componentId);
        if (vertexById.isLeft()) {
            for (EdgeLabelEnum edgeLabelEnum : relationEdgeLabelEnums) {
                Either<GraphVertex, JanusGraphOperationStatus> parentVertexEither = janusGraphDao
                    .getParentVertex(vertexById.left().value(), edgeLabelEnum, JsonParseFlagEnum.ParseJson);
                if(parentVertexEither.isLeft()){
                    Either<Component, StorageOperationStatus> componentEither = getToscaElement(parentVertexEither.left().value().getUniqueId());
                    if(componentEither.isLeft()){
                        parentComponents.add(componentEither.left().value());
                    }
                }
            }
        }
        return Either.left(parentComponents);
    }
    public void updateCapReqPropertiesOwnerId(String componentId) {
        topologyTemplateOperation
                .updateCapReqPropertiesOwnerId(componentId, getTopologyTemplate(componentId));
    }

    public <T extends Component> Either<T, StorageOperationStatus> getLatestByServiceName(String serviceName) {
        return getLatestByName(GraphPropertyEnum.NAME, serviceName);

    }
}