summaryrefslogtreecommitdiffstats
path: root/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ExternalAccessRolesServiceImpl.java
blob: c528e55e7290ff1e2ef6cd51a7bc34961ce5a5e1 (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
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
/*-
 * ============LICENSE_START==========================================
 * ONAP Portal
 * ===================================================================
 * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
 * ===================================================================
 *
 * Unless otherwise specified, all software contained herein is licensed
 * under the Apache License, Version 2.0 (the "License");
 * you may not use this software 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.
 *
 * Unless otherwise specified, all documentation contained herein is licensed
 * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
 * you may not use this documentation except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *             https://creativecommons.org/licenses/by/4.0/
 *
 * Unless required by applicable law or agreed to in writing, documentation
 * 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.onap.portalapp.portal.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.json.JSONArray;
import org.json.JSONObject;
import org.onap.portalapp.portal.domain.CentralV2RoleFunction;
import org.onap.portalapp.portal.domain.CentralizedApp;
import org.onap.portalapp.portal.domain.EPApp;
import org.onap.portalapp.portal.domain.EPAppRoleFunction;
import org.onap.portalapp.portal.domain.EPRole;
import org.onap.portalapp.portal.domain.EPUser;
import org.onap.portalapp.portal.domain.EPUserApp;
import org.onap.portalapp.portal.domain.ExternalRoleDetails;
import org.onap.portalapp.portal.ecomp.model.UploadRoleFunctionExtSystem;
import org.onap.portalapp.portal.exceptions.DeleteDomainObjectFailedException;
import org.onap.portalapp.portal.exceptions.ExternalAuthSystemException;
import org.onap.portalapp.portal.exceptions.InactiveApplicationException;
import org.onap.portalapp.portal.exceptions.InvalidApplicationException;
import org.onap.portalapp.portal.exceptions.InvalidUserException;
import org.onap.portalapp.portal.exceptions.RoleFunctionException;
import org.onap.portalapp.portal.logging.aop.EPAuditLog;
import org.onap.portalapp.portal.logging.aop.EPMetricsLog;
import org.onap.portalapp.portal.logging.logic.EPLogUtil;
import org.onap.portalapp.portal.transport.BulkUploadRoleFunction;
import org.onap.portalapp.portal.transport.BulkUploadUserRoles;
import org.onap.portalapp.portal.transport.CentralApp;
import org.onap.portalapp.portal.transport.CentralRole;
import org.onap.portalapp.portal.transport.CentralRoleFunction;
import org.onap.portalapp.portal.transport.CentralUser;
import org.onap.portalapp.portal.transport.CentralUserApp;
import org.onap.portalapp.portal.transport.CentralV2Role;
import org.onap.portalapp.portal.transport.CentralV2User;
import org.onap.portalapp.portal.transport.CentralV2UserApp;
import org.onap.portalapp.portal.transport.CentralizedAppRoles;
import org.onap.portalapp.portal.transport.EcompUserRoles;
import org.onap.portalapp.portal.transport.ExternalAccessPerms;
import org.onap.portalapp.portal.transport.ExternalAccessPermsDetail;
import org.onap.portalapp.portal.transport.ExternalAccessRole;
import org.onap.portalapp.portal.transport.ExternalAccessRolePerms;
import org.onap.portalapp.portal.transport.ExternalAccessUser;
import org.onap.portalapp.portal.transport.ExternalAccessUserRoleDetail;
import org.onap.portalapp.portal.transport.ExternalRequestFieldsValidator;
import org.onap.portalapp.portal.transport.GlobalRoleWithApplicationRoleFunction;
import org.onap.portalapp.portal.transport.LocalRole;
import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
import org.onap.portalapp.portal.utils.EcompPortalUtils;
import org.onap.portalapp.portal.utils.PortalConstants;
import org.onap.portalapp.util.EPUserUtils;
import org.onap.portalsdk.core.domain.Role;
import org.onap.portalsdk.core.domain.RoleFunction;
import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
import org.onap.portalsdk.core.restful.domain.EcompRole;
import org.onap.portalsdk.core.restful.domain.EcompRoleFunction;
import org.onap.portalsdk.core.restful.domain.EcompUser;
import org.onap.portalsdk.core.service.DataAccessService;
import org.onap.portalsdk.core.util.SystemProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;

@Service("externalAccessRolesService")
@EnableAspectJAutoProxy
@EPMetricsLog
@EPAuditLog
public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesService {

	private static final String APP_ROLE_NAME_PARAM = "appRoleName";

	private static final String GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM = "getRoletoUpdateInExternalAuthSystem";

	private static final String GET_PORTAL_APP_ROLES_QUERY = "getPortalAppRoles";

	private static final String GET_ROLE_FUNCTION_QUERY = "getRoleFunction";

	private static final String FUNCTION_CODE_PARAMS = "functionCode";

	private static final String AND_FUNCTION_CD_EQUALS = " and function_cd = '";

	private static final String OWNER = ".owner";

	private static final String ADMIN = ".admin";

	private static final String ACCOUNT_ADMINISTRATOR = ".Account_Administrator";

	private static final String FUNCTION_PIPE = "|";

	private static final String EXTERNAL_AUTH_PERMS = "perms";

	private static final String EXTERNAL_AUTH_ROLE_DESCRIPTION = "description";

	private static final String IS_EMPTY_JSON_STRING = "{}";

	private static final String CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE = "Connecting to External Auth system";

	private static final String APP_ID = "appId";

	private static final String ROLE_NAME = "name";

	private static final String APP_ID_EQUALS = " app_id = ";
	
	private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAccessRolesServiceImpl.class);

	@Autowired
	private DataAccessService dataAccessService;
	
	@Autowired
	private EPAppService epAppService;
	
	@Autowired
	private SessionFactory sessionFactory;
	
	@Autowired
	EPRoleService ePRoleService;

	RestTemplate template = new RestTemplate();
	
	
	// These decode values are based on HexDecoder
	static final String decodeValueOfForwardSlash = "2f";
	static final String decodeValueOfHiphen = "2d";
	static final String decodeValueOfStar = "2a";

	@SuppressWarnings("unchecked")
	public List<EPRole> getAppRoles(Long appId) throws Exception {
		List<EPRole> applicationRoles = null;
		final Map<String, Long> appParams = new HashMap<>();
		try {
			if (appId == 1) {
				applicationRoles = dataAccessService.executeNamedQuery("getPortalAppRolesList", null, null);
			} else {
				appParams.put("appId", appId);
				applicationRoles = dataAccessService.executeNamedQuery("getPartnerAppRolesList", appParams, null);
			}
		} catch (Exception e) {
			logger.error(EELFLoggerDelegate.errorLogger, "getAppRoles: failed", e);
			throw e;
		}
		return applicationRoles;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<EPApp> getApp(String uebkey) throws Exception {
		List<EPApp> app = null;
		try {
			final Map<String, String> appUebkeyParams = new HashMap<>();
			appUebkeyParams.put("appKey", uebkey);
			app = dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null);
			if(!app.isEmpty() && !app.get(0).getEnabled() && !app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)){
				throw new InactiveApplicationException("Application:"+app.get(0).getName()+" is Unavailable");
			}
		} catch (Exception e) {
			logger.error(EELFLoggerDelegate.errorLogger, "getApp: failed", e);
			throw e;
		}
		return app;
	}

	/**
	 * It returns  single application role from external auth system 
	 * @param addRole
	 * @param app
	 * @return JSON string which contains application role details
	 * @throws Exception
	 */
	private String getSingleAppRole(String addRole, EPApp app) throws Exception {
		HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
		HttpEntity<String> entity = new HttpEntity<>(headers);
		ResponseEntity<String> response = null;
		logger.debug(EELFLoggerDelegate.debugLogger, "getSingleAppRole: Connecting to External Auth system");
		response = template.exchange(
				SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "roles/"
						+ app.getNameSpace()
						+ "." + addRole
								.replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
				HttpMethod.GET, entity, String.class);
		logger.debug(EELFLoggerDelegate.debugLogger,
				"getSingleAppRole: Finished GET app role from External Auth system and status code: {} ",
				response.getStatusCode().value());
		return response.getBody();
	}

	@Override
	public boolean addRole(Role addRole, String uebkey) throws Exception {
		boolean response = false;
		ResponseEntity<String> addResponse = null;
		HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
		EPApp app = getApp(uebkey).get(0);
		String newRole = updateExistingRoleInExternalSystem(addRole, app);
		HttpEntity<String> entity = new HttpEntity<>(newRole, headers);
		logger.debug(EELFLoggerDelegate.debugLogger, "addRole: Connecting to External Auth system");
		addResponse = template.exchange(
				SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
				HttpMethod.POST, entity, String.class);
		if (addResponse.getStatusCode().value() == 201) {
			response = true;
			logger.debug(EELFLoggerDelegate.debugLogger, "addRole: Finished adding role in the External Auth system  and response code: {} ", addResponse.getStatusCode().value());
		}
		if (addResponse.getStatusCode().value() == 406) {
			logger.error(EELFLoggerDelegate.errorLogger,
					"addRole: Failed to add in the External Auth system due to {} and status code: {}", addResponse.getBody(), addResponse.getStatusCode().value());
		}
		return response;
	}

	/**
	 * 
	 * It deletes record in external auth system
	 * 
	 * @param delRole
	 * @return JSON String which has status code and response body 
	 * @throws Exception
	 */
	private ResponseEntity<String> deleteRoleInExternalSystem(String delRole) throws Exception {
		ResponseEntity<String> delResponse = null;
		HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
		HttpEntity<String> entity = new HttpEntity<>(delRole, headers);
		logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleInExternalSystem: {} for DELETE: {}" , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, delRole);
		delResponse = template.exchange(
				SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role?force=true",
				HttpMethod.DELETE, entity, String.class);
		logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleInExternalSystem: Finished DELETE operation in the External Auth system {} and status code: {} ", delRole, delResponse.getStatusCode().value());
		return delResponse;
	}

	/**
	 * It updates role in external auth system
	 * 
	 * @param updateExtRole
	 * @param app
	 * @return true if success else false
	 * @throws Exception
	 * 					If updateRoleInExternalSystem fails we catch it in logger for detail message
	 */
	private boolean updateRoleInExternalSystem(Role updateExtRole, EPApp app, boolean isGlobalRole) throws Exception {
		boolean response = false;
		ObjectMapper mapper = new ObjectMapper();
		ResponseEntity<String> deleteResponse = null;
		List<EPRole> epRoleList = null;
		if (app.getId().equals(PortalConstants.PORTAL_APP_ID)
				|| (isGlobalRole && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) {
			epRoleList = getPortalAppRoleInfo(updateExtRole.getId());
		} else {
			epRoleList = getPartnerAppRoleInfo(updateExtRole.getId(), app);
		}
		// Assigning functions to global role
		if ((isGlobalRole && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) {
			List<RoleFunction> globalRoleFunctionListNew = convertSetToListOfRoleFunctions(updateExtRole);
			EPApp portalAppInfo = epAppService.getApp(PortalConstants.PORTAL_APP_ID);
			addFunctionsTOGlobalRole(epRoleList, updateExtRole, globalRoleFunctionListNew, mapper, app, portalAppInfo);
			response = true;
		} else {
			String appRole = getSingleAppRole(epRoleList.get(0).getName(), app);
			List<RoleFunction> roleFunctionListNew = convertSetToListOfRoleFunctions(updateExtRole);
			if (!appRole.equals(IS_EMPTY_JSON_STRING)) {
				JSONObject jsonObj = new JSONObject(appRole);
				JSONArray extRole = jsonObj.getJSONArray("role");
				if (!extRole.getJSONObject(0).has(EXTERNAL_AUTH_ROLE_DESCRIPTION)) {
					String roleName = extRole.getJSONObject(0).getString(ROLE_NAME);
					Map<String, String> delRoleKeyMapper = new HashMap<>();
					delRoleKeyMapper.put(ROLE_NAME, roleName);
					String delRoleKeyValue = mapper.writeValueAsString(delRoleKeyMapper);
					deleteResponse = deleteRoleInExternalSystem(delRoleKeyValue);
					if (deleteResponse.getStatusCode().value() != 200) {
						throw new ExternalAuthSystemException(deleteResponse.getBody());
					}
					addRole(updateExtRole, app.getUebKey());
				} else {
					String desc = extRole.getJSONObject(0).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
					String name = extRole.getJSONObject(0).getString(ROLE_NAME);
					List<ExternalAccessPerms> list = new ArrayList<>();
					if (extRole.getJSONObject(0).has(EXTERNAL_AUTH_PERMS)) {
						JSONArray perms = extRole.getJSONObject(0).getJSONArray(EXTERNAL_AUTH_PERMS);
						list = mapper.readValue(perms.toString(), TypeFactory.defaultInstance()
								.constructCollectionType(List.class, ExternalAccessPerms.class));
					}
					// If role name or role functions are updated then delete
					// record in External System and add new record to avoid
					// conflicts
					boolean isRoleNameChanged = false;
					if (!desc.equals(updateExtRole.getName())) {
						isRoleNameChanged = true;
						deleteRoleInExtSystem(mapper, name);
						addRole(updateExtRole, app.getUebKey());
						// add partner functions to the global role in External Auth System
						if (!list.isEmpty() && isGlobalRole) {
							addPartnerHasRoleFunctionsToGlobalRole(list, mapper, app, updateExtRole);
						}
						list.removeIf(
								perm -> EcompPortalUtils.checkNameSpaceMatching(perm.getType(), app.getNameSpace()));
						// if role name is changes please ignore the previous functions in External Auth
						// and update with user requested functions
						addRemoveFunctionsToRole(updateExtRole, app, mapper, roleFunctionListNew, name, list);
					}
					// Delete role in External System if role is inactive
					if (!updateExtRole.getActive()) {
						deleteRoleInExtSystem(mapper, name);
					}
					if (!isRoleNameChanged) {
						response = addRemoveFunctionsToRole(updateExtRole, app, mapper, roleFunctionListNew, name,
								list);
					}
				}
			} else {
				// It seems like role exists in local DB but not in External
				// Access system
				if (updateExtRole.getActive()) {
					addRole(updateExtRole, app.getUebKey());
					ExternalAccessRolePerms extAddRolePerms = null;
					ExternalAccessPerms extAddPerms = null;
					List<RoleFunction> roleFunctionListAdd = convertSetToListOfRoleFunctions(updateExtRole);
					HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
					for (RoleFunction roleFunc : roleFunctionListAdd) {
						extAddPerms = new ExternalAccessPerms(app.getNameSpace() + "." + roleFunc.getType(),
								roleFunc.getCode(), roleFunc.getAction());
						extAddRolePerms = new ExternalAccessRolePerms(extAddPerms,
								app.getNameSpace() + "." + updateExtRole.getName().replaceAll(
										EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
						response = addRoleFuncExtSysRestAPI(mapper, extAddRolePerms, headers);
					}
				}
			}
		}
		return response;
	}

	private void deleteRoleInExtSystem(ObjectMapper mapper, String name)
			throws JsonProcessingException, Exception, ExternalAuthSystemException {
		ResponseEntity<String> deleteResponse;
		Map<String, String> delRoleKeyMapper = new HashMap<>();
		delRoleKeyMapper.put(ROLE_NAME, name);
		String delRoleKeyValue = mapper.writeValueAsString(delRoleKeyMapper);
		deleteResponse = deleteRoleInExternalSystem(delRoleKeyValue);
		if (deleteResponse.getStatusCode().value() != 200) {
			logger.error(EELFLoggerDelegate.errorLogger,
					"updateRoleInExternalSystem:  Failed to delete role in external system due to {} ",
					deleteResponse.getBody());
			throw new ExternalAuthSystemException(deleteResponse.getBody());
		}
	}

	private boolean addRemoveFunctionsToRole(Role updateExtRole, EPApp app, ObjectMapper mapper,
			List<RoleFunction> roleFunctionListNew, String name, List<ExternalAccessPerms> list) throws Exception {
		boolean response;
		Map<String, RoleFunction> updateRoleFunc = new HashMap<>();
		for (RoleFunction addPerm : roleFunctionListNew) {
			updateRoleFunc.put(addPerm.getCode(), addPerm);
		}
		final Map<String, ExternalAccessPerms> extRolePermMap = new HashMap<>();
		final Map<String, ExternalAccessPerms> extRolePermMapPipes = new HashMap<>();
		list.removeIf(perm -> !EcompPortalUtils.checkNameSpaceMatching(perm.getType(), app.getNameSpace()));
		// Update permissions in the ExternalAccess System
		HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
		if (!list.isEmpty()) {
			for (ExternalAccessPerms perm : list) {
				RoleFunction roleFunc =  updateRoleFunc.get(perm.getType().substring(app.getNameSpace().length()+1) + FUNCTION_PIPE + perm.getInstance() + FUNCTION_PIPE + perm.getAction());	
				if (roleFunc==null) {
					RoleFunction roleFuncPipeFilter =  updateRoleFunc.get(perm.getInstance());
					if(roleFuncPipeFilter == null)
					removePermForRole(perm, mapper, name, headers);
				}
				extRolePermMap.put(perm.getInstance(), perm);
				extRolePermMapPipes.put(
						perm.getType().substring(app.getNameSpace().length()+1) + FUNCTION_PIPE + perm.getInstance() + FUNCTION_PIPE + perm.getAction(), perm);
			}
		}
		response = true;
		if (!roleFunctionListNew.isEmpty()) {
			for (RoleFunction roleFunc : roleFunctionListNew) {
				if(roleFunc.getCode().contains(FUNCTION_PIPE)) {
					ExternalAccessPerms perm = extRolePermMapPipes.get(roleFunc.getCode());
					if (perm == null) {
						response = addFunctionsToRoleInExternalAuthSystem(updateExtRole, app, mapper, headers,
								roleFunc);
					}
				} else {
					if (!extRolePermMap.containsKey(EcompPortalUtils.getFunctionCode(roleFunc.getCode()))) {
						response = addFunctionsToRoleInExternalAuthSystem(updateExtRole, app, mapper, headers,
								roleFunc);
					}
				}
			}
		}
		return response;
	}
	
	/*
	 * Adds function to the role in the external auth system while editing a role or updating new functions to a role 
	 *
	 */
	private boolean addFunctionsToRoleInExternalAuthSystem(Role updateExtRole, EPApp app, ObjectMapper mapper,
			HttpHeaders headers, RoleFunction roleFunc) throws JsonProcessingException {
		boolean response;
		ExternalAccessRolePerms extRolePerms;
		ExternalAccessPerms extPerms;
		String code = "";
		String type = "";
		String action = "";
		if (roleFunc.getCode().contains(FUNCTION_PIPE)) {
			code = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
			type = getFunctionCodeType(roleFunc.getCode());
			action = getFunctionCodeAction(roleFunc.getCode());
		} else {
			code = roleFunc.getCode();
			type = roleFunc.getCode().contains("menu") ? "menu" : "url";
			action = "*";
		}
		extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, code, action);
		extRolePerms = new ExternalAccessRolePerms(extPerms,
				app.getNameSpace() + "."
						+ updateExtRole.getName().replaceAll(
								EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS,
								"_"));
		String updateRolePerms = mapper.writeValueAsString(extRolePerms);
		HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
		logger.debug(EELFLoggerDelegate.debugLogger, "updateRoleInExternalSystem: {} for POST: {}",
				CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms);
		ResponseEntity<String> addResponse = template.exchange(
				SystemProperties.getProperty(
						EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
				HttpMethod.POST, entity, String.class);
		if (addResponse.getStatusCode().value() != 201 && addResponse.getStatusCode().value()!= 409) {
			response = false;
			logger.debug(EELFLoggerDelegate.debugLogger,
					"updateRoleInExternalSystem: Connected to External Auth system but something went wrong! due to {} and statuscode: {}",
					addResponse.getStatusCode().getReasonPhrase(),
					addResponse.getStatusCode().value());
		} else {
			response = true;
			logger.debug(EELFLoggerDelegate.debugLogger,
					"updateRoleInExternalSystem: Finished adding permissions to roles in External Auth system {} and status code: {} ",
					updateRolePerms, addResponse.getStatusCode().value());
		}
		return response;
	}
	
	private void addPartnerHasRoleFunctionsToGlobalRole(List<ExternalAccessPerms> permslist, ObjectMapper mapper,
			EPApp app, Role updateExtRole) throws Exception {
		for (ExternalAccessPerms perm : permslist) {
			if (!EcompPortalUtils.checkNameSpaceMatching(perm.getType(), app.getNameSpace())) {
				ExternalAccessRolePerms extAddGlobalRolePerms = null;
				ExternalAccessPerms extAddPerms = null;
				extAddPerms = new ExternalAccessPerms(perm.getType(), perm.getInstance(), perm.getAction());
				extAddGlobalRolePerms = new ExternalAccessRolePerms(extAddPerms,
						app.getNameSpace() + "." + updateExtRole.getName().replaceAll(
								EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
				String addPerms = mapper.writeValueAsString(extAddGlobalRolePerms);
				HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
				HttpEntity<String> entity = new HttpEntity<>(addPerms, headers);
				logger.debug(EELFLoggerDelegate.debugLogger, "addPartnerHasRoleFunctionsToGlobalRole: {} ",
						CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
				try {
					ResponseEntity<String> addResponse = template
							.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
									+ "role/perm", HttpMethod.POST, entity, String.class);
					if (addResponse.getStatusCode().value() != 201) {
						logger.debug(EELFLoggerDelegate.debugLogger,
								"addPartnerHasRoleFunctionsToGlobalRole: While adding permission to the role in  External Auth system something went wrong! due to {} and statuscode: {}",
								addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
					} else {
						logger.debug(EELFLoggerDelegate.debugLogger,
								"addPartnerHasRoleFunctionsToGlobalRole: Finished adding permissions to roles in External Auth system and status code: {} ",
								addResponse.getStatusCode().value());
					}
				} catch (Exception e) {
					logger.error(EELFLoggerDelegate.errorLogger, "addPartnerHasRoleFunctionsToGlobalRole: Failed for POST request: {} due to ",
							addPerms, e);
				}
			}
		}
	}

	@SuppressWarnings("unchecked")
	private void addFunctionsTOGlobalRole(List<EPRole> epRoleList, Role updateExtRole, List<RoleFunction> roleFunctionListNew, ObjectMapper mapper, EPApp app, EPApp portalAppInfo)
			throws Exception {
		try {
			logger.debug(EELFLoggerDelegate.debugLogger, "Entering into addFunctionsTOGlobalRole");
			//GET Permissions from External Auth System
			JSONArray extPerms = getExtAuthPermissions(app);
			List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPerms);
			final Map<String, ExternalAccessPermsDetail> existingPermsWithRoles = new HashMap<>();
			final Map<String, ExternalAccessPermsDetail> existingPermsWithRolesWithPipes = new HashMap<>();
			final Map<String, RoleFunction> userRquestedFunctionsMap = new HashMap<>();
			final Map<String, RoleFunction> userRquestedFunctionsMapPipesFilter = new HashMap<>();
			for (ExternalAccessPermsDetail permDetail : permsDetailList) {
				existingPermsWithRoles.put(EcompPortalUtils.getFunctionCode(permDetail.getInstance()), permDetail);
				existingPermsWithRolesWithPipes.put(permDetail.getInstance(), permDetail);

			}
			// Add If function does not exists for role in External Auth System
			for (RoleFunction roleFunc : roleFunctionListNew) {
				String roleFuncCode = "";
				ExternalAccessPermsDetail permsDetail;
				if(roleFunc.getCode().contains(FUNCTION_PIPE)) {
					roleFuncCode = roleFunc.getCode();
					permsDetail = existingPermsWithRolesWithPipes.get(roleFunc.getCode());
				} else {
					roleFuncCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
					permsDetail = existingPermsWithRoles.get(roleFuncCode);
				}
				if (null == permsDetail.getRoles() || !permsDetail.getRoles()
						.contains(portalAppInfo.getNameSpace() + FUNCTION_PIPE + epRoleList.get(0).getName().replaceAll(
								EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"))) {
					addRoleFunctionsToGlobalRoleInExternalSystem(roleFunc, updateExtRole, mapper, app, portalAppInfo);
				}
				userRquestedFunctionsMap.put(roleFuncCode, roleFunc);
				userRquestedFunctionsMapPipesFilter.put(EcompPortalUtils.getFunctionCode(roleFuncCode), roleFunc);
			}			
			// Delete functions if exists in External Auth System but not in incoming request
			final Map<String, Long> epAppRoleFuncParams =  new HashMap<>();
			epAppRoleFuncParams.put("requestedAppId", app.getId());
			epAppRoleFuncParams.put("roleId",updateExtRole.getId());
			List<GlobalRoleWithApplicationRoleFunction> globalRoleFunctionList = dataAccessService.executeNamedQuery("getGlobalRoleForRequestedApp", epAppRoleFuncParams, null);
			for(GlobalRoleWithApplicationRoleFunction globalRoleFunc: globalRoleFunctionList){
				String globalRoleFuncWithoutPipes = "";
				RoleFunction roleFunc = null;
				if(globalRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)) {
					globalRoleFuncWithoutPipes = globalRoleFunc.getFunctionCd();
					roleFunc = userRquestedFunctionsMap.get(globalRoleFuncWithoutPipes);
				}else {
					globalRoleFuncWithoutPipes  = EcompPortalUtils.getFunctionCode(globalRoleFunc.getFunctionCd());
					roleFunc = userRquestedFunctionsMapPipesFilter.get(globalRoleFuncWithoutPipes);
				}
				if(roleFunc == null){
					ExternalAccessPermsDetail permDetailFromMap = globalRoleFunc.getFunctionCd().contains(FUNCTION_PIPE) ? existingPermsWithRolesWithPipes.get(globalRoleFuncWithoutPipes) : existingPermsWithRoles.get(globalRoleFuncWithoutPipes);
					ExternalAccessPerms perm = new ExternalAccessPerms(permDetailFromMap.getType(), EcompPortalUtils.getFunctionCode(permDetailFromMap.getInstance()), permDetailFromMap.getAction());
					String roleName = portalAppInfo.getNameSpace()+"."+globalRoleFunc.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_");
					HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
					removePermForRole(perm, mapper, roleName, headers);
				}
			}
			logger.debug(EELFLoggerDelegate.debugLogger, "Finished addFunctionsTOGlobalRole");
		} catch (Exception e) {
			logger.error(EELFLoggerDelegate.errorLogger, "addFunctionsTOGlobalRole: Failed",e);
			throw e;
		}
	}

	private void addRoleFunctionsToGlobalRoleInExternalSystem(RoleFunction addFunction, Role globalRole, ObjectMapper mapper, EPApp app,
			EPApp portalAppInfo) throws Exception {
		try {
			logger.debug(EELFLoggerDelegate.debugLogger, "Entering into addRoleFunctionsToGlobalRoleInExternalSystem");
			ExternalAccessRolePerms extAddRolePerms = null;
			ExternalAccessPerms extAddPerms = null;
			HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
				String code = "";
				String type = "";
				String action = "";
				if (addFunction.getCode().contains(FUNCTION_PIPE)) {
					code = EcompPortalUtils.getFunctionCode(addFunction.getCode());
					type = getFunctionCodeType(addFunction.getCode());
					action = getFunctionCodeAction(addFunction.getCode());
				} else {
					code = addFunction.getCode();
					type = addFunction.getCode().contains("menu") ? "menu" : "url";
					action = "*";
				}
				extAddPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, code, action);
				extAddRolePerms = new ExternalAccessRolePerms(extAddPerms,
						portalAppInfo.getNameSpace() + "." + globalRole.getName().replaceAll(
								EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
				String updateRolePerms = mapper.writeValueAsString(extAddRolePerms);
				HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
				logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: {} ",
						CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
				ResponseEntity<String> addResponse = template
						.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
								+ "role/perm", HttpMethod.POST, entity, String.class);
				if (addResponse.getStatusCode().value() != 201) {
					logger.debug(EELFLoggerDelegate.debugLogger,
							"addRoleFunctionsInExternalSystem: While adding permission to the role in  External Auth system something went wrong! due to {} and statuscode: {}",
							addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
				} else {
					logger.debug(EELFLoggerDelegate.debugLogger,
							"addRoleFunctionsInExternalSystem: Finished adding permissions to roles in External Auth system and status code: {} ",
							addResponse.getStatusCode().value());
				}
			logger.debug(EELFLoggerDelegate.debugLogger, "Finished addRoleFunctionsToGlobalRoleInExternalSystem");
		}catch(Exception e){
			logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionsToGlobalRoleInExternalSystem: Failed",e);
			throw e;
		}
	}

	private boolean addRoleFuncExtSysRestAPI(ObjectMapper addPermsMapper, ExternalAccessRolePerms extAddRolePerms,
			HttpHeaders headers) throws JsonProcessingException {
		boolean response;
		String updateRolePerms = addPermsMapper.writeValueAsString(extAddRolePerms);
		HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
		logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: {} for POST: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms);
		ResponseEntity<String> addResponse = template.exchange(
				SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
				HttpMethod.POST, entity, String.class);
		if (addResponse.getStatusCode().value() != 201 && addResponse.getStatusCode().value() != 409) {
			response = false;
			logger.debug(EELFLoggerDelegate.debugLogger,
					"addRoleFunctionsInExternalSystem: While adding permission to the role in  External Auth system something went wrong! due to {} and statuscode: {}",
					addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
		} else {
			response = true;
			logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: Finished adding permissions to roles in External Auth system {} and status code: {} ", updateRolePerms, addResponse.getStatusCode().value());
		}
		return response;
	}

	/**
	 * 
	 * It converts list of functions in updateExtRole parameter to the RoleFunction object
	 * 
	 * @param updateExtRole
	 * @return list of functions 
	 */
	@SuppressWarnings("unchecked")
	private List<RoleFunction> convertSetToListOfRoleFunctions(Role updateExtRole) {
		Set<RoleFunction> roleFunctionSetList = updateExtRole.getRoleFunctions();
		List<RoleFunction> roleFunctionList = new ArrayList<>();
		ObjectMapper roleFuncMapper = new ObjectMapper();
		Iterator<RoleFunction> itetaror = roleFunctionSetList.iterator();
		while (itetaror.hasNext()) {
			Object nextValue = itetaror.next();
			RoleFunction roleFunction = roleFuncMapper.convertValue(nextValue, RoleFunction.class);
			roleFunctionList.add(roleFunction);
		}
		return roleFunctionList.stream().distinct().collect(Collectors.toList());
	}

	/**
	 * It delete permissions/functions in the external auth system
	 * 
	 * @param perm
	 * @param permMapper
	 * @param name
	 * @param headers
	 * @throws JsonProcessingException 
	 * @throws Exception
	 */
	private void removePermForRole(ExternalAccessPerms perm, ObjectMapper permMapper, String name, HttpHeaders headers)
			throws ExternalAuthSystemException, JsonProcessingException {
		ExternalAccessRolePerms extAccessRolePerms = new ExternalAccessRolePerms(perm, name);
		String permDetails = permMapper.writeValueAsString(extAccessRolePerms);
		try{
		HttpEntity<String> deleteEntity = new HttpEntity<>(permDetails, headers);
		logger.debug(EELFLoggerDelegate.debugLogger, "removePermForRole: {} for DELETE: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, permDetails);
		ResponseEntity<String> deletePermResponse = template
				.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/"
						+ name + "/perm", HttpMethod.DELETE, deleteEntity, String.class);
		if (deletePermResponse.getStatusCode().value() != 200) {
			throw new ExternalAuthSystemException(deletePermResponse.getBody());
		}
		logger.debug(EELFLoggerDelegate.debugLogger, "removePermForRole: Finished deleting permission to role in External Auth system: {} and status code: {}",
				permDetails, deletePermResponse.getStatusCode().value());
		} catch(Exception e){
			if(e.getMessage().contains("404")){
				logger.error(EELFLoggerDelegate.errorLogger, "Failed to add role for DELETE request: {} due to {}", permDetails, e.getMessage());				
			} else{
				throw e;
			}
		}
	}

	/**
	 * It will create new role in the External Auth System
	 * 
	 * @param newRole
	 * @param app
	 * @return true if successfully added in the system else false
	 * @throws Exception
	 *             If fails to add role in the system
	 */
	private void addNewRoleInExternalSystem(List<EPRole> newRole, EPApp app) throws Exception, HttpClientErrorException {
		try{
		HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
		ObjectMapper mapper = new ObjectMapper();
		String addNewRole = "";
		ExternalAccessRole extRole = new ExternalAccessRole();
		extRole.setName(app.getNameSpace() + "." + newRole.get(0).getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
		extRole.setDescription(String.valueOf(newRole.get(0).getName()));
		addNewRole = mapper.writeValueAsString(extRole);
		HttpEntity<String> postEntity = new HttpEntity<>(addNewRole, headers);
		logger.debug(EELFLoggerDelegate.debugLogger, "addNewRoleInExternalSystem: {} for POST: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addNewRole);
		ResponseEntity<String> addNewRoleInExternalSystem = template.exchange(
				SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
				HttpMethod.POST, postEntity, String.class);
			if (addNewRoleInExternalSystem.getStatusCode().value() == 201) {
				logger.debug(EELFLoggerDelegate.debugLogger,
						"addNewRoleInExternalSystem: Finished adding into External Auth system for POST: {} and status code: {}",
						addNewRole, addNewRoleInExternalSystem.getStatusCode().value());
			}
		}catch(HttpClientErrorException ht){
			dataAccessService.deleteDomainObjects(EPRole.class, " role_id = "+ newRole.get(0).getId(), null);
			logger.error(EELFLoggerDelegate.debugLogger, "addNewRoleInExternalSystem: Failed to add in External Auth system and status code: {}",
					ht);
			throw new HttpClientErrorException(ht.getStatusCode());
		}
	}

	/**
	 * 
	 * It updates existing role in the External Auth System
	 * 
	 * @param addRole
	 *            It Contains role information
	 * @param app
	 * @return string which is formatted to match with the external auth system
	 * @throws JsonProcessingException
	 */
	private String updateExistingRoleInExternalSystem(Role addRole, EPApp app) throws JsonProcessingException {
		ObjectMapper mapper = new ObjectMapper();
		String addNewRole = "";
		ExternalAccessRole extRole = new ExternalAccessRole();
		extRole.setName(app.getNameSpace() + "." + addRole.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
		extRole.setDescription(String.valueOf(addRole.getName()));
		addNewRole = mapper.writeValueAsString(extRole);
		return addNewRole;
	}

	/**
	 * It create a role in the external auth system and then in our local 
	 * 
	 * @param addRoleInDB
	 * @param app
	 * @return true else false
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	@Transactional(rollbackFor = Exception.class)
	public boolean addRoleInEcompDB(Role addRoleInDB, EPApp app) throws Exception {		
		boolean result = false;
		EPRole epRole = null;
		Set<RoleFunction> roleFunctionList = addRoleInDB.getRoleFunctions();
		List<RoleFunction> roleFunctionListNew = new ArrayList<>();
		ObjectMapper mapper = new ObjectMapper();
		Iterator<RoleFunction> itetaror = roleFunctionList.iterator();
		while (itetaror.hasNext()) {
			Object nextValue = itetaror.next();
			RoleFunction roleFunction = mapper.convertValue(nextValue, RoleFunction.class);
			roleFunctionListNew.add(roleFunction);
		}
		List<RoleFunction> listWithoutDuplicates = roleFunctionListNew.stream().distinct().collect(Collectors.toList());
		try {
			if (addRoleInDB.getId() == null) { // check if it is new role
				if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
					checkIfRoleExitsInExternalSystem(addRoleInDB, app);
				}
				EPRole epRoleNew = new EPRole();
				epRoleNew.setActive(addRoleInDB.getActive());
				epRoleNew.setName(addRoleInDB.getName());
				epRoleNew.setPriority(addRoleInDB.getPriority());
				if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
					epRoleNew.setAppId(null);
				} else {
					epRoleNew.setAppId(app.getId());
				}
				dataAccessService.saveDomainObject(epRoleNew, null);
				List<EPRole> getRoleCreated = null;
				final Map<String, String> epAppRoleParams =  new HashMap<>();
				final Map<String, String> epAppPortalRoleParams =  new HashMap<>();
				if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
					epAppRoleParams.put("appId", String.valueOf(app.getId()));
					epAppRoleParams.put(APP_ROLE_NAME_PARAM, addRoleInDB.getName());
					List<EPRole> roleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, epAppRoleParams, null);
					EPRole epUpdateRole = roleCreated.get(0);
					epUpdateRole.setAppRoleId(epUpdateRole.getId());
					dataAccessService.saveDomainObject(epUpdateRole, null);
					getRoleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, epAppRoleParams, null);
				} else {
					epAppPortalRoleParams.put(APP_ROLE_NAME_PARAM, addRoleInDB.getName());
					getRoleCreated = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, epAppPortalRoleParams, null);
				}
				// Add role in External Auth system
				if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
					addNewRoleInExternalSystem(getRoleCreated, app);
				}
				result = true;
			} else { // if role already exists then update it
				EPRole globalRole = null;
				List<EPRole> applicationRoles;
				List<EPRole> globalRoleList = getGlobalRolesOfPortal();
				boolean isGlobalRole = false;
				if (!globalRoleList.isEmpty()) {
					EPRole role = globalRoleList.stream().filter(x -> addRoleInDB.getId().equals(x.getId())).findAny()
							.orElse(null);
					if (role != null) {
						globalRole = role;
						isGlobalRole = true;
					}
				}
				if (app.getId().equals(PortalConstants.PORTAL_APP_ID)
						|| (globalRole != null && app.getId() != globalRole.getAppId())) {
					applicationRoles = getPortalAppRoleInfo(addRoleInDB.getId());
				} else {
					applicationRoles = getPartnerAppRoleInfo(addRoleInDB.getId(), app);
				}
				if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
					updateRoleInExternalSystem(addRoleInDB, app, isGlobalRole);
					// Add all user to the re-named role in external auth system
					if (!applicationRoles.isEmpty()
							&& !addRoleInDB.getName().equals(applicationRoles.get(0).getName())) {
						bulkUploadUsersSingleRole(app.getUebKey(), applicationRoles.get(0).getId(),
								addRoleInDB.getName());
					}
				}
				deleteRoleFunction(app, applicationRoles);
				if (!applicationRoles.isEmpty()) {
					epRole = applicationRoles.get(0);
					epRole.setName(addRoleInDB.getName());
					epRole.setPriority(addRoleInDB.getPriority());
					epRole.setActive(addRoleInDB.getActive());
					if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
						epRole.setAppId(null);
						epRole.setAppRoleId(null);
					} else if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)
							&& applicationRoles.get(0).getAppRoleId() == null) {
						epRole.setAppRoleId(epRole.getId());
					}
					dataAccessService.saveDomainObject(epRole, null);
				}
				Long roleAppId = null;
				if (globalRole != null && !app.getId().equals(globalRole.getAppId()))
					roleAppId = PortalConstants.PORTAL_APP_ID;
				saveRoleFunction(listWithoutDuplicates, app, applicationRoles, roleAppId);
				result = true;
			}
		} catch (Exception e) {
			logger.error(EELFLoggerDelegate.errorLogger, "addRoleInEcompDB is failed", e);
			throw e;
		}
		return result;
	}

	/**
	 * 
	 * It validates whether role exists in external auth system
	 * 
	 * @param checkRole
	 * @param app
	 * @throws Exception
	 * 					If role exits
	 */
	private void checkIfRoleExitsInExternalSystem(Role checkRole, EPApp app) throws Exception {
		getNameSpaceIfExists(app);
		HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
		String roleName = app.getNameSpace() + "." + checkRole.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_");
		HttpEntity<String> checkRoleEntity = new HttpEntity<>(headers);
		logger.debug(EELFLoggerDelegate.debugLogger, "checkIfRoleExitsInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
		ResponseEntity<String> checkRoleInExternalSystem = template
				.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "roles/"
						+ roleName, HttpMethod.GET, checkRoleEntity, String.class);
		if (!checkRoleInExternalSystem.getBody().equals(IS_EMPTY_JSON_STRING)) {
			logger.debug("checkIfRoleExitsInExternalSystem: Role already exists in external system {} and status code: {} ", checkRoleInExternalSystem.getBody(), checkRoleInExternalSystem.getStatusCode().value());
			throw new ExternalAuthSystemException(" Role already exists in external system");
		}
	}

	/**
	 * It saves list of functions to the role in portal
	 * 
	 * @param roleFunctionListNew
	 * @param app
	 * @param applicationRoles
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	private void saveRoleFunction(List<RoleFunction> roleFunctionListNew, EPApp app, List<EPRole> applicationRoles ,Long roleAppId)
			throws Exception {	
		final Map<String, String> getAppFunctionParams = new HashMap<>(); 

		for (RoleFunction roleFunc : roleFunctionListNew) {
			String code = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
			EPAppRoleFunction appRoleFunc = new EPAppRoleFunction();
			appRoleFunc.setAppId(app.getId());
			appRoleFunc.setRoleId(applicationRoles.get(0).getId());
			appRoleFunc.setRoleAppId(String.valueOf(roleAppId));
			getAppFunctionParams.put("appId", String.valueOf(app.getId()));
			getAppFunctionParams.put(FUNCTION_CODE_PARAMS, roleFunc.getCode());
			// query to check if function code has pipes
			List<CentralV2RoleFunction> roleFunction = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, getAppFunctionParams, null);
			if(roleFunction.isEmpty()){
				getAppFunctionParams.put(FUNCTION_CODE_PARAMS, code);
				roleFunction = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, getAppFunctionParams, null);
			}
			if(roleFunction.size() > 1){
				CentralV2RoleFunction getExactFunctionCode = appFunctionListFilter(code, roleFunction);
				appRoleFunc.setCode(getExactFunctionCode.getCode());
			} else{
				appRoleFunc.setCode(roleFunction.get(0).getCode());
			}
			
			dataAccessService.saveDomainObject(appRoleFunc, null);
		}
	}

	/**
	 * 
	 * It filters the app functions which starts with similar name in the result set
	 * 
	 * @param roleFunc
	 * @param roleFunction
	 * @return CentralRoleFunction 
	 */
	private CentralV2RoleFunction appFunctionListFilter(String roleFuncCode, List<CentralV2RoleFunction> roleFunction) {
		final Map<String, CentralV2RoleFunction> appFunctionsFilter = new HashMap<>(); 
		final Map<String, CentralV2RoleFunction> appFunctionsFilterPipes = new HashMap<>(); 
		CentralV2RoleFunction getExactFunctionCode = null;
		for(CentralV2RoleFunction cenRoleFunction : roleFunction){
			appFunctionsFilter.put(cenRoleFunction.getCode(), cenRoleFunction);
			appFunctionsFilterPipes.put(EcompPortalUtils.getFunctionCode(cenRoleFunction.getCode()), cenRoleFunction);
		}
		getExactFunctionCode = appFunctionsFilter.get(roleFuncCode);
		if(getExactFunctionCode == null){
			getExactFunctionCode = appFunctionsFilterPipes.get(roleFuncCode);
		}
		return getExactFunctionCode;
	}
	
	/**
	 * It deletes all EPAppRoleFunction records in the portal
	 * 
	 * @param app
	 * @param role
	 */
	@SuppressWarnings("unchecked")
	private void deleteRoleFunction(EPApp app, List<EPRole> role) {
		final Map<String, Long> appRoleFuncsParams = new HashMap<>();
		appRoleFuncsParams.put("appId", app.getId());
		appRoleFuncsParams.put("roleId", role.get(0).getId());
		List<EPAppRoleFunction> appRoleFunctionList =  dataAccessService.executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", appRoleFuncsParams, null);
		if (!appRoleFunctionList.isEmpty()) {
			for (EPAppRoleFunction approleFunction : appRoleFunctionList) {
				dataAccessService.deleteDomainObject(approleFunction, null);
			}
		}
	}
	
	@Override
	@SuppressWarnings("unchecked")
	public List<EPUser> getUser(String loginId) throws InvalidUserException{
		final Map<String, String> userParams = new HashMap<>();
		userParams.put("org_user_id", loginId);
		List<EPUser> userList = dataAccessService.executeNamedQuery("getEPUserByOrgUserId", userParams, null);
		if (userList.isEmpty()) {
			throw new InvalidUserException("User not found");
		}
		return userList;
	}

	@Override
	public String getV2UserWithRoles(String loginId, String uebkey) throws Exception {
		final Map<String, String> params = new HashMap<>();
		List<EPUser> userList = null;
		CentralV2User cenV2User = null;
		String result = null;
		try {
			params.put("orgUserIdValue", loginId);
			List<EPApp> appList = getApp(uebkey);
			if (!appList.isEmpty()) {
				userList = getUser(loginId);
				if (!userList.isEmpty()) {
					ObjectMapper mapper = new ObjectMapper();
					cenV2User = getV2UserAppRoles(loginId, uebkey);
					result = mapper.writeValueAsString(cenV2User);
				} else if (userList.isEmpty()) {
					throw new InvalidUserException("User not found");
				}
			} else {
				throw new InactiveApplicationException("Application not found");
			}
		} catch (Exception e) {
			logger.error(EELFLoggerDelegate.errorLogger, "getUser: failed", e);
			throw e;
		}
		return result;
	}

	@Override
	public List<CentralV2Role> getRolesForApp(String uebkey) throws Exception {
		logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Entering into getRolesForApp");
		List<CentralV2Role> roleList = new ArrayList<>();
		final Map<String, Long> params = new HashMap<>();
		try {
			List<EPApp> app = getApp(uebkey);
			List<EPRole> appRolesList = getAppRoles(app.get(0).getId());
			roleList = createCentralRoleObject(app, appRolesList, roleList, params);
			if(app.get(0).getId() != PortalConstants.PORTAL_APP_ID){
			    List<CentralV2Role> globalRoleList = getGlobalRolesOfApplication(app.get(0).getId());
				List<EPRole> globalRolesList = getGlobalRolesOfPortal();
			    List<CentralV2Role> portalsGlobalRolesFinlaList = new ArrayList<>();
				if (!globalRolesList.isEmpty()) {
					for (EPRole eprole : globalRolesList) {
						CentralV2Role cenRole = convertRoleToCentralV2Role(eprole);
						portalsGlobalRolesFinlaList.add(cenRole);
					}
					roleList.addAll(globalRoleList);
					for (CentralV2Role role : portalsGlobalRolesFinlaList) {
						CentralV2Role result = roleList.stream()
									.filter(x -> role.getId().equals(x.getId())).findAny().orElse(null);
							if (result == null)
								roleList.add(role);
					}
				} else {
					for (EPRole role : globalRolesList) {
						CentralV2Role cenRole = convertRoleToCentralV2Role(role);
						roleList.add(cenRole);
					}
				}
			}
		} catch (Exception e) {
			logger.error(EELFLoggerDelegate.errorLogger, "getRolesForApp: Failed!", e);
			throw e;
		}
		logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Finished!");
		return roleList.stream().distinct().collect(Collectors.toList());
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<CentralV2RoleFunction> getRoleFuncList(String uebkey) throws Exception {
		EPApp app = getApp(uebkey).get(0);
		List<CentralV2RoleFunction> finalRoleList = new ArrayList<>();
		final Map<String, Long> params = new HashMap<>();
		params.put(APP_ID, app.getId());
		List<CentralV2RoleFunction> getRoleFuncList = dataAccessService.executeNamedQuery("getAllRoleFunctions", params, null);
		for (CentralV2RoleFunction roleFuncItem : getRoleFuncList) {
			String code = EcompPortalUtils.getFunctionCode(roleFuncItem.getCode());
			String type = getFunctionCodeType(roleFuncItem.getCode());
			String action = getFunctionCodeAction(roleFuncItem.getCode());
			roleFuncItem.setCode(EPUserUtils.decodeFunctionCode(code));
			roleFuncItem.setType(type);
			roleFuncItem.setAction(action);
			finalRoleList.add(roleFuncItem);
		}
		return finalRoleList;
	}


	@Override
	public String getFunctionCodeAction(String roleFuncItem) {
		return (!roleFuncItem.contains(FUNCTION_PIPE)) ? "*"
				: EcompPortalUtils.getFunctionAction(roleFuncItem);
	}

	@Override
	public String getFunctionCodeType(String roleFuncItem) {
		String type = null;
		if ((roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("menu"))
				|| (!roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("menu"))) {
			type = "menu";
		} else if (checkIfCodeHasNoPipesAndHasTypeUrl(roleFuncItem)
				||checkIfCodeHasPipesAndHasTypeUrl(roleFuncItem)
				||checkIfCodeHasNoPipesAndHasNoTypeUrl(roleFuncItem)) {
			type = "url";
		} else if (roleFuncItem.contains(FUNCTION_PIPE)
				&& (!roleFuncItem.contains("menu") || roleFuncItem.contains("url"))) {
			type = EcompPortalUtils.getFunctionType(roleFuncItem);
		}
		return type;
	}

	/**
	 * 
	 * It check whether function code has no pipes and no url string in it
	 * 
	 * @param roleFuncItem
	 * @return true or false
	 */
	private boolean checkIfCodeHasNoPipesAndHasNoTypeUrl(String roleFuncItem) {
		return !roleFuncItem.contains(FUNCTION_PIPE) && !roleFuncItem.contains("url");
	}
	
	/**
	 * 
	 * It check whether function code has pipes and url string in it  
	 * 
	 * @param roleFuncItem
	 * @return true or false
	 */
	private boolean checkIfCodeHasPipesAndHasTypeUrl(String roleFuncItem) {
		return roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("url");
	}

	/**
	 * 
	 * It check whether function code has no pipes and has url string in it 
	 * 
	 * @param roleFuncItem
	 * @return true or false
	 */
	private boolean checkIfCodeHasNoPipesAndHasTypeUrl(String roleFuncItem) {
		return !roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("url");
	}

	/**
	 * It returns user detail information which is deep copy of EPUser.class object
	 * 
	 * @param userInfo
	 * @param userAppSet
	 * @param app
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	private CentralV2User createEPUser(EPUser userInfo, Set<EPUserApp> userAppSet, EPApp app) throws Exception {
		final Map<String, Long> params = new HashMap<>();
		CentralV2User userAppList = new CentralV2User();
		CentralV2User user1 = null;
		final Map<String, Long> params1 = new HashMap<>();
		List<EPRole> globalRoleList = new ArrayList<>();
		try {
			if (app.getId() != PortalConstants.PORTAL_APP_ID) {
				params1.put("userId", userInfo.getId());
				params1.put("appId", app.getId());
				globalRoleList = dataAccessService.executeNamedQuery("userAppGlobalRoles", params1, null);
			}
			userAppList.setUserApps(new TreeSet<CentralV2UserApp>());
			for (EPUserApp userApp : userAppSet) {
				if (userApp.getRole().getActive()) {
					EPApp epApp = userApp.getApp();
					String globalRole = userApp.getRole().getName().toLowerCase();
					if (((epApp.getId().equals(app.getId()))
							&& (!userApp.getRole().getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)))
							|| ((epApp.getId().equals(PortalConstants.PORTAL_APP_ID))
									&& (globalRole.toLowerCase().startsWith("global_")))) {
						CentralV2UserApp cua = new CentralV2UserApp();
						cua.setUserId(null);
						CentralApp cenApp = new CentralApp(1L, epApp.getCreated(), epApp.getModified(),
								epApp.getCreatedId(), epApp.getModifiedId(), epApp.getRowNum(), epApp.getName(),
								epApp.getImageUrl(), epApp.getDescription(), epApp.getNotes(), epApp.getUrl(),
								epApp.getAlternateUrl(), epApp.getAppRestEndpoint(), epApp.getMlAppName(),
								epApp.getMlAppAdminId(), String.valueOf(epApp.getMotsId()), epApp.getAppPassword(),
								String.valueOf(epApp.getOpen()), String.valueOf(epApp.getEnabled()),
								epApp.getThumbnail(), epApp.getUsername(), epApp.getUebKey(), epApp.getUebSecret(),
								epApp.getUebTopicName());
						cua.setApp(cenApp);
						Long appId = null;
						if (globalRole.toLowerCase().startsWith("global_")
								&& epApp.getId().equals(PortalConstants.PORTAL_APP_ID)
								&& !epApp.getId().equals(app.getId())) {
							appId = app.getId();
							EPRole result = null;
							if (globalRoleList.size() > 0)
								result = globalRoleList.stream()
										.filter(x -> userApp.getRole().getId().equals(x.getId())).findAny()
										.orElse(null);
							if (result == null)
								continue;
						} else {
							appId = userApp.getApp().getId();
						}
						params.put("roleId", userApp.getRole().getId());
						params.put(APP_ID, appId);
						List<CentralV2RoleFunction> appRoleFunctionList = dataAccessService
								.executeNamedQuery("getAppRoleFunctionList", params, null);
						SortedSet<CentralV2RoleFunction> roleFunctionSet = new TreeSet<>();
						for (CentralV2RoleFunction roleFunc : appRoleFunctionList) {
							String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
							String type = getFunctionCodeType(roleFunc.getCode());
							String action = getFunctionCodeAction(roleFunc.getCode());
							CentralV2RoleFunction cenRoleFunc = new CentralV2RoleFunction(roleFunc.getId(),
									functionCode, roleFunc.getName(), null, type, action, null);
							roleFunctionSet.add(cenRoleFunc);
						}
						Long userRoleId = null;
						if (globalRole.toLowerCase().startsWith("global_")
								|| epApp.getId().equals(PortalConstants.PORTAL_APP_ID)) {
							userRoleId = userApp.getRole().getId();
						} else {
							userRoleId = userApp.getRole().getAppRoleId();
						}
						CentralV2Role cenRole = new CentralV2Role(userRoleId, userApp.getRole().getCreated(),
								userApp.getRole().getModified(), userApp.getRole().getCreatedId(),
								userApp.getRole().getModifiedId(), userApp.getRole().getRowNum(),
								userApp.getRole().getName(), userApp.getRole().getActive(),
								userApp.getRole().getPriority(), roleFunctionSet, null, null);
						cua.setRole(cenRole);

						userAppList.getUserApps().add(cua);
					}
				}
			}

			user1 = new CentralV2User(null, userInfo.getCreated(), userInfo.getModified(), userInfo.getCreatedId(),
					userInfo.getModifiedId(), userInfo.getRowNum(), userInfo.getOrgId(), userInfo.getManagerId(),
					userInfo.getFirstName(), userInfo.getMiddleInitial(), userInfo.getLastName(), userInfo.getPhone(),
					userInfo.getFax(), userInfo.getCellular(), userInfo.getEmail(), userInfo.getAddressId(),
					userInfo.getAlertMethodCd(), userInfo.getHrid(), userInfo.getOrgUserId(), userInfo.getOrgCode(),
					userInfo.getAddress1(), userInfo.getAddress2(), userInfo.getCity(), userInfo.getState(),
					userInfo.getZipCode(), userInfo.getCountry(), userInfo.getOrgManagerUserId(),
					userInfo.getLocationClli(), userInfo.getBusinessCountryCode(), userInfo.getBusinessCountryName(),
					userInfo.getBusinessUnit(), userInfo.getBusinessUnitName(), userInfo.getDepartment(),
					userInfo.getDepartmentName(), userInfo.getCompanyCode(), userInfo.getCompany(),
					userInfo.getZipCodeSuffix(), userInfo.getJobTitle(), userInfo.getCommandChain(),
					userInfo.getSiloStatus(), userInfo.getCostCenter(), userInfo.getFinancialLocCode(),
					userInfo.getLoginId(), userInfo.getLoginPwd(), userInfo.getLastLoginDate(), userInfo.getActive(),
					userInfo.getInternal(), userInfo.getSelectedProfileId(), userInfo.getTimeZoneId(),
					userInfo.isOnline(), userInfo.getChatId(), userAppList.getUserApps(), null);
		} catch (Exception e) {
			logger.error(EELFLoggerDelegate.errorLogger, "createEPUser: createEPUser failed", e);
			throw e;
		}
		return user1;
	}

	@Override
	public CentralV2Role getRoleInfo(Long roleId, String uebkey) throws Exception {
		final Map<String, Long> params = new HashMap<>();
		List<CentralV2Role> roleList = new ArrayList<>();
		CentralV2Role cenRole = new CentralV2Role();
		List<EPRole> roleInfo = null;
		List<EPApp> app = null;
		try {
			app = getApp(uebkey);
			if (app.isEmpty()) {
				throw new InactiveApplicationException("Application not found");
			}
			if (app.get(0).getId() != PortalConstants.PORTAL_APP_ID) {
				List<EPRole> globalRoleList = new ArrayList<>();
				globalRoleList = getGlobalRolesOfPortal();
				if (globalRoleList.size() > 0) {
					EPRole result = globalRoleList.stream().filter(x -> roleId.equals(x.getId())).findAny()
							.orElse(null);
					if (result != null)
						return getGlobalRoleForRequestedApp(app.get(0).getId(), roleId);
				}
			}
			if (app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
				roleInfo = getPortalAppRoleInfo(roleId);
			} else {
				roleInfo = getPartnerAppRoleInfo(roleId, app.get(0));
			}
			roleList = createCentralRoleObject(app, roleInfo, roleList, params);
			if (roleList.isEmpty()) {
				return cenRole;
			}

		} catch (Exception e) {
			logger.error(EELFLoggerDelegate.errorLogger, "getRoleInfo: failed", e);
			throw e;

		}
		return roleList.get(0);
	}

	@SuppressWarnings("unchecked")
	private List<EPRole> getPartnerAppRoleInfo(Long roleId, EPApp app) {
		List<EPRole> roleInfo;
		final Map<String, Long> getPartnerAppRoleParams = new HashMap<>();
		getPartnerAppRoleParams.put("appRoleId", roleId);
		getPartnerAppRoleParams.put("appId", app.getId());				
		roleInfo = dataAccessService.executeNamedQuery("getPartnerAppRoleByRoleId", getPartnerAppRoleParams, null);
		if(roleInfo.isEmpty()) {
			getPartnerAppRoleParams.put("appRoleId", roleId);
			roleInfo = dataAccessService.executeNamedQuery("getPartnerAppRoleById", getPartnerAppRoleParams, null);
		}
		return roleInfo;
	}

	@SuppressWarnings("unchecked")
	private List<EPRole> getPortalAppRoleInfo(Long roleId) {
		List<EPRole> roleInfo;
		final Map<String, Long> getPortalAppRoleParams = new HashMap<>();
		getPortalAppRoleParams.put("roleId", roleId);
		roleInfo = dataAccessService.executeNamedQuery("getPortalAppRoleByRoleId", getPortalAppRoleParams, null);
		return roleInfo;
	}
	
	/**
	 * 
	 * It returns list of app roles along with role functions and which went through deep copy
	 * 
	 * @param app
	 * @param roleInfo
	 * @param roleList
	 * @param params
	 * @return
	 * @throws DecoderException 
	 */
	@SuppressWarnings("unchecked")
	private List<CentralV2Role> createCentralRoleObject(List<EPApp> app, List<EPRole> roleInfo,
			List<CentralV2Role> roleList, Map<String, Long> params) throws RoleFunctionException {
		for (EPRole role : roleInfo) {
			params.put("roleId", role.getId());
			params.put(APP_ID, app.get(0).getId());
			List<CentralV2RoleFunction> cenRoleFuncList = dataAccessService.executeNamedQuery("getAppRoleFunctionList",
					params, null);
			SortedSet<CentralV2RoleFunction> roleFunctionSet = new TreeSet<>();
			for (CentralV2RoleFunction roleFunc : cenRoleFuncList) {
				String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
				functionCode = EPUserUtils.decodeFunctionCode(functionCode);
				String type = getFunctionCodeType(roleFunc.getCode());
				String action = getFunctionCodeAction(roleFunc.getCode());
				CentralV2RoleFunction cenRoleFunc = new CentralV2RoleFunction(role.getId(), functionCode,
						roleFunc.getName(), null, type, action, null);
				roleFunctionSet.add(cenRoleFunc);
			}
			SortedSet<CentralV2Role> childRoles = new TreeSet<>();
			SortedSet<CentralV2Role> parentRoles = new TreeSet<>();
			CentralV2Role cenRole = null;
			if (role.getAppRoleId() == null) {
				cenRole = new CentralV2Role(role.getId(), role.getCreated(), role.getModified(), role.getCreatedId(),
						role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(), role.getPriority(),
						roleFunctionSet, childRoles, parentRoles);
			} else {
				cenRole = new CentralV2Role(role.getAppRoleId(), role.getCreated(), role.getModified(),
						role.getCreatedId(), role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(),
						role.getPriority(), roleFunctionSet, childRoles, parentRoles);
			}
			roleList.add(cenRole);
		}
		return roleList;
	}

	@SuppressWarnings("unchecked")
	@Override
	public CentralV2RoleFunction getRoleFunction(String functionCode, String uebkey) throws Exception {
		String code = EcompPortalUtils.getFunctionCode(functionCode);
		String encodedCode = encodeFunctionCode(code);
		CentralV2RoleFunction roleFunc = null;
		EPApp app = getApp(uebkey).get(0);
		List<CentralV2RoleFunction> getRoleFuncList = null;
		final Map<String, String> params = new HashMap<>();
		try {
			params.put(FUNCTION_CODE_PARAMS, functionCode);
			params.put(APP_ID, String.valueOf(app.getId()));
			getRoleFuncList = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null);
			if (getRoleFuncList.isEmpty()) {
				params.put(FUNCTION_CODE_PARAMS, encodedCode);
				getRoleFuncList = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null);
				if (getRoleFuncList.isEmpty()) {
					return roleFunc;
				}
			}
			if (getRoleFuncList.size() > 1) {
				CentralV2RoleFunction cenV2RoleFunction = appFunctionListFilter(encodedCode, getRoleFuncList);
				if (cenV2RoleFunction == null)
					return roleFunc;
				roleFunc = checkIfPipesExitsInFunctionCode(cenV2RoleFunction);
			} else {
				// Check even if single record have pipes
				if (!getRoleFuncList.isEmpty() && getRoleFuncList.get(0).getCode().contains(FUNCTION_PIPE)) {
					roleFunc = checkIfPipesExitsInFunctionCode(getRoleFuncList.get(0));
				} else {
					roleFunc = getRoleFuncList.get(0);
				}
			}
		} catch (Exception e) {
			logger.error(EELFLoggerDelegate.errorLogger, "getRoleFunction: failed", e);
			throw e;
		}
		return roleFunc;
	}

	private CentralV2RoleFunction checkIfPipesExitsInFunctionCode(CentralV2RoleFunction getRoleFuncList) {
		CentralV2RoleFunction roleFunc;
		String functionCodeFormat = getRoleFuncList.getCode();
		if (functionCodeFormat.contains(FUNCTION_PIPE)) {
			String newfunctionCodeFormat = EcompPortalUtils.getFunctionCode(functionCodeFormat);
			String newfunctionTypeFormat = EcompPortalUtils.getFunctionType(functionCodeFormat);
			String newfunctionActionFormat = EcompPortalUtils.getFunctionAction(functionCodeFormat);
			roleFunc = new CentralV2RoleFunction(getRoleFuncList.getId(), newfunctionCodeFormat,
					getRoleFuncList.getName(), getRoleFuncList.getAppId(), newfunctionTypeFormat, newfunctionActionFormat,
					getRoleFuncList.getEditUrl());
		} else {
			roleFunc = new CentralV2RoleFunction(getRoleFuncList.getId(), functionCodeFormat,
					getRoleFuncList.getName(), getRoleFuncList.getAppId(),
					getRoleFuncList.getEditUrl());
		}
		return roleFunc;
	}

	@Override
	public boolean saveCentralRoleFunction(CentralV2RoleFunction domainCentralRoleFunction, EPApp app) throws Exception {
		boolean saveOrUpdateFunction = false;
		try {
			domainCentralRoleFunction.setCode(encodeFunctionCode(domainCentralRoleFunction.getCode()));
			final Map<String, String> functionParams = new HashMap<>();
			functionParams.put("appId", String.valueOf(app.getId()));
			if(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
				addRoleFunctionInExternalSystem(domainCentralRoleFunction, app);			
			}
			if(domainCentralRoleFunction.getType() != null && domainCentralRoleFunction.getAction() != null){
				domainCentralRoleFunction.setCode(domainCentralRoleFunction.getType()+
					FUNCTION_PIPE+domainCentralRoleFunction.getCode()+FUNCTION_PIPE+domainCentralRoleFunction.getAction());
			}
			domainCentralRoleFunction.setAppId(app.getId());
			dataAccessService.saveDomainObject(domainCentralRoleFunction, null);
			saveOrUpdateFunction = true;
		} catch (Exception e) {
			logger.error(EELFLoggerDelegate.errorLogger, "saveCentralRoleFunction: failed", e);
			throw e;
		}
		return saveOrUpdateFunction;
	}
	
	/**
	 * It creates application permission in external auth system
	 * 
	 * @param domainCentralRoleFunction
	 * @param app
	 * @throws Exception
	 */
	private void addRoleFunctionInExternalSystem(CentralV2RoleFunction domainCentralRoleFunction, EPApp app)
			throws Exception {
		ObjectMapper mapper = new ObjectMapper();
		ExternalAccessPerms extPerms = new ExternalAccessPerms();
		HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); 
		String type = "";
		String instance = "";
		String action = "";
		if((domainCentralRoleFunction.getType()!=null && domainCentralRoleFunction.getAction()!=null) || domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE)){
			type =  domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE) ? EcompPortalUtils.getFunctionType(domainCentralRoleFunction.getCode()) : domainCentralRoleFunction.getType(); 
			instance =  domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE) ?  EcompPortalUtils.getFunctionCode(domainCentralRoleFunction.getCode()) : domainCentralRoleFunction.getCode();
			action =  domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE) ? EcompPortalUtils.getFunctionAction(domainCentralRoleFunction.getCode()) : domainCentralRoleFunction.getAction();
		} else{
			type = domainCentralRoleFunction.getCode().contains("menu") ? "menu" : "url";
			instance = domainCentralRoleFunction.getCode();
			action = "*"; 
		}		
		// get Permissions from External Auth System
		JSONArray extPermsList = getExtAuthPermissions(app);
		List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPermsList);
		String requestedPerm = type+FUNCTION_PIPE+instance+FUNCTION_PIPE+action;
		boolean checkIfFunctionsExits = permsDetailList.stream().anyMatch(permsDetail -> permsDetail.getInstance().equals(requestedPerm));
		if (!checkIfFunctionsExits) {
			try {
				extPerms.setAction(action);
				extPerms.setInstance(instance);
				extPerms.setType(app.getNameSpace() + "." + type);
				extPerms.setDescription(domainCentralRoleFunction.getName());
				String addFunction = mapper.writeValueAsString(extPerms);
				HttpEntity<String> entity = new HttpEntity<>(addFunction, headers);
				logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} for POST: {}" , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addFunction);
				ResponseEntity<String> addPermResponse= template.exchange(
						SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
						HttpMethod.POST, entity, String.class);
				logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: Finished adding permission for POST: {} and status code: {} ", addPermResponse.getStatusCode().value(), addFunction);
			} catch(HttpClientErrorException e){
				logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to add function in external central auth system", e);
				EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
				throw e;
			}catch (Exception e) {
				logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionInExternalSystem: Failed to add fucntion in external central auth system",
						e);
				throw e;
			}
		} else {
			try {
				extPerms.setAction(action);
				extPerms.setInstance(instance);
				extPerms.setType(app.getNameSpace() + "." + type);
				extPerms.setDescription(domainCentralRoleFunction.getName());
				String updateRoleFunction = mapper.writeValueAsString(extPerms);
				HttpEntity<String> entity = new HttpEntity<>(updateRoleFunction, headers);
				logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} for PUT: {}" , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRoleFunction);
				ResponseEntity<String> updatePermResponse = template.exchange(
						SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
						HttpMethod.PUT, entity, String.class);
				logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: Finished updating permission in External Auth system {} and response: {} ", updateRoleFunction, updatePermResponse.getStatusCode().value());
			} catch(HttpClientErrorException e){
				logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to add function in external central auth system", e);
				EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
				throw e;
			} catch (Exception e) {
				logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionInExternalSystem: Failed to update function in external central auth system",e);
				throw e;
			}
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean deleteCentralRoleFunction(String code, EPApp app) {
		boolean deleteFunctionResponse = false;
		try {
			final Map<String, String> params = new HashMap<>();
			params.put(FUNCTION_CODE_PARAMS, code);
			params.put(APP_ID, String.valueOf(app.getId()));
			List<CentralV2RoleFunction> domainCentralRoleFunction = dataAccessService
					.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null);
			CentralV2RoleFunction appFunctionCode = appFunctionListFilter(code, domainCentralRoleFunction);
			if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
				deleteRoleFunctionInExternalSystem(appFunctionCode, app);
				// Delete role function dependency records
				deleteAppRoleFunctions(appFunctionCode.getCode(), app);
			}
			dataAccessService.deleteDomainObject(appFunctionCode, null);
			deleteFunctionResponse = true;
		} catch (Exception e) {
			logger.error(EELFLoggerDelegate.errorLogger, "deleteCentralRoleFunction: failed", e);
		}
		return deleteFunctionResponse;
	}

	/**
	 * It deletes app function record in portal 
	 * 
	 * @param code
	 * @param app
	 */
	private void deleteAppRoleFunctions(String code, EPApp app) {
		dataAccessService.deleteDomainObjects(EPAppRoleFunction.class,
				APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + code + "'", null);
	}
	
	/**
	 * 
	 * It deletes permission in the external auth system  
	 * 
	 * @param domainCentralRoleFunction
	 * @param app
	 * @throws Exception
	 */
	private void deleteRoleFunctionInExternalSystem(CentralV2RoleFunction domainCentralRoleFunction, EPApp app)
			throws Exception {
		try {
			ObjectMapper mapper = new ObjectMapper();
			ExternalAccessPerms extPerms = new ExternalAccessPerms();
			String instanceValue = EcompPortalUtils.getFunctionCode(domainCentralRoleFunction.getCode());
			String checkType = getFunctionCodeType(domainCentralRoleFunction.getCode());
			String actionValue = getFunctionCodeAction(domainCentralRoleFunction.getCode());
			HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
			extPerms.setAction(actionValue);
			extPerms.setInstance(instanceValue);
			extPerms.setType(app.getNameSpace() + "." + checkType);
			extPerms.setDescription(domainCentralRoleFunction.getName());
			String deleteRoleFunction = mapper.writeValueAsString(extPerms);
			HttpEntity<String> entity = new HttpEntity<>(deleteRoleFunction, headers);
			logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleFunctionInExternalSystem: {} for DELETE: {} ",
					CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, deleteRoleFunction);
			ResponseEntity<String> delPermResponse = template
					.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
							+ "perm?force=true", HttpMethod.DELETE, entity, String.class);
			logger.debug(EELFLoggerDelegate.debugLogger,
					"deleteRoleFunctionInExternalSystem: Finished deleting permission in External Auth system {} and status code: {} ",
					deleteRoleFunction, delPermResponse.getStatusCode().value());
		} catch(HttpClientErrorException e){
			logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to delete functions in External System", e);
			EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
		} catch (Exception e) {
			if (e.getMessage().equalsIgnoreCase("404 Not Found")) {
				logger.debug(EELFLoggerDelegate.debugLogger,
						" deleteRoleFunctionInExternalSystem: It seems like function is already deleted in external central auth system  but exists in local DB",
						e.getMessage());
			} else {
				logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleFunctionInExternalSystem: Failed to delete functions in External System", e);
			}
		}
	}

	@Override
	public ExternalRequestFieldsValidator saveRoleForApplication(Role saveRole, String uebkey) throws Exception {
		boolean response = false;
		String message = "";
		try {
			EPApp app = getApp(uebkey).get(0);
			addRoleInEcompDB(saveRole, app);
			response = true;
		} catch (Exception e) {
			message = e.getMessage();
			logger.error(EELFLoggerDelegate.errorLogger, "saveRoleForApplication failed", e);
		}
		return new ExternalRequestFieldsValidator(response,message);
	}

	@SuppressWarnings("unchecked")
	@Override
	public boolean deleteRoleForApplication(String deleteRole, String uebkey) throws Exception {
		Session localSession = sessionFactory.openSession();
		Transaction transaction = null;
		boolean result = false;
		try {
			List<EPRole> epRoleList = null;
			EPApp app = getApp(uebkey).get(0);
			final Map<String, String> deleteRoleParams = new HashMap<>();
			deleteRoleParams.put(APP_ROLE_NAME_PARAM, deleteRole);
			if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
				epRoleList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, deleteRoleParams, null);
			} else {
				deleteRoleParams.put(APP_ID, String.valueOf(app.getId()));
				epRoleList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, deleteRoleParams, null);
			}
			if (!epRoleList.isEmpty()) {
				transaction = localSession.beginTransaction();
				// Delete app role functions before deleting role
				deleteRoleFunction(app, epRoleList);
				if (app.getId() == 1) {
					// Delete fn_user_ role
					dataAccessService.deleteDomainObjects(EPUserApp.class,
							APP_ID_EQUALS + app.getId() + " and role_id = " + epRoleList.get(0).getId(), null);
					boolean isPortalRequest = false;
					deleteRoleDependencyRecords(localSession, epRoleList.get(0).getId(), app.getId(), isPortalRequest);
				}
				deleteRoleInExternalAuthSystem(epRoleList, app);
				transaction.commit();
				logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleForApplication: committed the transaction");
				dataAccessService.deleteDomainObject(epRoleList.get(0), null);
			}
			result = true;
		} catch (Exception e) {
			logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleForApplication: failed", e);
			result = false;
		} finally {
			localSession.close();
		}
		return result;
	}
	
	/**
	 * 
	 * It deletes role for application in external auth system 
	 * 
	 * @param epRoleList contains role information
	 * @param app contains application information
	 * @throws Exception
	 */
	private void deleteRoleInExternalAuthSystem(List<EPRole> epRoleList, EPApp app) throws Exception {
		ResponseEntity<String> deleteResponse;
		ResponseEntity<String> res = getNameSpaceIfExists(app);
		if (res.getStatusCode() == HttpStatus.OK) {
		// Delete Role in External System
		String deleteRoleKey = "{\"name\":\"" + app.getNameSpace() + "." + epRoleList.get(0).getName()
				.replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_") + "\"}";
		deleteResponse = deleteRoleInExternalSystem(deleteRoleKey);
		if (deleteResponse.getStatusCode().value() != 200 && deleteResponse.getStatusCode().value() != 404) {
			EPLogUtil.logExternalAuthAccessAlarm(logger, deleteResponse.getStatusCode());
			logger.error(EELFLoggerDelegate.errorLogger,
					"deleteRoleForApplication: Failed to delete role in external auth system! due to {} ",
					deleteResponse.getBody());
		}
		logger.debug(EELFLoggerDelegate.debugLogger,
				"deleteRoleForApplication: about to commit the transaction");
		}
	}

	/**
	 * 
	 * It deletes application user role in external auth system
	 * 
	 * @param role
	 * @param app
	 * @param LoginId
	 * @throws Exception
	 */
	private void deleteUserRoleInExternalSystem(EPRole role, EPApp app, String LoginId) throws Exception {
		HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
		HttpEntity<String> entity = new HttpEntity<>(headers);
		getNameSpaceIfExists(app);
		logger.debug(EELFLoggerDelegate.debugLogger,"deleteUserRoleInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
		ResponseEntity<String> getResponse = template
				.exchange(
						SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole/"
								+ LoginId
								+ SystemProperties
										.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
								+ "/" + app.getNameSpace() + "." + role.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
						HttpMethod.GET, entity, String.class);
		logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: Finished GET user roles from External Auth system and response: {} ", getResponse.getBody());
		if (getResponse.getStatusCode().value() != 200) {
			throw new ExternalAuthSystemException(getResponse.getBody());
		}
		String res = getResponse.getBody();
		if (!res.equals(IS_EMPTY_JSON_STRING)) {
			HttpEntity<String> userRoleentity = new HttpEntity<>(headers);
			logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
			ResponseEntity<String> deleteResponse = template
					.exchange(
							SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
									+ "userRole/" + LoginId
									+ SystemProperties
											.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
									+ "/" + app.getNameSpace() + "." + role.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
							HttpMethod.DELETE, userRoleentity, String.class);
			if (deleteResponse.getStatusCode().value() != 200) {
				throw new ExternalAuthSystemException("Failed to delete user role");
			}
			logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: Finished deleting user role in External Auth system and status code: {} ", deleteResponse.getStatusCode().value());
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<CentralV2Role> getActiveRoles(String uebkey) throws Exception {
		List<CentralV2Role> roleList = new ArrayList<>();
		try {
			List<EPApp> app = getApp(uebkey);
			final Map<String, Long> params = new HashMap<>();
			// check if portal
			Long appId = null;
			if (!app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
				appId = app.get(0).getId();
			}
			List<Criterion> restrictionsList = new ArrayList<Criterion>();
			Criterion active_ynCrt = Restrictions.eq("active", Boolean.TRUE);
			Criterion appIdCrt;
			if (appId == null)
				appIdCrt = Restrictions.isNull("appId");
			else
				appIdCrt = Restrictions.eq("appId", appId);
			Criterion andCrit = Restrictions.and(active_ynCrt, appIdCrt);
			restrictionsList.add(andCrit);
			List<EPRole> epRole = (List<EPRole>) dataAccessService.getList(EPRole.class, null, restrictionsList, null);
			roleList = createCentralRoleObject(app, epRole, roleList, params);
			List<CentralV2Role> globalRoleList = getGlobalRolesOfApplication(app.get(0).getId());
			if (globalRoleList.size() > 0)
				roleList.addAll(globalRoleList);
		} catch (Exception e) {
			logger.error(EELFLoggerDelegate.errorLogger, "getActiveRoles: failed", e);
			throw e;
		}
		return roleList;

	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public ExternalRequestFieldsValidator deleteDependencyRoleRecord(Long roleId, String uebkey, String LoginId) throws Exception {
		Session localSession = sessionFactory.openSession();
		String message = "";
		Transaction transaction = null;
		boolean response = false;
		EPApp app = null;
		try {
			transaction = localSession.beginTransaction();
			List<EPRole> epRoleList = null;
			app = getApp(uebkey).get(0);
			if(app.getId().equals(PortalConstants.PORTAL_APP_ID)){
				epRoleList = getPortalAppRoleInfo(roleId);
			} else{
				epRoleList = getPartnerAppRoleInfo(roleId, app);
			}
			if(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
				// Delete User Role in External System before deleting role
				deleteUserRoleInExternalSystem(epRoleList.get(0), app, LoginId);	
			}
			// Delete user app roles
			dataAccessService.deleteDomainObjects(EPUserApp.class,
					APP_ID_EQUALS + app.getId() + " and role_id = " + epRoleList.get(0).getId(), null);
			boolean isPortalRequest = false;
			deleteRoleDependencyRecords(localSession, epRoleList.get(0).getId(), app.getId(), isPortalRequest);
			transaction.commit();
			if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
				// Final call to delete role once all dependencies has been deleted
				deleteRoleInExternalAuthSystem(epRoleList, app);
			}
			dataAccessService.deleteDomainObjects(EPRole.class, " role_id = "+ epRoleList.get(0).getId(), null);		
			logger.debug(EELFLoggerDelegate.debugLogger, "deleteDependencyRoleRecord: committed the transaction");
			response = true;
		} catch(HttpClientErrorException e){
			logger.error(EELFLoggerDelegate.errorLogger, "deleteDependencyRoleRecord: HttpClientErrorException", e);
			EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
			message = e.getMessage();
		} catch (Exception e) {
			logger.error(EELFLoggerDelegate.errorLogger, "deleteDependencyRoleRecord failed", e);
			EcompPortalUtils.rollbackTransaction(transaction,
					"deleteDependencyRoleRecord rollback, exception = " + e.toString());
			message = e.getMessage();
		} finally {
			localSession.close();
		}
		return new ExternalRequestFieldsValidator(response,message);
	}
	
	@Override
	@SuppressWarnings("unchecked")
	@Transactional
	public void syncRoleFunctionFromExternalAccessSystem(EPApp app) {
		try {

			// get Permissions from External Auth System
			JSONArray extPerms = getExtAuthPermissions(app);
			List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPerms);

			// get functions in DB
			final Map<String, Long> params = new HashMap<>();
			final Map<String, CentralV2RoleFunction> roleFuncMap = new HashMap<>();
			params.put(APP_ID, app.getId());
			List<CentralV2RoleFunction> appFunctions = dataAccessService.executeNamedQuery("getAllRoleFunctions", params,
					null);
			if (!appFunctions.isEmpty()) {
				for (CentralV2RoleFunction roleFunc : appFunctions) {
					roleFuncMap.put(roleFunc.getCode(), roleFunc);
				}
			}
			
			// get Roles for portal in DB
			List<EPRole> portalRoleList = getGlobalRolesOfPortal();
			final Map<String, EPRole> existingPortalRolesMap = new HashMap<>();
			for(EPRole epRole : portalRoleList){
				existingPortalRolesMap.put(epRole.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), epRole);
			}
			
			// get Roles in DB
			final Map<String, EPRole> currentRolesInDB = getCurrentRolesInDB(app);
			
			// store External Permissions with Pipe and without Pipe (just instance)
			final Map<String, ExternalAccessPermsDetail> extAccessPermsContainsPipeMap = new HashMap<>();
			final Map<String, ExternalAccessPermsDetail> extAccessPermsMap = new HashMap<>();
			for (ExternalAccessPermsDetail permsDetailInfoWithPipe : permsDetailList) {
				extAccessPermsContainsPipeMap.put(permsDetailInfoWithPipe.getInstance(), permsDetailInfoWithPipe);
				String finalFunctionCodeVal = EcompPortalUtils.getFunctionCode(permsDetailInfoWithPipe.getInstance());
				extAccessPermsMap.put(finalFunctionCodeVal, permsDetailInfoWithPipe);
			}

			// Add if new functions and app role functions were added in
			// external auth system
			for (ExternalAccessPermsDetail permsDetail : permsDetailList) {
				String code = permsDetail.getInstance();
				CentralV2RoleFunction getFunctionCodeKey = roleFuncMap.get(permsDetail.getInstance());
				List<CentralV2RoleFunction> roleFunctionList = addGetLocalFunction(app, roleFuncMap, permsDetail, code,
						getFunctionCodeKey);
				List<String> roles = permsDetail.getRoles();
				if (roles != null) {
					// Check if function has any roles and which does not exist
					// in External Auth System. If exists delete in local
					addRemoveIfFunctionsRolesIsSyncWithExternalAuth(app, currentRolesInDB, roleFunctionList, roles, existingPortalRolesMap);
				}
			}

			// Check if function does exits in External Auth System but exits in
			// local then delete function and its dependencies
			for (CentralV2RoleFunction roleFunc : appFunctions) {
				try {
					ExternalAccessPermsDetail getFunctionCodeContainsPipeKey = extAccessPermsContainsPipeMap
							.get(roleFunc.getCode());
					if (null == getFunctionCodeContainsPipeKey) {
						ExternalAccessPermsDetail getFunctionCodeKey = extAccessPermsMap.get(roleFunc.getCode());
						if (null == getFunctionCodeKey) {
							deleteAppRoleFuncDoesNotExitsInExtSystem(app, roleFunc);
						}
					}
				} catch (Exception e) {
					logger.error(EELFLoggerDelegate.errorLogger,
							"syncRoleFunctionFromExternalAccessSystem: Failed to delete function", e);

				}
			}

			logger.debug(EELFLoggerDelegate.debugLogger,
					"syncRoleFunctionFromExternalAccessSystem: Finished syncRoleFunctionFromExternalAccessSystem");
		} catch (Exception e) {
			logger.error(EELFLoggerDelegate.errorLogger,
					"syncRoleFunctionFromExternalAccessSystem: Failed syncRoleFunctionFromExternalAccessSystem", e);

		}
	}

	@SuppressWarnings("unchecked")
	private void addRemoveIfFunctionsRolesIsSyncWithExternalAuth(EPApp app, final Map<String, EPRole> currentRolesInDB,
			List<CentralV2RoleFunction> roleFunctionList, List<String> roles, Map<String, EPRole> existingPortalRolesMap)
			throws Exception {
		if (!roleFunctionList.isEmpty()) {
			final Map<String, String> appRoleFuncParams = new HashMap<>();
			final Map<String, LocalRole> currentAppRoleFunctionsMap = new HashMap<>();
			final Map<String, String> currentRolesInExtSystem = new HashMap<>();
			appRoleFuncParams.put("functionCd", roleFunctionList.get(0).getCode());
			appRoleFuncParams.put("appId", String.valueOf(app.getId()));
			List<LocalRole> localRoleList = dataAccessService.executeNamedQuery("getCurrentAppRoleFunctions",
					appRoleFuncParams, null);
			for (LocalRole localRole : localRoleList) {
				currentAppRoleFunctionsMap.put(localRole.getRolename().replaceAll(
						EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), localRole);
			}
			for (String addRole : roles) {
				currentRolesInExtSystem.put(addRole.substring(addRole.indexOf(FUNCTION_PIPE)+1), addRole);
			}
			for (String extAuthrole : roles) {
				String roleNameSpace = extAuthrole.substring(0, extAuthrole.indexOf(FUNCTION_PIPE));
				boolean isNameSpaceMatching = EcompPortalUtils.checkNameSpaceMatching(roleNameSpace, app.getNameSpace());
				if (isNameSpaceMatching) {
					if (!currentAppRoleFunctionsMap
							.containsKey(extAuthrole.substring(app.getNameSpace().length() + 1))) {
						EPRole localAddFuntionRole = currentRolesInDB
								.get(extAuthrole.substring(app.getNameSpace().length() + 1));
						if (localAddFuntionRole == null) {
							checkAndAddRoleInDB(app, currentRolesInDB, roleFunctionList, extAuthrole);
						} else {
							EPAppRoleFunction addAppRoleFunc = new EPAppRoleFunction();
							addAppRoleFunc.setAppId(app.getId());
							addAppRoleFunc.setCode(roleFunctionList.get(0).getCode());
							addAppRoleFunc.setRoleId(localAddFuntionRole.getId());
							dataAccessService.saveDomainObject(addAppRoleFunc, null);
						}
					}
					// This block is to save global role function if exists
				} else {
					String extAuthAppRoleName = extAuthrole.substring(extAuthrole.indexOf(FUNCTION_PIPE) + 1);
					boolean checkIfGlobalRoleExists = existingPortalRolesMap.containsKey(extAuthAppRoleName);
					if (checkIfGlobalRoleExists) {
						final Map<String, Long> params = new HashMap<>();
						EPRole role = existingPortalRolesMap.get(extAuthAppRoleName);
						EPAppRoleFunction addGlobalRoleFunctions = new EPAppRoleFunction();
						params.put("appId", app.getId());
						params.put("roleId", role.getId());
						List<EPAppRoleFunction> currentGlobalRoleFunctionsList = dataAccessService.executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", params, null);				
						boolean checkIfRoleFunctionExists = currentGlobalRoleFunctionsList.stream().anyMatch(currentGlobalRoleFunction -> currentGlobalRoleFunction.getCode().equals(roleFunctionList.get(0).getCode()));
						if (role != null && !checkIfRoleFunctionExists) {
							addGlobalRoleFunctions.setAppId(app.getId());
							addGlobalRoleFunctions.setRoleId(role.getId());
							if (!app.getId().equals(role.getAppRoleId())) {
								addGlobalRoleFunctions.setRoleAppId((PortalConstants.PORTAL_APP_ID).toString());
							} else {
								addGlobalRoleFunctions.setRoleAppId(null);
							}
							addGlobalRoleFunctions.setCode(roleFunctionList.get(0).getCode());
							dataAccessService.saveDomainObject(addGlobalRoleFunctions, null);
						}
					}
				}
			}
			for (LocalRole localRoleDelete : localRoleList) {
				if (!currentRolesInExtSystem.containsKey(localRoleDelete.getRolename()
						.replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"))) {
					dataAccessService.deleteDomainObjects(EPAppRoleFunction.class,
							APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + roleFunctionList.get(0).getCode()
									+ "'" + " and role_id = " + localRoleDelete.getRoleId().longValue(),
							null);
				}
			}
		}
	}

	private void deleteAppRoleFuncDoesNotExitsInExtSystem(EPApp app, CentralV2RoleFunction roleFunc) {
		logger.debug(EELFLoggerDelegate.debugLogger,
				"syncRoleFunctionFromExternalAccessSystem: Deleting app role function {}",
				roleFunc.getCode());
		dataAccessService.deleteDomainObjects(EPAppRoleFunction.class,
				APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + roleFunc.getCode() +"'", null);
		logger.debug(EELFLoggerDelegate.debugLogger,
				"syncRoleFunctionFromExternalAccessSystem: Deleted app role function {}",
				roleFunc.getCode());

		logger.debug(EELFLoggerDelegate.debugLogger,
				"syncRoleFunctionFromExternalAccessSystem: Deleting app function {}",
				roleFunc.getCode());
		dataAccessService.deleteDomainObjects(CentralV2RoleFunction.class,
				APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + roleFunc.getCode() +"'", null);
		logger.debug(EELFLoggerDelegate.debugLogger,
				"syncRoleFunctionFromExternalAccessSystem: Deleted app function {}",
				roleFunc.getCode());
	}

	private void checkAndAddRoleInDB(EPApp app, final Map<String, EPRole> currentRolesInDB,
			List<CentralV2RoleFunction> roleFunctionList, String roleList) throws Exception {
		if (!currentRolesInDB.containsKey(
				roleList.substring(app.getNameSpace().length() + 1))) {
			Role role = addRoleInDBIfDoesNotExists(app,
					roleList.substring(app.getNameSpace().length() + 1));
			addIfRoleDescriptionNotExitsInExtSystem(role, app);
			if (!roleFunctionList.isEmpty()) {
				try {
					if (!roleFunctionList.isEmpty()) {
						EPAppRoleFunction addAppRoleFunc = new EPAppRoleFunction();
						addAppRoleFunc.setAppId(app.getId());
						addAppRoleFunc.setCode(roleFunctionList.get(0).getCode());
						addAppRoleFunc.setRoleId(role.getId());
						dataAccessService.saveDomainObject(addAppRoleFunc, null);
					}
				} catch (Exception e) {
					logger.error(EELFLoggerDelegate.errorLogger,
							"syncRoleFunctionFromExternalAccessSystem: Failed to save app role function ",
							e);
				}
			}
		}
	}

	@SuppressWarnings("unchecked")
	private List<CentralV2RoleFunction> addGetLocalFunction(EPApp app, final Map<String, CentralV2RoleFunction> roleFuncMap,
			ExternalAccessPermsDetail permsDetail, String code, CentralV2RoleFunction getFunctionCodeKey) {
		String finalFunctionCodeVal = addToLocalIfFunctionNotExists(app, roleFuncMap, permsDetail, code,
				getFunctionCodeKey);
		final Map<String, String> appSyncFuncsParams = new HashMap<>();
		appSyncFuncsParams.put("appId", String.valueOf(app.getId()));
		appSyncFuncsParams.put("functionCd", finalFunctionCodeVal);
		List<CentralV2RoleFunction> roleFunctionList = null;
		roleFunctionList = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appSyncFuncsParams,
				null);
		if (roleFunctionList.isEmpty()) {
			appSyncFuncsParams.put("functionCd", code);
			roleFunctionList = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appSyncFuncsParams,
					null);
		}
		return roleFunctionList;
	}

	private String addToLocalIfFunctionNotExists(EPApp app, final Map<String, CentralV2RoleFunction> roleFuncMap,
			ExternalAccessPermsDetail permsDetail, String code, CentralV2RoleFunction getFunctionCodeKey
			) {
		String finalFunctionCodeVal = "";	
		if (null == getFunctionCodeKey) {
			finalFunctionCodeVal = EcompPortalUtils.getFunctionCode(permsDetail.getInstance());
			CentralV2RoleFunction checkIfCodeStillExits = roleFuncMap.get(finalFunctionCodeVal);
			// If function does not exist in local then add!
			if (null == checkIfCodeStillExits) {
				logger.debug(EELFLoggerDelegate.debugLogger,
						"syncRoleFunctionFromExternalAccessSystem: Adding function: {} ", code);
				addFunctionInEcompDB(app, permsDetail, code);
				logger.debug(EELFLoggerDelegate.debugLogger,
						"syncRoleFunctionFromExternalAccessSystem: Finished adding function: {} ", code);
			}
		}
		return finalFunctionCodeVal;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Map<String, EPRole> getCurrentRolesInDB(EPApp app) {
		final Map<String, EPRole> currentRolesInDB = new HashMap<>();
		List<EPRole> getCurrentRoleList = null;
		final Map<String, Long> appParams = new HashMap<>();
		if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
			getCurrentRoleList = dataAccessService.executeNamedQuery("getPortalAppRolesList", null, null);
		} else {
			appParams.put("appId", app.getId());
			getCurrentRoleList = dataAccessService.executeNamedQuery("getPartnerAppRolesList", appParams, null);
		}
		for (EPRole role : getCurrentRoleList) {
			currentRolesInDB.put(role.getName()
					.replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), role);
		}
		return currentRolesInDB;
	}

	private List<ExternalAccessPermsDetail> getExtAuthPerrmissonList(EPApp app, JSONArray extPerms)
			throws IOException{
		ExternalAccessPermsDetail permDetails = null;
		List<ExternalAccessPermsDetail> permsDetailList = new ArrayList<>();
		for (int i = 0; i < extPerms.length(); i++) {
			String description = null;
			if (extPerms.getJSONObject(i).has("description")) {
				description = extPerms.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
			} else {
				description = extPerms.getJSONObject(i).getString("type")+"|"+extPerms.getJSONObject(i).getString("instance")
						+"|"+extPerms.getJSONObject(i).getString("action");
			}
			if (extPerms.getJSONObject(i).has("roles")) {
				ObjectMapper rolesListMapper = new ObjectMapper();
				JSONArray resRoles = extPerms.getJSONObject(i).getJSONArray("roles");
				List<String> list = rolesListMapper.readValue(resRoles.toString(),
						TypeFactory.defaultInstance().constructCollectionType(List.class, String.class));
				permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"),
						extPerms.getJSONObject(i).getString("type").substring(app.getNameSpace().length() + 1)
								+ FUNCTION_PIPE + extPerms.getJSONObject(i).getString("instance") + FUNCTION_PIPE
								+ extPerms.getJSONObject(i).getString("action"),
						extPerms.getJSONObject(i).getString("action"), list, description);
				permsDetailList.add(permDetails);
			} else {
				permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"),
						extPerms.getJSONObject(i).getString("type").substring(app.getNameSpace().length() + 1)
								+ FUNCTION_PIPE + extPerms.getJSONObject(i).getString("instance") + FUNCTION_PIPE
								+ extPerms.getJSONObject(i).getString("action"),
						extPerms.getJSONObject(i).getString("action"), description);
				permsDetailList.add(permDetails);
			}
		}
		return permsDetailList;
	}

	private JSONArray getExtAuthPermissions(EPApp app) throws Exception {
		ResponseEntity<String> response = null;
		HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
		HttpEntity<String> entity = new HttpEntity<>(headers);
		logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: {} ",
				CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
		response = template
				.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
						+ "perms/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);

		String res = response.getBody();
		logger.debug(EELFLoggerDelegate.debugLogger,
				"syncRoleFunctionFromExternalAccessSystem: Finished GET permissions from External Auth system and response: {} ",
				response.getBody());
		JSONObject jsonObj = new JSONObject(res);
		JSONArray extPerms = jsonObj.getJSONArray("perm");
		for (int i = 0; i < extPerms.length(); i++) {
			if (extPerms.getJSONObject(i).getString("type").equals(app.getNameSpace() + ".access")) {
				extPerms.remove(i);
				i--;
			}
		}
		return extPerms;
	}
	
	/**
	 * 
	 * Add function into local DB
	 * 
	 * @param app
	 * @param permsDetail
	 * @param code
	 */
	private void addFunctionInEcompDB(EPApp app, ExternalAccessPermsDetail permsDetail, String code) {
		try{
		CentralV2RoleFunction addFunction = new CentralV2RoleFunction();
		addFunction.setAppId(app.getId());
		addFunction.setCode(code);
		addFunction.setName(permsDetail.getDescription());
		dataAccessService.saveDomainObject(addFunction, null);
		} catch(Exception e){
			logger.error(EELFLoggerDelegate.errorLogger, "addFunctionInEcompDB: Failed to add function", e);
		}
	}

	/**
	 * 
	 * It updates description of a role in external auth system
	 * 
	 * @param role
	 * @param app
	 * @throws Exception
	 */
	private void addIfRoleDescriptionNotExitsInExtSystem(Role role, EPApp app) throws Exception {
		String addRoleNew = updateExistingRoleInExternalSystem(role, app);
		HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
		try {
			HttpEntity<String> entity = new HttpEntity<>(addRoleNew, headers);
			template.exchange(
					SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
					HttpMethod.PUT, entity, String.class);
		} catch (HttpClientErrorException e) {
			logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addIfRoleDescriptionNotExitsInExtSystem",
					e);
			EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
		} catch (Exception e) {
			logger.error(EELFLoggerDelegate.errorLogger, "addIfRoleDescriptionNotExitsInExtSystem: Failed",
					e);
		}
	}

	/**
	 * 
	 * While sync functions form external auth system if new role found we should add in local and return Role.class object
	 * 
	 * @param app
	 * @param role
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private Role addRoleInDBIfDoesNotExists(EPApp app, String role) {
		Role setNewRole = new Role();
		try {
			// functions can have new role created in External Auth System prevent
			// duplication here
			boolean isCreated = checkIfRoleExitsElseCreateInSyncFunctions(role, app);
			final Map<String, String> getRoleByNameParams = new HashMap<>();
			List<EPRole> getRoleCreated = null;
			getRoleByNameParams.put(APP_ROLE_NAME_PARAM, role);
			if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
				getRoleByNameParams.put("appId", String.valueOf(app.getId()));
				List<EPRole> roleCreated = dataAccessService
						.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, getRoleByNameParams, null);
				if (!isCreated) {
					EPRole epUpdateRole = roleCreated.get(0);
					epUpdateRole.setAppRoleId(epUpdateRole.getId());
					dataAccessService.saveDomainObject(epUpdateRole, null);
					getRoleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM,
							getRoleByNameParams, null);
				} else {
					getRoleCreated = roleCreated;
				}
			} else {
				getRoleCreated = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, getRoleByNameParams,
						null);
			}
			if (getRoleCreated != null && !getRoleCreated.isEmpty()) {
				EPRole roleObject = getRoleCreated.get(0);
				setNewRole.setId(roleObject.getId());
				setNewRole.setName(roleObject.getName());
				setNewRole.setActive(roleObject.getActive());
				setNewRole.setPriority(roleObject.getPriority());
			}
		} catch (Exception e) {
			logger.error(EELFLoggerDelegate.errorLogger, "addRoleInDBIfDoesNotExists: Failed", e);
		}
		return setNewRole;
	}

	@SuppressWarnings("unchecked")
	private boolean checkIfRoleExitsElseCreateInSyncFunctions(String role, EPApp app) {
		boolean isCreated = false;
		final Map<String, String> roleParams = new HashMap<>();
		roleParams.put(APP_ROLE_NAME_PARAM, role);
		List<EPRole> roleCreated = null;
		if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
			roleCreated = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, roleParams,
					null);
		} else {
			roleParams.put("appId", String.valueOf(app.getId()));
			roleCreated = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, roleParams,
					null);
		}
		if (roleCreated == null || roleCreated.isEmpty()) {
			roleParams.put("appId", String.valueOf(app.getId()));
			EPRole epRoleNew = new EPRole();
			epRoleNew.setActive(true);
			epRoleNew.setName(role);
			if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
				epRoleNew.setAppId(null);
			} else {
				epRoleNew.setAppId(app.getId());
			}
			dataAccessService.saveDomainObject(epRoleNew, null);
			isCreated = false;
		} else {
			isCreated = true;
		}
		return isCreated;
	}

	@Override
	@SuppressWarnings("unchecked")
	public Integer bulkUploadFunctions(String uebkey) throws Exception {
		EPApp app = getApp(uebkey).get(0);
		List<RoleFunction> roleFuncList = dataAccessService.executeNamedQuery("getAllFunctions", null, null);
		CentralV2RoleFunction cenRoleFunc = null;
		Integer functionsAdded = 0;
		try {
			for (RoleFunction roleFunc : roleFuncList) {
				cenRoleFunc = new CentralV2RoleFunction(roleFunc.getCode(), roleFunc.getName());
				addRoleFunctionInExternalSystem(cenRoleFunc, app);
				functionsAdded++;
			}
		} catch(HttpClientErrorException e){
			logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - bulkUploadFunctions failed", e);
			EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
		} catch (Exception e) {
			logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadFunctions: failed", e.getMessage(), e);
		}
		return functionsAdded;
	}

	@Override
	public Integer bulkUploadRoles(String uebkey) throws Exception {
		List<EPApp> app = getApp(uebkey);
		List<EPRole> roles = getAppRoles(app.get(0).getId());
		List<CentralV2Role> cenRoleList = new ArrayList<>();
		final Map<String, Long> params = new HashMap<>();
		Integer rolesListAdded = 0;
		try {
			cenRoleList = createCentralRoleObject(app, roles, cenRoleList, params);
			ObjectMapper mapper = new ObjectMapper();
			mapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
			String roleList = mapper.writeValueAsString(cenRoleList);
			List<Role> roleObjectList = mapper.readValue(roleList,
					TypeFactory.defaultInstance().constructCollectionType(List.class, Role.class));
			for (Role role : roleObjectList) {
				addRoleInExternalSystem(role, app.get(0));
				rolesListAdded++;
			}
			if (!app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
				// Add Account Admin role in External AUTH System
				try {
					String addAccountAdminRole = "";
					ExternalAccessRole extRole = new ExternalAccessRole();
					extRole.setName(app.get(0).getNameSpace() + "." + PortalConstants.ADMIN_ROLE
							.replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
					addAccountAdminRole = mapper.writeValueAsString(extRole);
					HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
					HttpEntity<String> entity = new HttpEntity<>(addAccountAdminRole, headers);
					template.exchange(
							SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
							HttpMethod.POST, entity, String.class);
					rolesListAdded++;
				} catch (HttpClientErrorException e) {
					logger.error(EELFLoggerDelegate.errorLogger,
							"HttpClientErrorException - Failed to create Account Admin role", e);
					EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
				} catch (Exception e) {
					if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
						logger.error(EELFLoggerDelegate.errorLogger,
								"bulkUploadRoles: Account Admin Role already exits but does not break functionality",
								e);
					} else {
						logger.error(EELFLoggerDelegate.errorLogger,
								"bulkUploadRoles: Failed to create Account Admin role", e.getMessage());
					}
				}
			}
		} catch (Exception e) {
			logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRoles: failed", e);
			throw e;
		}
		return rolesListAdded;
	}

	/**
	 * It creating new role in external auth system while doing bulk upload
	 * 
	 * @param role
	 * @param app
	 * @throws Exception
	 */
	private void addRoleInExternalSystem(Role role, EPApp app) throws Exception {
		String addRoleNew = updateExistingRoleInExternalSystem(role, app);
		HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
		try {
			HttpEntity<String> entity = new HttpEntity<>(addRoleNew, headers);
			template.exchange(
					SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
					HttpMethod.POST, entity, String.class);
		} catch(HttpClientErrorException e){
			logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addRoleInExternalSystem", e);
			EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
		} catch (Exception e) {
			if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
				logger.error(EELFLoggerDelegate.errorLogger, "addRoleInExternalSystem: Role already exits but does not break functionality", e);
			} else {
				logger.error(EELFLoggerDelegate.errorLogger, "addRoleInExternalSystem: Failed to addRoleInExternalSystem", e.getMessage());
			}
		}
	}

	@Override
	@SuppressWarnings("unchecked")
	public Integer bulkUploadRolesFunctions(String uebkey) throws Exception {
		EPApp app = getApp(uebkey).get(0);
		List<EPRole> roles = getAppRoles(app.getId());
		final Map<String, Long> params = new HashMap<>();
		Integer roleFunctions = 0;
		try {
			for (EPRole role : roles) {
				params.put("roleId", role.getId());
				List<BulkUploadRoleFunction> appRoleFunc = dataAccessService.executeNamedQuery("uploadAllRoleFunctions",
						params, null);
				if (!appRoleFunc.isEmpty()) {
					for (BulkUploadRoleFunction addRoleFunc : appRoleFunc) {
						addRoleFunctionsInExternalSystem(addRoleFunc, role, app);
						roleFunctions++;
					}
				}
			}
		} catch(HttpClientErrorException e){
			logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to bulkUploadRolesFunctions", e);
			EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
		} catch (Exception e) {
			logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRolesFunctions: failed", e);
		}
		return roleFunctions;
	}
	
	/**
	 * Its adding a role function while doing bulk upload
	 * 
	 * @param addRoleFunc
	 * @param role
	 * @param app
	 */
	private void addRoleFunctionsInExternalSystem(BulkUploadRoleFunction addRoleFunc, EPRole role, EPApp app) {
		String type = "";
		String instance = "";
		String action = "";
		if(addRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)){
			type = EcompPortalUtils.getFunctionType(addRoleFunc.getFunctionCd()); 
			instance = EcompPortalUtils.getFunctionCode(addRoleFunc.getFunctionCd());
			action = EcompPortalUtils.getFunctionAction(addRoleFunc.getFunctionCd());
		} else{
			type = addRoleFunc.getFunctionCd().contains("menu") ? "menu" : "url";
			instance = addRoleFunc.getFunctionCd();
			action = "*"; 
		}
		ExternalAccessRolePerms extRolePerms = null;
		ExternalAccessPerms extPerms = null;
		ObjectMapper mapper = new ObjectMapper();
		try {
			HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
			extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, instance, action,
					addRoleFunc.getFunctionName());
			extRolePerms = new ExternalAccessRolePerms(extPerms,
					app.getNameSpace() + "." + role.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
			String updateRolePerms = mapper.writeValueAsString(extRolePerms);
			HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
			template.exchange(
					SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
					HttpMethod.POST, entity, String.class);
		} catch (Exception e) {
			if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
				logger.error(EELFLoggerDelegate.errorLogger,
						"addRoleFunctionsInExternalSystem: RoleFunction already exits but does not break functionality", e);
			} else {
				logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionsInExternalSystem: Failed to addRoleFunctionsInExternalSystem",
						e.getMessage());
			}
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public Integer bulkUploadPartnerFunctions(String uebkey) throws Exception {
		EPApp app = getApp(uebkey).get(0);
		final Map<String, Long> params = new HashMap<>();
		params.put("appId", app.getId());
		List<CentralV2RoleFunction> roleFuncList = dataAccessService.executeNamedQuery("getPartnerAppFunctions", params,
				null);
		Integer functionsAdded = 0;
		try {
			for (CentralV2RoleFunction roleFunc : roleFuncList) {
				addFunctionInExternalSystem(roleFunc, app);
				functionsAdded++;
			}
		} catch (HttpClientErrorException e) {
			logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - bulkUploadPartnerFunctions failed", e);
			EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
		} catch (Exception e) {
			logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadPartnerFunctions: failed", e.getMessage(), e);
		}
		return functionsAdded;
	}

	private void addFunctionInExternalSystem(CentralV2RoleFunction roleFunc, EPApp app) throws Exception {
		ObjectMapper mapper = new ObjectMapper();
		ExternalAccessPerms extPerms = new ExternalAccessPerms();
		HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
		String type = "";
		String instance = "";
		String action = "";
		if ((roleFunc.getCode().contains(FUNCTION_PIPE))
				|| (roleFunc.getType() != null && roleFunc.getAction() != null)) {
			type = EcompPortalUtils.getFunctionType(roleFunc.getCode());
			instance = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
			action = EcompPortalUtils.getFunctionAction(roleFunc.getCode());
		} else {
			type = roleFunc.getCode().contains("menu") ? "menu" : "url";
			instance = roleFunc.getCode();
			action = "*";
		}
		try {
			extPerms.setAction(action);
			extPerms.setInstance(instance);
			extPerms.setType(app.getNameSpace() + "." + type);
			extPerms.setDescription(roleFunc.getName());
			String addFunction = mapper.writeValueAsString(extPerms);
			HttpEntity<String> entity = new HttpEntity<>(addFunction, headers);
			logger.debug(EELFLoggerDelegate.debugLogger, "addFunctionInExternalSystem: {} for POST: {}",
					CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addFunction);
			ResponseEntity<String> addPermResponse = template.exchange(
					SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
					HttpMethod.POST, entity, String.class);
			logger.debug(EELFLoggerDelegate.debugLogger,
					"addFunctionInExternalSystem: Finished adding permission for POST: {} and status code: {} ",
					addPermResponse.getStatusCode().value(), addFunction);
		} catch (HttpClientErrorException e) {
			logger.error(EELFLoggerDelegate.errorLogger,
					"HttpClientErrorException - Failed to add function in external central auth system", e);
			EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
			throw e;
		} catch (Exception e) {
			logger.error(EELFLoggerDelegate.errorLogger,
					"addFunctionInExternalSystem: Failed to add fucntion in external central auth system", e);
			throw e;
		}
	} 

	@Override
	public void bulkUploadPartnerRoles(String uebkey, List<Role> roleList) throws Exception {
		EPApp app = getApp(uebkey).get(0);
		for (Role role : roleList) {
			addRoleInExternalSystem(role, app);
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public Integer bulkUploadPartnerRoleFunctions(String uebkey) throws Exception {
		EPApp app = getApp(uebkey).get(0);
		List<EPRole> roles = getAppRoles(app.getId());
		final Map<String, Long> params = new HashMap<>();
		Integer roleFunctions = 0;
		try {
			for (EPRole role : roles) {
				params.put("roleId", role.getId());
				List<BulkUploadRoleFunction> appRoleFunc = dataAccessService.executeNamedQuery("uploadPartnerRoleFunctions",
						params, null);
				if (!appRoleFunc.isEmpty()) {
					for (BulkUploadRoleFunction addRoleFunc : appRoleFunc) {
						addRoleFunctionsInExternalSystem(addRoleFunc, role, app);
						roleFunctions++;
					}
				}
			}
			// upload global role functions to ext auth system
			if(!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
				roleFunctions = bulkUploadGlobalRoleFunctions(app, roleFunctions);
			}
		} catch(HttpClientErrorException e){
			logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to bulkUploadRolesFunctions", e);
			EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
		} catch (Exception e) {
			logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRolesFunctions: failed", e);
		}
		return roleFunctions;
	}

	@SuppressWarnings("unchecked")
	private Integer bulkUploadGlobalRoleFunctions(EPApp app, Integer roleFunctions) throws Exception {
		try {
			EPApp portalApp = epAppService.getApp(1l);
			final Map<String, Long> params = new HashMap<>();
			params.put("appId", app.getId());
			List<GlobalRoleWithApplicationRoleFunction> globalRoleFuncs = dataAccessService
					.executeNamedQuery("getBulkUploadPartnerGlobalRoleFunctions", params, null);
			ObjectMapper mapper = new ObjectMapper();
			HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
			for (GlobalRoleWithApplicationRoleFunction globalRoleFunc : globalRoleFuncs) {
				ExternalAccessRolePerms extRolePerms;
				ExternalAccessPerms extPerms;
				String type = "";
				String instance = "";
				String action = "";
				if (globalRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)) {
					type = EcompPortalUtils.getFunctionType(globalRoleFunc.getFunctionCd());
					instance = EcompPortalUtils.getFunctionCode(globalRoleFunc.getFunctionCd());
					action = EcompPortalUtils.getFunctionAction(globalRoleFunc.getFunctionCd());
				} else {
					type = globalRoleFunc.getFunctionCd().contains("menu") ? "menu" : "url";
					instance = globalRoleFunc.getFunctionCd();
					action = "*";
				}
				extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, instance, action);
				extRolePerms = new ExternalAccessRolePerms(extPerms, portalApp.getNameSpace() + "." + globalRoleFunc.getRoleName()
						.replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
				String updateRolePerms = mapper.writeValueAsString(extRolePerms);
				HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
				updateRoleFunctionInExternalSystem(updateRolePerms, entity);
				roleFunctions++;
			}
		} catch (HttpClientErrorException e) {
			logger.error(EELFLoggerDelegate.errorLogger,
					"HttpClientErrorException - Failed to add role function in external central auth system", e);
			EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
			throw e;
		} catch (Exception e) {
			logger.error(EELFLoggerDelegate.errorLogger,
					"bulkUploadGlobalRoleFunctions: Failed to add role fucntion in external central auth system", e);
			throw e;
		}
		return roleFunctions;
	}

	@Override
	@Transactional
	public void syncApplicationRolesWithEcompDB(EPApp app) {
		try {
			logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: Started");
			//Sync functions and roles assigned to it which also creates new roles if does not exits in portal
			syncRoleFunctionFromExternalAccessSystem(app);
			logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: Finished");	
			
			ObjectMapper mapper = new ObjectMapper();
			logger.debug(EELFLoggerDelegate.debugLogger, "Entering to getAppRolesJSONFromExtAuthSystem");
			// Get Permissions from External Auth System
			JSONArray extRole = getAppRolesJSONFromExtAuthSystem(app);
			
			logger.debug(EELFLoggerDelegate.debugLogger, "Entering into getExternalRoleDetailsList");
			//refactoring done
			List<ExternalRoleDetails> externalRoleDetailsList = getExternalRoleDetailsList(app,
					mapper, extRole);
			
			List<EPRole> finalRoleList = new ArrayList<>();
			for (ExternalRoleDetails externalRole : externalRoleDetailsList) {
				EPRole ecompRole = convertExternalRoleDetailstoEpRole(externalRole);
				finalRoleList.add(ecompRole);
			}

			List<EPRole> applicationRolesList;
			applicationRolesList = getAppRoles(app.getId());
			List<String> applicationRoleIdList = new ArrayList<>();
			for (EPRole applicationRole : applicationRolesList) {
				applicationRoleIdList.add(applicationRole.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
			}

			List<EPRole> roleListToBeAddInEcompDB = new ArrayList<>();
			for (EPRole aafRole : finalRoleList) {
				if (!applicationRoleIdList.contains(aafRole.getName())) {
					roleListToBeAddInEcompDB.add(aafRole);
				}
			}

			logger.debug(EELFLoggerDelegate.debugLogger, "Entering into inactiveRolesNotInExternalAuthSystem");
			// Check if roles exits in external Access system and if not make inactive in DB
			inactiveRolesNotInExternalAuthSystem(app, finalRoleList, applicationRolesList);

			logger.debug(EELFLoggerDelegate.debugLogger, "Entering into checkAndUpdateRoleInDB");
			// It checks properties in the external auth system app role description and updates role in local
			checkAndUpdateRoleInDB(app, finalRoleList);

			logger.debug(EELFLoggerDelegate.debugLogger, "Entering into addNewRoleInEcompDBUpdateDescInExtAuthSystem");
			// Add new roles in DB and updates role description in External Auth System 
			addNewRoleInEcompDBUpdateDescInExtAuthSystem(app, roleListToBeAddInEcompDB);
			logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: Finished");
		} catch (HttpClientErrorException e) {
			logger.error(EELFLoggerDelegate.errorLogger, "syncApplicationRolesWithEcompDB: Failed due to the External Auth System", e);
			EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
		} catch (Exception e) {
			logger.error(EELFLoggerDelegate.errorLogger, "syncApplicationRolesWithEcompDB: Failed ", e);
		}
	}

	/**
	 * 
	 * It adds new roles in DB and updates description in External Auth System
	 * 
	 * @param app
	 * @param roleListToBeAddInEcompDB
	 */
	@SuppressWarnings("unchecked")
	private void addNewRoleInEcompDBUpdateDescInExtAuthSystem(EPApp app, List<EPRole> roleListToBeAddInEcompDB) {
		EPRole roleToBeAddedInEcompDB;
		for (int i = 0; i < roleListToBeAddInEcompDB.size(); i++) {
			try {
				roleToBeAddedInEcompDB = roleListToBeAddInEcompDB.get(i);
				if (app.getId() == 1) {
					roleToBeAddedInEcompDB.setAppRoleId(null);
				}
				dataAccessService.saveDomainObject(roleToBeAddedInEcompDB, null);
				List<EPRole> getRoleCreatedInSync = null;
				if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
					final Map<String, String> globalRoleParams = new HashMap<>();
					globalRoleParams.put("appId", String.valueOf(app.getId()));
					globalRoleParams.put("appRoleName", roleToBeAddedInEcompDB.getName());
					getRoleCreatedInSync = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, globalRoleParams, null);
					EPRole epUpdateRole = getRoleCreatedInSync.get(0);
					epUpdateRole.setAppRoleId(epUpdateRole.getId());
					dataAccessService.saveDomainObject(epUpdateRole, null);
				}
				List<EPRole> roleList = new ArrayList<>();
				final Map<String, String> params = new HashMap<>();

				params.put(APP_ROLE_NAME_PARAM, roleToBeAddedInEcompDB.getName());
				boolean isPortalRole = false;
				if (app.getId() == 1) {
					isPortalRole = true;
					roleList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, params, null);
				} else {
					isPortalRole = false;
					params.put(APP_ID, app.getId().toString());
					roleList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, params, null);
				}
				EPRole role = roleList.get(0);
				Role aaFrole = new Role();
				aaFrole.setId(role.getId());
				aaFrole.setActive(role.getActive());
				aaFrole.setPriority(role.getPriority());
				aaFrole.setName(role.getName());
				updateRoleInExternalSystem(aaFrole, app, isPortalRole);
			} catch (Exception e) {
				logger.error(EELFLoggerDelegate.errorLogger,
						"SyncApplicationRolesWithEcompDB: Failed to add or update role in external auth system", e);
			}
		}
	}

	/**
	 * 
	 * It checks description in External Auth System if found any changes updates in DB
	 * 
	 * @param app
	 * @param finalRoleList contains list of External Auth System roles list which is converted to EPRole
	 */
	@SuppressWarnings("unchecked")
	private void checkAndUpdateRoleInDB(EPApp app, List<EPRole> finalRoleList) {
		for (EPRole roleItem : finalRoleList) {
			final Map<String, String> roleParams = new HashMap<>();
			List<EPRole> currentList = null;
			roleParams.put(APP_ROLE_NAME_PARAM, roleItem.getName());
			if (app.getId() == 1) {
				currentList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, roleParams, null);
			} else {
				roleParams.put(APP_ID, app.getId().toString());
				currentList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, roleParams, null);
			}

			if (!currentList.isEmpty()) {
				try {
					Boolean aafRoleActive;
					Boolean localRoleActive;
					boolean result;
					aafRoleActive = Boolean.valueOf(roleItem.getActive());
					localRoleActive = Boolean.valueOf(currentList.get(0).getActive());
					result = aafRoleActive.equals(localRoleActive);
					EPRole updateRole = currentList.get(0);

					if (!result) {
						updateRole.setActive(roleItem.getActive());
						dataAccessService.saveDomainObject(updateRole, null);
					}
					if (roleItem.getPriority() != null
							&& !currentList.get(0).getPriority().equals(roleItem.getPriority())) {
						updateRole.setPriority(roleItem.getPriority());
						dataAccessService.saveDomainObject(updateRole, null);
					}
				} catch (Exception e) {
					logger.error(EELFLoggerDelegate.errorLogger,
							"syncApplicationRolesWithEcompDB: Failed to update role ", e);
				}
			}
		}
	}
	/**
	 * 
	 * It de-activates application roles in DB if not present in External Auth system  
	 * 
	 * @param app
	 * @param finalRoleList contains list of current roles present in External Auth System
	 * @param applicationRolesList contains list of current roles present in DB
	 */
	@SuppressWarnings("unchecked")
	private void inactiveRolesNotInExternalAuthSystem(EPApp app, List<EPRole> finalRoleList,
			List<EPRole> applicationRolesList) {
		final Map<String, EPRole> checkRolesInactive = new HashMap<>();
		for (EPRole extrole : finalRoleList) {
			checkRolesInactive.put(extrole.getName(), extrole);
		}
		for (EPRole role : applicationRolesList) {
			try {
				final Map<String, String> extRoleParams = new HashMap<>();
				List<EPRole> roleList = null;
				extRoleParams.put(APP_ROLE_NAME_PARAM, role.getName());
				if (!checkRolesInactive.containsKey(role.getName())) {
					if (app.getId() == 1) {
						roleList = dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, extRoleParams, null);
					} else {
						extRoleParams.put(APP_ID, app.getId().toString());
						roleList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, extRoleParams, null);
					}
					if(!roleList.isEmpty()) {
						EPRole updateRoleInactive = roleList.get(0);
						updateRoleInactive.setActive(false);
						dataAccessService.saveDomainObject(updateRoleInactive, null);
					}
				}
			} catch (Exception e) {
				logger.error(EELFLoggerDelegate.errorLogger,
						"syncApplicationRolesWithEcompDB: Failed to de-activate role ", e);
			}
		}
	}
	
	@Override
	@SuppressWarnings("unchecked")
	public List<ExternalRoleDetails> getExternalRoleDetailsList(EPApp app,
			ObjectMapper mapper, JSONArray extRole)
			throws IOException {
		List<ExternalRoleDetails> externalRoleDetailsList = new ArrayList<>();
		ExternalAccessPerms externalAccessPerms = new ExternalAccessPerms();
		List<String> functionCodelist = new ArrayList<>();
		Map<String, EPRole> curRolesMap = getCurrentRolesInDB(app);
		for (int i = 0; i < extRole.length(); i++) {
			ExternalRoleDetails externalRoleDetail = new ExternalRoleDetails();
			EPAppRoleFunction ePAppRoleFunction = new EPAppRoleFunction();
			JSONObject Role = (JSONObject) extRole.get(i);
			String name = extRole.getJSONObject(i).getString(ROLE_NAME);
			String actualRoleName = name.substring(app.getNameSpace().length() + 1); 
			SortedSet<ExternalAccessPerms> externalAccessPermsOfRole = new TreeSet<>();
			if (extRole.getJSONObject(i).has(EXTERNAL_AUTH_PERMS)) {
				JSONArray extPerm = (JSONArray) Role.get(EXTERNAL_AUTH_PERMS);
				for (int j = 0; j < extPerm.length(); j++) {
					JSONObject perms = extPerm.getJSONObject(j);
					boolean isNamespaceMatching = EcompPortalUtils.checkNameSpaceMatching(perms.getString("type"),
							app.getNameSpace());
					if (isNamespaceMatching) {
						externalAccessPerms = new ExternalAccessPerms(perms.getString("type"),
								perms.getString("instance"), perms.getString("action"));
						ePAppRoleFunction.setCode(externalAccessPerms.getInstance());
						functionCodelist.add(ePAppRoleFunction.getCode());
						externalAccessPermsOfRole.add(externalAccessPerms);
					}

				}
			}
			externalRoleDetail.setActive(true);
			externalRoleDetail.setName(actualRoleName);
			if (app.getId() == 1) {
				externalRoleDetail.setAppId(null);
			} else {
				externalRoleDetail.setAppId(app.getId());
			}
			// get role functions from DB
			EPRole currRole = curRolesMap.get(actualRoleName
					.replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
			Long roleId = null;
			if (currRole != null)
				roleId = currRole.getId();
			// get role functions from DB
			final Map<String, EPAppRoleFunction> roleFunctionsMap = new HashMap<>();
			final Map<String, Long> appRoleFuncsParams = new HashMap<>();
			if (roleId != null) {
				appRoleFuncsParams.put("appId", app.getId());
				appRoleFuncsParams.put("roleId", roleId);
				List<EPAppRoleFunction> appRoleFunctions = dataAccessService
						.executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", appRoleFuncsParams, null);
				if (!appRoleFunctions.isEmpty()) {
					for (EPAppRoleFunction roleFunc : appRoleFunctions) {
						roleFunctionsMap.put(roleFunc.getCode(), roleFunc);
					}
				}
			}
			if (!externalAccessPermsOfRole.isEmpty()) {
				// Adding functions to role
				for (ExternalAccessPerms externalpermission : externalAccessPermsOfRole) {
					EPAppRoleFunction checkRoleFunctionExits = roleFunctionsMap.get(externalpermission.getInstance());
					if (checkRoleFunctionExits == null) {
						String funcCode = externalpermission.getType().substring(app.getNameSpace().length() + 1)
								+ FUNCTION_PIPE + externalpermission.getInstance() + FUNCTION_PIPE
								+ externalpermission.getAction();
						EPAppRoleFunction checkRoleFunctionPipeExits = roleFunctionsMap.get(funcCode);
						if (checkRoleFunctionPipeExits == null) {
							try {
								final Map<String, String> appFuncsParams = new HashMap<>();
								appFuncsParams.put("appId", String.valueOf(app.getId()));
								appFuncsParams.put("functionCd", externalpermission.getInstance());
								logger.debug(EELFLoggerDelegate.debugLogger,
										"SyncApplicationRolesWithEcompDB: Adding function to the role: {}",
										externalpermission.getInstance());
								List<CentralV2RoleFunction> roleFunction = null;
								roleFunction = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId",
										appFuncsParams, null);
								if (roleFunction.isEmpty()) {
									appFuncsParams.put("functionCd", funcCode);
									roleFunction = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId",
											appFuncsParams, null);
								}
								if (!roleFunction.isEmpty()) {
									EPAppRoleFunction apRoleFunction = new EPAppRoleFunction();
									apRoleFunction.setAppId(app.getId());
									apRoleFunction.setRoleId(roleId);
									apRoleFunction.setCode(roleFunction.get(0).getCode());
									dataAccessService.saveDomainObject(apRoleFunction, null);
								}
							} catch (Exception e) {
								logger.error(EELFLoggerDelegate.errorLogger,
										"SyncApplicationRolesWithEcompDB: Failed to add role function", e);
							}
						}
					}
				}
			}
			externalRoleDetailsList.add(externalRoleDetail);
		}
		return externalRoleDetailsList;
	}

	@Override
	public JSONArray getAppRolesJSONFromExtAuthSystem(EPApp app) throws Exception {
		ResponseEntity<String> response = null;
		HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
		HttpEntity<String> entity = new HttpEntity<>(headers);
		logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: {} ",
				CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
		response = template
				.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
						+ "roles/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
		String res = response.getBody();
		logger.debug(EELFLoggerDelegate.debugLogger,
				"syncApplicationRolesWithEcompDB: Finished GET roles from External Auth system and the result is :",
				res);
		JSONObject jsonObj = new JSONObject(res);
		JSONArray extRole = jsonObj.getJSONArray("role");
		for (int i = 0; i < extRole.length(); i++) {
			if (extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + ADMIN)
					|| extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + OWNER)
					|| (extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + ACCOUNT_ADMINISTRATOR)
							&& !app.getId().equals(PortalConstants.PORTAL_APP_ID))) {
				extRole.remove(i);
				i--;
			}			
		}
		return extRole;
	}
	
	@Override
	public JSONArray getAllUsersByRole(String roleName) throws Exception{
		ResponseEntity<String> response = null;
		HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
		HttpEntity<String> entity = new HttpEntity<>(headers);
		logger.debug(EELFLoggerDelegate.debugLogger, "getAllUsersByRole: {} ",
				CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
		response = template
				.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
						+ "userRoles/role/" + roleName, HttpMethod.GET, entity, String.class);
		String res = response.getBody();
		logger.debug(EELFLoggerDelegate.debugLogger,
				"syncApplicationRolesWithEcompDB: Finished GET roles from External Auth system and the result is :",
				res);
		if(res == null || res.trim().isEmpty()) 
			return null;
		
		JSONObject jsonObj = new JSONObject(res);
		JSONArray extRole = jsonObj.getJSONArray("userRole");
		
		return extRole;
	}

	/**
	 * 
	 * It converts from ExternalRoleDetails.class object to EPRole.class object
	 * 
	 * @param externalRoleDetails
	 * @return EPRole object
	 */
	private EPRole convertExternalRoleDetailstoEpRole(ExternalRoleDetails externalRoleDetails) {
		EPRole role = new EPRole();
		role.setActive(true);
		role.setAppId(externalRoleDetails.getAppId());
		role.setAppRoleId(externalRoleDetails.getAppRoleId());
		role.setName(externalRoleDetails.getName());
		role.setPriority(externalRoleDetails.getPriority());
		return role;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Integer bulkUploadUserRoles(String uebkey) throws Exception {
		EPApp app = getApp(uebkey).get(0);
		final Map<String, String> params = new HashMap<>();
		params.put("uebKey", app.getUebKey());
		List<BulkUploadUserRoles> userRolesList = null;
		Integer userRolesAdded = 0;
		if (app.getCentralAuth()) {
			userRolesList = dataAccessService.executeNamedQuery("getBulkUserRoles", params, null);
			for (BulkUploadUserRoles userRolesUpload : userRolesList) {
				if(!userRolesUpload.getOrgUserId().equals("su1234")){
					addUserRoleInExternalSystem(userRolesUpload);
					userRolesAdded++;
				}
			}
		}
		return userRolesAdded;
	}

	/**
	 * Its adding a user role in external auth system while doing bulk upload 
	 * 
	 * @param userRolesUpload
	 */
	private void addUserRoleInExternalSystem(BulkUploadUserRoles userRolesUpload) {
		try {
			String name = "";
			ObjectMapper mapper = new ObjectMapper();
			if (EPCommonSystemProperties
					.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
				name = userRolesUpload.getOrgUserId()
						+ SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
			}
			ExternalAccessUser extUser = new ExternalAccessUser(name,
					userRolesUpload.getAppNameSpace() + "." + userRolesUpload.getRoleName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
			String userRole = mapper.writeValueAsString(extUser);
			HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
			HttpEntity<String> entity = new HttpEntity<>(userRole, headers);
			template.exchange(
					SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole",
					HttpMethod.POST, entity, String.class);
		} catch(HttpClientErrorException e){
			logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addUserRoleInExternalSystem", e);
			EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
		} catch (Exception e) {
			if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
				logger.error(EELFLoggerDelegate.errorLogger, "addUserRoleInExternalSystem: UserRole already exits but does not break functionality");
			} else {
				logger.error(EELFLoggerDelegate.errorLogger, "addUserRoleInExternalSystem: Failed to addUserRoleInExternalSystem", e);
			}
		}
	}

	@Override
	public void deleteRoleDependencyRecords(Session localSession, Long roleId, Long appId, boolean isPortalRequest) throws Exception {
		try {
			String sql = ""; 
			Query query = null;
			
			//It should delete only when it portal's roleId
			if(appId.equals(PortalConstants.PORTAL_APP_ID)){
			// Delete from fn_role_function
			sql = "DELETE FROM fn_role_function WHERE role_id=" + roleId;
			logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
			query = localSession.createSQLQuery(sql);
			query.executeUpdate();
			
			// Delete from fn_role_composite
			sql = "DELETE FROM fn_role_composite WHERE parent_role_id=" + roleId + " OR child_role_id=" + roleId;
			logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
			query = localSession.createSQLQuery(sql);
			query.executeUpdate();
			}
			
			// Delete from ep_app_role_function
			sql = "DELETE FROM ep_app_role_function WHERE role_id=" + roleId;
			logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
			query = localSession.createSQLQuery(sql);
			query.executeUpdate();

			// Delete from ep_role_notification
			sql = "DELETE FROM ep_role_notification WHERE role_id=" + roleId;
			logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
			query = localSession.createSQLQuery(sql);
			query.executeUpdate();
			
			// Delete from fn_user_pseudo_role
			sql = "DELETE FROM fn_user_pseudo_role WHERE pseudo_role_id=" + roleId;
			logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
			query = localSession.createSQLQuery(sql);
			query.executeUpdate();

			// Delete form EP_WIDGET_CATALOG_ROLE
			sql = "DELETE FROM EP_WIDGET_CATALOG_ROLE WHERE role_id=" + roleId;
			logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
			query = localSession.createSQLQuery(sql);
			query.executeUpdate();

			// Delete form EP_WIDGET_CATALOG_ROLE
			sql = "DELETE FROM ep_user_roles_request_det WHERE requested_role_id=" + roleId;
			logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
			query = localSession.createSQLQuery(sql);
			query.executeUpdate();

			if(!isPortalRequest) {
				// Delete form fn_menu_functional_roles
				sql = "DELETE FROM fn_menu_functional_roles WHERE role_id=" + roleId;
				logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
				query = localSession.createSQLQuery(sql);
				query.executeUpdate();	
			}
		} catch (Exception e) {
			logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleDependeciesRecord: failed ", e);
			throw new DeleteDomainObjectFailedException("delete Failed" + e.getMessage());
		}

	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<String> getMenuFunctionsList(String uebkey) throws Exception {
		List<String> appMenuFunctionsList = null;
		List<String> appMenuFunctionsFinalList = new ArrayList<>();
		try {
			EPApp app = getApp(uebkey).get(0);
			final Map<String, Long> appParams = new HashMap<>();
			appParams.put(APP_ID, app.getId());
			appMenuFunctionsList = dataAccessService.executeNamedQuery("getMenuFunctions", appParams, null);
			for(String appMenuFunction : appMenuFunctionsList) {
				if(appMenuFunction.contains(FUNCTION_PIPE)) {
					appMenuFunctionsFinalList.add(EcompPortalUtils.getFunctionCode(appMenuFunction));
				} else {
					appMenuFunctionsFinalList.add(appMenuFunction);
				}
			}
		} catch (Exception e) {
			logger.error(EELFLoggerDelegate.errorLogger, "getMenuFunctionsList: Failed", e);
			return appMenuFunctionsFinalList;
		}
		return appMenuFunctionsFinalList;
	}

	@SuppressWarnings({ "unchecked"})
	@Override
	public List<EcompUser> getAllAppUsers(String uebkey) throws Exception {
		List<String> usersList = new ArrayList<>();
        List<EcompUser> usersfinalList = new ArrayList<>();
        try {
               EPApp app = getApp(uebkey).get(0);
               final Map<String, Long> appParams = new HashMap<>();
               appParams.put("appId", app.getId());
               List<EcompUserRoles> userList = (List<EcompUserRoles>) dataAccessService
                            .executeNamedQuery("ApplicationUserRoles", appParams, null);
               for (EcompUserRoles ecompUserRole : userList) {
                     boolean found = false;
                     Set<EcompRole> roles = null;
                     for (EcompUser user : usersfinalList) {
                            if (user.getOrgUserId().equals(ecompUserRole.getOrgUserId())) {
                                   EcompRole ecompRole = new EcompRole();
                                   ecompRole.setId(ecompUserRole.getRoleId());
                                   ecompRole.setName(ecompUserRole.getRoleName());
                                   roles = user.getRoles();
                                   EcompRole role = roles.stream().filter(x -> x.getName().equals(ecompUserRole.getRoleName())).findAny()
                                                 .orElse(null);
                                   SortedSet<EcompRoleFunction> roleFunctionSet = new TreeSet<>();
                                   if(role != null)
                                   {
                                          roleFunctionSet = (SortedSet<EcompRoleFunction>) role.getRoleFunctions();
                                   }
                                          
                             String functionCode = EcompPortalUtils.getFunctionCode(ecompUserRole.getFunctionCode());
                            functionCode = EPUserUtils.decodeFunctionCode(functionCode);
                            EcompRoleFunction epRoleFunction = new EcompRoleFunction();
                            epRoleFunction.setName(ecompUserRole.getFunctionName());
                            epRoleFunction.setCode(EPUserUtils.decodeFunctionCode(functionCode));
                            epRoleFunction.setType(getFunctionCodeType(ecompUserRole.getFunctionCode()));
                            epRoleFunction.setAction(getFunctionCodeAction(ecompUserRole.getFunctionCode()));
                            roleFunctionSet.add(epRoleFunction);
                        ecompRole.setRoleFunctions(roleFunctionSet);
                                   roles.add(ecompRole);
                                   user.setRoles(roles);
                                   found = true;
                                   break;
                            }
                     }

                     if (!found) {
                            EcompUser epUser = new EcompUser();
                            epUser.setOrgId(ecompUserRole.getOrgId());
                            epUser.setManagerId(ecompUserRole.getManagerId());
                            epUser.setFirstName(ecompUserRole.getFirstName());
                            epUser.setLastName(ecompUserRole.getLastName());
                            epUser.setPhone(ecompUserRole.getPhone());
                            epUser.setEmail(ecompUserRole.getEmail());
                            epUser.setOrgUserId(ecompUserRole.getOrgUserId());
                            epUser.setOrgCode(ecompUserRole.getOrgCode());
                            epUser.setOrgManagerUserId(ecompUserRole.getOrgManagerUserId());
                            epUser.setJobTitle(ecompUserRole.getJobTitle());
                            epUser.setLoginId(ecompUserRole.getLoginId());
                            epUser.setActive(true);
                            roles = new HashSet<>();
                            EcompRole ecompRole = new EcompRole();
                            ecompRole.setId(ecompUserRole.getRoleId());
                            ecompRole.setName(ecompUserRole.getRoleName());
              SortedSet<EcompRoleFunction> roleFunctionSet = new TreeSet<>();
              
                            String functionCode = EcompPortalUtils.getFunctionCode(ecompUserRole.getFunctionCode());
              functionCode = EPUserUtils.decodeFunctionCode(functionCode);
              EcompRoleFunction epRoleFunction = new EcompRoleFunction();
              epRoleFunction.setName(ecompUserRole.getFunctionName());
              epRoleFunction.setCode(EPUserUtils.decodeFunctionCode(functionCode));
              epRoleFunction.setType(getFunctionCodeType(ecompUserRole.getFunctionCode()));
              epRoleFunction.setAction(getFunctionCodeAction(ecompUserRole.getFunctionCode()));
              roleFunctionSet.add(epRoleFunction);
              ecompRole.setRoleFunctions(roleFunctionSet);
                            roles.add(ecompRole);
                            epUser.setRoles(roles);
                            usersfinalList.add(epUser);
                     }
               }
               ObjectMapper mapper = new ObjectMapper();

               for (EcompUser u1 : usersfinalList) {
                     String str = mapper.writeValueAsString(u1);
                     usersList.add(str);
               }
        } catch (Exception e) {
               logger.error(EELFLoggerDelegate.errorLogger, "getAllUsers failed", e);
               throw e;
        }
        return usersfinalList;

	}
	

	@Override
	public Role ConvertCentralRoleToRole(String result) {
		ObjectMapper mapper = new ObjectMapper();
		mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		Role newRole = new Role();
		try {
			newRole = mapper.readValue(result, Role.class);
		} catch (IOException e) {
			logger.error(EELFLoggerDelegate.errorLogger, "Failed to convert the result to Role Object", e);
		}
		if (newRole.getRoleFunctions() != null) {
			@SuppressWarnings("unchecked")
			Set<RoleFunction> roleFunctionList = newRole.getRoleFunctions();
			Set<RoleFunction> roleFunctionListNew = new HashSet<>();
			Iterator<RoleFunction> itetaror = roleFunctionList.iterator();
			while (itetaror.hasNext()) {
				Object nextValue = itetaror.next();
				RoleFunction roleFun = mapper.convertValue(nextValue, RoleFunction.class);
				roleFunctionListNew.add(roleFun);
			}
			newRole.setRoleFunctions(roleFunctionListNew);
		}
		return newRole;
	}
	
	@Override
	@SuppressWarnings("unchecked")
	public List<CentralizedApp> getCentralizedAppsOfUser(String userId) {
		Map<String, String> params = new HashMap<>();
		params.put("userId", userId);
		List<CentralizedApp> centralizedAppsList = new ArrayList<>();
		try{
			centralizedAppsList =  dataAccessService
					.executeNamedQuery("getCentralizedAppsOfUser", params, null);
		}catch (Exception e) {
			logger.error(EELFLoggerDelegate.errorLogger, "getCentralizedAppsOfUser failed", e);
		}
		return centralizedAppsList;
	}

	@SuppressWarnings("unchecked")
	public List<CentralV2Role> getGlobalRolesOfApplication(Long appId) {
		Map<String, Long> params = new HashMap<>();
		params.put("appId", appId);
		List<GlobalRoleWithApplicationRoleFunction> globalRoles = new ArrayList<>();
		try {
			globalRoles = dataAccessService.executeNamedQuery("getGlobalRoleWithApplicationRoleFunctions", params,
					null);
		} catch (Exception e) {
			logger.error(EELFLoggerDelegate.errorLogger, "getCentralizedAppsOfUser failed", e);
		}
		List<CentralV2Role> rolesfinalList = new ArrayList<>();
		if (globalRoles.size() > 0)
			rolesfinalList = finalListOfCentralRoles(globalRoles);
		return rolesfinalList;
	}

	@SuppressWarnings("unchecked")
	private CentralV2Role getGlobalRoleForRequestedApp(long requestedAppId, long roleId) {
		CentralV2Role finalGlobalrole = null;
		List<GlobalRoleWithApplicationRoleFunction> roleWithApplicationRoleFucntions = new ArrayList<>();
		Map<String, Long> params = new HashMap<>();
		params.put("roleId", roleId);
		params.put("requestedAppId", requestedAppId);
		try {
			roleWithApplicationRoleFucntions = dataAccessService.executeNamedQuery("getGlobalRoleForRequestedApp",
					params, null);
		} catch (Exception e) {
			logger.error(EELFLoggerDelegate.errorLogger, "getGlobalRoleForRequestedApp failed", e);
		}
		if (roleWithApplicationRoleFucntions.size() > 0) {
			List<CentralV2Role> rolesfinalList = finalListOfCentralRoles(roleWithApplicationRoleFucntions);
			finalGlobalrole = rolesfinalList.get(0);
		} else {
			List<EPRole> roleList = getPortalAppRoleInfo(roleId);
			finalGlobalrole = convertRoleToCentralV2Role(roleList.get(0));
		}
		return finalGlobalrole;
	}

	private List<CentralV2Role> finalListOfCentralRoles(List<GlobalRoleWithApplicationRoleFunction> globalRoles) {
		List<CentralV2Role> rolesfinalList = new ArrayList<>();
		for (GlobalRoleWithApplicationRoleFunction role : globalRoles) {
			boolean found = false;
			for (CentralV2Role cenRole : rolesfinalList) {
				if (role.getRoleId().equals(cenRole.getId())) {
					SortedSet<CentralV2RoleFunction> roleFunctions = cenRole.getRoleFunctions();
					CentralV2RoleFunction cenRoleFun = createCentralRoleFunctionForGlobalRole(role);
					roleFunctions.add(cenRoleFun);
					cenRole.setRoleFunctions(roleFunctions);
					found = true;
					break;
				}
			}
			if (!found) {
				CentralV2Role cenrole = new CentralV2Role();
				cenrole.setName(role.getRoleName());
				cenrole.setId(role.getRoleId());
				cenrole.setActive(role.isActive());
				cenrole.setPriority(role.getPriority());
				SortedSet<CentralV2RoleFunction> roleFunctions = new TreeSet<>();
				CentralV2RoleFunction cenRoleFun = createCentralRoleFunctionForGlobalRole(role);
				roleFunctions.add(cenRoleFun);
				cenrole.setRoleFunctions(roleFunctions);
				rolesfinalList.add(cenrole);
			}
		}
		return rolesfinalList;
	}

	private CentralV2RoleFunction createCentralRoleFunctionForGlobalRole(GlobalRoleWithApplicationRoleFunction role) {
		String instance;
		String type;
		String action;
		CentralV2RoleFunction cenRoleFun;
		if(role.getFunctionCd().contains(FUNCTION_PIPE)){
			instance = EcompPortalUtils.getFunctionCode(role.getFunctionCd());
			type = EcompPortalUtils.getFunctionType(role.getFunctionCd());
			action = EcompPortalUtils.getFunctionAction(role.getFunctionCd());
			cenRoleFun = new CentralV2RoleFunction(null, instance, role.getFunctionName(), null, type, action, null);
		} else{
			type = getFunctionCodeType(role.getFunctionCd());
			action = getFunctionCodeAction(role.getFunctionCd());
			cenRoleFun = new CentralV2RoleFunction(null, role.getFunctionCd(), role.getFunctionName(), null, type, action, null);
		}
		return cenRoleFun;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<EPRole> getGlobalRolesOfPortal() {
		List<EPRole> globalRoles = new ArrayList<>();
		try {
			globalRoles = dataAccessService.executeNamedQuery("getGlobalRolesOfPortal", null, null);
		} catch (Exception e) {
			logger.error(EELFLoggerDelegate.errorLogger, "getGlobalRolesOfPortal failed", e);
		}
		return globalRoles;
	}

	private CentralV2Role convertRoleToCentralV2Role(EPRole role) {
	 return new CentralV2Role(role.getId(), role.getCreated(), role.getModified(), role.getCreatedId(),
				role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(), role.getPriority(),
				new TreeSet<>(), new TreeSet<>(), new TreeSet<>());
		
	}
	
	@Override
	public List<CentralRoleFunction> convertCentralRoleFunctionToRoleFunctionObject(List<CentralV2RoleFunction> answer) {
		List<CentralRoleFunction> addRoleFuncList = new ArrayList<>();
		for(CentralV2RoleFunction cenRoleFunc : answer){
			CentralRoleFunction setRoleFunc = new CentralRoleFunction();
			setRoleFunc.setCode(cenRoleFunc.getCode());
			setRoleFunc.setName(cenRoleFunc.getName());
			addRoleFuncList.add(setRoleFunc);
		}		
		return addRoleFuncList;
	}

	@Override
	public CentralUser getUserRoles(String loginId, String uebkey) throws Exception {
		CentralUser sendUserRoles = null;

		try {
			CentralV2User cenV2User = getV2UserAppRoles(loginId, uebkey);
			sendUserRoles = convertV2UserRolesToOlderVersion(cenV2User);
		} catch (Exception e) {
			logger.error(EELFLoggerDelegate.errorLogger, "getUserRoles: failed", e);
			throw e;
		}
		return sendUserRoles;
	}

	/**
	 * 
	 * It returns V2 CentralUser object if user has any roles and permissions
	 * 
	 * @param loginId
	 * @param uebkey
	 * @return CentralUser object
	 * @throws Exception
	 */
	private CentralV2User getV2UserAppRoles(String loginId, String uebkey) throws Exception {
		EPApp app;
		List<EPUser> epUserList;
		List<EPApp> appList = getApp(uebkey);
		app = appList.get(0);
		epUserList = getUser(loginId);
		EPUser user = epUserList.get(0);
		Set<EPUserApp> userAppSet = user.getEPUserApps();
		return createEPUser(user, userAppSet, app);
	}

	/**
	 * It converts V2 CentralUser object to old version CentralUser object
	 * 
	 * @param cenV2User
	 * @return EPUser object
	 */
	private CentralUser convertV2UserRolesToOlderVersion(CentralV2User cenV2User) {
			Set<CentralV2UserApp> userV2Apps = cenV2User.getUserApps();
			Set<CentralUserApp> userApps = new TreeSet<>();
			for(CentralV2UserApp userApp : userV2Apps){				
				CentralApp app  = userApp.getApp();
				CentralUserApp cua = new CentralUserApp();
				cua.setUserId(null);
				cua.setApp(app);
				SortedSet<CentralRoleFunction> cenRoleFunction = new TreeSet<>();
				for(CentralV2RoleFunction  cenV2RoleFunc : userApp.getRole().getRoleFunctions() ){					
					CentralRoleFunction cenRoleFunc = new CentralRoleFunction(cenV2RoleFunc.getCode(), cenV2RoleFunc.getName());								
					cenRoleFunction.add(cenRoleFunc);
				}
				CentralRole role = new CentralRole(userApp.getRole().getId(), userApp.getRole().getName(), userApp.getRole().getActive(), userApp.getRole().getPriority(),
						cenRoleFunction);
				cua.setRole(role);
				userApps.add(cua);
			}
			return new CentralUser(cenV2User.getId(), cenV2User.getCreated(), cenV2User.getModified(), 
					cenV2User.getCreatedId(),cenV2User.getModifiedId(), 
					cenV2User.getRowNum(), cenV2User.getOrgId(), cenV2User.getManagerId(), cenV2User.getFirstName(), 
					cenV2User.getMiddleInitial(), cenV2User.getLastName(), cenV2User.getPhone(), cenV2User.getFax(), 
					cenV2User.getCellular(),cenV2User.getEmail(),cenV2User.getAddressId(),cenV2User.getAlertMethodCd(),
					cenV2User.getHrid(),cenV2User.getOrgUserId(),cenV2User.getOrgCode(),cenV2User.getAddress1(), 
					cenV2User.getAddress2(),cenV2User.getCity(),cenV2User.getState(),cenV2User.getZipCode(),cenV2User.getCountry(), 
					cenV2User.getOrgManagerUserId(),cenV2User.getLocationClli(),cenV2User.getBusinessCountryCode(), 
					cenV2User.getBusinessCountryName(),cenV2User.getBusinessUnit(),cenV2User.getBusinessUnitName(), 
					cenV2User.getDepartment(),cenV2User.getDepartmentName(),cenV2User.getCompanyCode(), 
					cenV2User.getCompany(),cenV2User.getZipCodeSuffix(),cenV2User.getJobTitle(), 
					cenV2User.getCommandChain(),cenV2User.getSiloStatus(),cenV2User.getCostCenter(),
					cenV2User.getFinancialLocCode(),cenV2User.getLoginId(),cenV2User.getLoginPwd(), 
					cenV2User.getLastLoginDate(),cenV2User.isActive(),cenV2User.isInternal(),cenV2User.getSelectedProfileId(),cenV2User.getTimeZoneId(),
					cenV2User.isOnline(),cenV2User.getChatId(), 
					userApps);
	}

	@Override
	public List<CentralRole> convertV2CentralRoleListToOldVerisonCentralRoleList(List<CentralV2Role> v2CenRoleList) {
		List<CentralRole> cenRoleList = new ArrayList<>();
			for(CentralV2Role v2CenRole : v2CenRoleList){
				SortedSet<CentralRoleFunction> cenRoleFuncList = new TreeSet<>();
				for(CentralV2RoleFunction v2CenRoleFunc: v2CenRole.getRoleFunctions()){
					CentralRoleFunction roleFunc = new CentralRoleFunction(v2CenRoleFunc.getCode(), v2CenRoleFunc.getName());
					cenRoleFuncList.add(roleFunc);
				}
				CentralRole role = new CentralRole(v2CenRole.getId(), v2CenRole.getName(), v2CenRole.getActive(), v2CenRole.getPriority(), cenRoleFuncList);
				cenRoleList.add(role);
			}		
		return cenRoleList;
	}
	
	@Override
	public ResponseEntity<String> getNameSpaceIfExists(EPApp app) throws Exception {
		HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
		HttpEntity<String> entity = new HttpEntity<>(headers);
		logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists: Connecting to External Auth system");
		ResponseEntity<String> response = null;
		try {
			response = template
					.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
							+ "nss/" + app.getNameSpace(), HttpMethod.GET, entity, String.class);
			logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists: Finished ",
					response.getStatusCode().value());
		} catch (HttpClientErrorException e) {
			logger.error(EELFLoggerDelegate.errorLogger, "checkIfNameSpaceExists failed", e);
			EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
			if (e.getStatusCode() == HttpStatus.NOT_FOUND)
				throw new InvalidApplicationException("Invalid NameSpace");
			else
				throw e;
		}
		return response;
	}
	
	@Override
	public CentralRole convertV2CentralRoleToOldVerisonCentralRole(CentralV2Role v2CenRole) {
		SortedSet<CentralRoleFunction> cenRoleFuncList = new TreeSet<>();
		for (CentralV2RoleFunction v2CenRoleFunc : v2CenRole.getRoleFunctions()) {
			CentralRoleFunction roleFunc = new CentralRoleFunction(v2CenRoleFunc.getCode(), v2CenRoleFunc.getName());
			cenRoleFuncList.add(roleFunc);
		}
		return new CentralRole(v2CenRole.getId(), v2CenRole.getName(), v2CenRole.getActive(), v2CenRole.getPriority(),
				cenRoleFuncList);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Integer bulkUploadUsersSingleRole(String uebkey, Long roleId, String modifiedRoleName) throws Exception {
		EPApp app = getApp(uebkey).get(0);
		final Map<String, String> params = new HashMap<>();
		params.put("uebKey", app.getUebKey());
		params.put("roleId", String.valueOf(roleId));
		List<BulkUploadUserRoles> userRolesList = null;
		Integer userRolesAdded = 0;
		if (app.getCentralAuth()) {
			userRolesList = dataAccessService.executeNamedQuery("getBulkUsersForSingleRole", params, null);
			for (BulkUploadUserRoles userRolesUpload : userRolesList) {
				userRolesUpload.setRoleName(modifiedRoleName);
				if(!userRolesUpload.getOrgUserId().equals("su1234")){
					addUserRoleInExternalSystem(userRolesUpload);
					userRolesAdded++;
				}
			}
		}
		return userRolesAdded;
	}	
	
	@Override
	public String encodeFunctionCode(String funCode){
		String encodedString = funCode;
		List<Pattern> encodingList = new ArrayList<>();
		encodingList.add(Pattern.compile("/"));
		encodingList.add(Pattern.compile("-"));
		for (Pattern xssInputPattern : encodingList) {
			encodedString = xssInputPattern.matcher(encodedString)
					.replaceAll("%" + Hex.encodeHexString(xssInputPattern.toString().getBytes()));
		}		
		encodedString = encodedString.replaceAll("\\*", "%"+ Hex.encodeHexString("*".getBytes()));
		return encodedString;
	}
	
	@Override
	public void bulkUploadRoleFunc(UploadRoleFunctionExtSystem data, EPApp app) throws Exception {
		ObjectMapper mapper = new ObjectMapper();
		HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
		try {
			ExternalAccessRolePerms extRolePerms;
			ExternalAccessPerms extPerms;
			extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + data.getType(), encodeFunctionCode(data.getInstance()), data.getAction());
			String appNameSpace = "";
			if(data.getIsGlobalRolePartnerFunc()) {
				appNameSpace =  epAppService.getApp(1l).getNameSpace();
			} else {
				appNameSpace =  app.getNameSpace();
			}
			extRolePerms = new ExternalAccessRolePerms(extPerms,
					appNameSpace + "."
							+ data.getRoleName().replaceAll(
									EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS,
									"_"));
			String updateRolePerms = mapper.writeValueAsString(extRolePerms);
			HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
			updateRoleFunctionInExternalSystem(updateRolePerms, entity);
		} catch (HttpClientErrorException e) {
			logger.error(EELFLoggerDelegate.errorLogger,
					"HttpClientErrorException - Failed to add role function in external central auth system", e);
			EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
			throw e;
		} catch (Exception e) {
			logger.error(EELFLoggerDelegate.errorLogger,
					"addFunctionInExternalSystem: Failed to add role fucntion in external central auth system", e);
			throw e;
		}
		
	}

	private void updateRoleFunctionInExternalSystem(String updateRolePerms, HttpEntity<String> entity) {
		logger.debug(EELFLoggerDelegate.debugLogger, "bulkUploadRoleFunc: {} for POST: {}",
				CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms);
		ResponseEntity<String> addPermResponse = template.exchange(
				SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
				HttpMethod.POST, entity, String.class);
		logger.debug(EELFLoggerDelegate.debugLogger,
				"bulkUploadRoleFunc: Finished adding permission for POST: {} and status code: {} ",
				addPermResponse.getStatusCode().value(), updateRolePerms);
	}
	
	@Override
	public void syncApplicationUserRolesFromExtAuthSystem(String loginId) throws Exception {
		String name = "";
		if (EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
			name = loginId + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
		}
		HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
		HttpEntity<String> getUserRolesEntity = new HttpEntity<>(headers);
		ResponseEntity<String> getResponse = getUserRolesFromExtAuthSystem(name, getUserRolesEntity);
		List<ExternalAccessUserRoleDetail> userRoleDetailList = new ArrayList<>();
		String res = getResponse.getBody();
		JSONObject jsonObj = null;
		JSONArray extRoles = null;
		if (!res.equals("{}")) {
			jsonObj = new JSONObject(res);
			extRoles = jsonObj.getJSONArray("role");
		}
		updateUserRolesInLocal(userRoleDetailList, extRoles, loginId);
	}

	@SuppressWarnings("unchecked")
	private void updateUserRolesInLocal(List<ExternalAccessUserRoleDetail> userRoleDetailList, JSONArray extRoles,
			String loginId) throws InvalidUserException {
		HashMap<String, String> userParams = new HashMap<>();
		userParams.put("orgUserId", loginId);
		// Get all centralized applications existing user roles from local
		List<CentralizedAppRoles> currentUserAppRoles = dataAccessService
				.executeNamedQuery("getUserCentralizedAppRoles", userParams, null);
		EPUser user = getUser(loginId).get(0);
		// Get all centralized applications roles from local
		HashMap<String, CentralizedAppRoles> cenAppRolesMap = getCentralizedAppRoleList();
		HashMap<String, CentralizedAppRoles> currentCentralizedUserAppRolesMap = getCurrentUserCentralizedAppRoles(
				currentUserAppRoles);
		// Get all centralized applications + admin role from local
		HashMap<String, EPApp> centralisedAppsMap = getCentralizedAdminAppsInfo();
		if (extRoles != null) {
			ExternalAccessUserRoleDetail userRoleDetail = null;
			for (int i = 0; i < extRoles.length(); i++) {
				if (!extRoles.getJSONObject(i).getString("name").endsWith(ADMIN)
						&& !extRoles.getJSONObject(i).getString("name").endsWith(OWNER)) {
					userRoleDetail = new ExternalAccessUserRoleDetail(extRoles.getJSONObject(i).getString("name"),
							null);
					userRoleDetailList.add(userRoleDetail);
				}
			}
			addUserRolesInLocal(userRoleDetailList, user, cenAppRolesMap, currentCentralizedUserAppRolesMap,
					centralisedAppsMap);
		}
	}

	private void addUserRolesInLocal(List<ExternalAccessUserRoleDetail> userRoleDetailList, EPUser user,
			HashMap<String, CentralizedAppRoles> cenAppRolesMap,
			HashMap<String, CentralizedAppRoles> currentCentralizedUserAppRolesMap,
			HashMap<String, EPApp> centralisedAppsMap) {
		for (ExternalAccessUserRoleDetail extUserRoleDetail : userRoleDetailList) {
			try {
				// check if user already has role in local
				if (!currentCentralizedUserAppRolesMap.containsKey(extUserRoleDetail.getName())) {
					CentralizedAppRoles getCenAppRole = cenAppRolesMap.get(extUserRoleDetail.getName());
					if (getCenAppRole != null) {
						logger.debug(EELFLoggerDelegate.debugLogger, "addUserRolesInLocal: Adding user role from external auth system  {}",
								extUserRoleDetail.toString());
						EPUserApp userApp = new EPUserApp();
						EPApp app = new EPApp();
						app.setId(getCenAppRole.getAppId());
						EPRole epRole = new EPRole();
						epRole.setId(getCenAppRole.getRoleId());
						userApp.setApp(app);
						userApp.setUserId(user.getId());
						userApp.setRole(epRole);
						dataAccessService.saveDomainObject(userApp, null);
						logger.debug(EELFLoggerDelegate.debugLogger, "addUserRolesInLocal: Finished user role from external auth system  {}",
								extUserRoleDetail.toString());
					} else if (getCenAppRole == null // check if user has app account admin role
							&& extUserRoleDetail.getName().endsWith(PortalConstants.ADMIN_ROLE.replaceAll(
									EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"))) {
						EPApp app = centralisedAppsMap.get(extUserRoleDetail.getName());
						if (app != null) {
							logger.debug(EELFLoggerDelegate.debugLogger, "addUserRolesInLocal: Adding user role from external auth system  {}",
									extUserRoleDetail.toString());
							EPUserApp userApp = new EPUserApp();
							EPRole epRole = new EPRole();
							epRole.setId(PortalConstants.ACCOUNT_ADMIN_ROLE_ID);
							userApp.setApp(app);
							userApp.setUserId(user.getId());
							userApp.setRole(epRole);
							dataAccessService.saveDomainObject(userApp, null);
							logger.debug(EELFLoggerDelegate.debugLogger, "addUserRolesInLocal: Finished user role from external auth system  {}",
									extUserRoleDetail.toString());
						}
					}
				}
			} catch (Exception e) {
				logger.error(EELFLoggerDelegate.errorLogger,
						"addUserRolesInLocal - Failed to update user role in local from external auth system {} ",
						extUserRoleDetail.toString(), e);
			}
		}
	}

	@SuppressWarnings("unchecked")
	private HashMap<String, EPApp> getCentralizedAdminAppsInfo() {
		List<EPApp> centralizedApps = dataAccessService
				.executeNamedQuery("getCentralizedApps", null, null);
		HashMap<String, EPApp> centralisedAppsMap = new HashMap<>();
		for (EPApp cenApp : centralizedApps) {
			centralisedAppsMap.put(cenApp.getNameSpace()+ "." +
					PortalConstants.ADMIN_ROLE.replaceAll(
							EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), cenApp);
		}
		return centralisedAppsMap;
	}

	private HashMap<String, CentralizedAppRoles> getCurrentUserCentralizedAppRoles(
			List<CentralizedAppRoles> currentUserAppRoles) {
		HashMap<String, CentralizedAppRoles> currentCentralizedUserAppRolesMap = new HashMap<>();
		for (CentralizedAppRoles cenAppUserRole : currentUserAppRoles) {
			currentCentralizedUserAppRolesMap.put(
					cenAppUserRole.getAppNameSpace() + "." + cenAppUserRole.getRoleName()
							.replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
							cenAppUserRole);
		}
		return currentCentralizedUserAppRolesMap;
	}

	@SuppressWarnings("unchecked")
	private HashMap<String, CentralizedAppRoles> getCentralizedAppRoleList() {
		List<CentralizedAppRoles> centralizedAppRoles = dataAccessService
				.executeNamedQuery("getAllCentralizedAppsRoles", null, null);
		HashMap<String, CentralizedAppRoles> cenAppRolesMap = new HashMap<>();
		for (CentralizedAppRoles CentralizedAppRole : centralizedAppRoles) {
			cenAppRolesMap.put(
					CentralizedAppRole.getAppNameSpace() + "." + CentralizedAppRole.getRoleName()
							.replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
					CentralizedAppRole);
		}
		return cenAppRolesMap;
	}
	
	@Override
	public ResponseEntity<String> getUserRolesFromExtAuthSystem(String name, HttpEntity<String> getUserRolesEntity) {
		logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to external system to get current user roles");
		ResponseEntity<String> getResponse = template
				.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
						+ "roles/user/" + name, HttpMethod.GET, getUserRolesEntity, String.class);
		if (getResponse.getStatusCode().value() == 200) {
			logger.debug(EELFLoggerDelegate.debugLogger, "getAllUserRoleFromExtAuthSystem: Finished GET user roles from external system and received user roles {}",
					getResponse.getBody());

		}else{
			logger.error(EELFLoggerDelegate.errorLogger, "getAllUserRoleFromExtAuthSystem: Failed GET user roles from external system and received user roles {}",getResponse.getBody() );
			EPLogUtil.logExternalAuthAccessAlarm(logger, getResponse.getStatusCode());
		}
		return getResponse;
	}

}