aboutsummaryrefslogtreecommitdiffstats
path: root/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/XACMLPapServlet.java
blob: efc70708559af22672f8c356da81df305bf8f6f5 (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
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
/*-
 * ============LICENSE_START=======================================================
 * ECOMP-PAP-REST
 * ================================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.openecomp.policy.pap.xacml.rest;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.net.URL;
import java.net.URLDecoder;
import java.net.UnknownHostException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArrayList;

import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityManagerFactory;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.openecomp.policy.pap.xacml.rest.adapters.PolicyRestAdapter;
import org.openecomp.policy.pap.xacml.rest.components.ActionPolicy;
import org.openecomp.policy.pap.xacml.rest.components.AutoPushPolicy;
import org.openecomp.policy.pap.xacml.rest.components.ClosedLoopPolicy;
import org.openecomp.policy.pap.xacml.rest.components.ConfigPolicy;
import org.openecomp.policy.pap.xacml.rest.components.CreateBrmsParamPolicy;
import org.openecomp.policy.pap.xacml.rest.components.CreateBrmsRawPolicy;
import org.openecomp.policy.pap.xacml.rest.components.CreateClosedLoopPerformanceMetrics;
import org.openecomp.policy.pap.xacml.rest.components.CreateNewMicroSerivceModel;
import org.openecomp.policy.pap.xacml.rest.components.DecisionPolicy;
import org.openecomp.policy.pap.xacml.rest.components.FirewallConfigPolicy;
import org.openecomp.policy.pap.xacml.rest.components.MicroServiceConfigPolicy;
import org.openecomp.policy.pap.xacml.rest.components.Policy;
import org.openecomp.policy.pap.xacml.rest.components.PolicyDBDao;
import org.openecomp.policy.pap.xacml.rest.components.PolicyDBDaoTransaction;
import org.openecomp.policy.pap.xacml.rest.model.RemoveGroupPolicy;
import org.openecomp.policy.pap.xacml.rest.util.JPAUtils;
import org.openecomp.policy.pap.xacml.restAuth.CheckPDP;
import org.openecomp.policy.rest.XACMLRest;
import org.openecomp.policy.rest.XACMLRestProperties;
import org.openecomp.policy.rest.jpa.ActionPolicyDict;
import org.openecomp.policy.rest.jpa.BRMSParamTemplate;
import org.openecomp.policy.rest.jpa.MicroServiceModels;
import org.openecomp.policy.rest.jpa.PolicyEditorScopes;
import org.openecomp.policy.rest.jpa.PolicyScore;
import org.openecomp.policy.rest.jpa.PolicyVersion;
import org.openecomp.policy.rest.jpa.UserInfo;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.persistence.PersistenceException;

import org.openecomp.policy.common.logging.ECOMPLoggingContext;
import org.openecomp.policy.common.logging.ECOMPLoggingUtils;
import org.openecomp.policy.common.logging.eelf.MessageCodes;
import org.openecomp.policy.common.logging.eelf.PolicyLogger;

import org.openecomp.policy.xacml.api.XACMLErrorConstants;
import org.openecomp.policy.xacml.api.pap.ECOMPPapEngineFactory;
import org.openecomp.policy.xacml.api.pap.EcompPDP;
import org.openecomp.policy.xacml.api.pap.EcompPDPGroup;
import org.openecomp.policy.xacml.api.pap.PAPPolicyEngine;

import com.att.research.xacml.api.pap.PAPException;
//import com.att.research.xacml.api.pap.PDP;
//import com.att.research.xacml.api.pap.PDPGroup;
import com.att.research.xacml.api.pap.PDPPolicy;
import com.att.research.xacml.api.pap.PDPStatus;
import org.openecomp.policy.xacml.std.pap.StdPAPPolicy;
import org.openecomp.policy.xacml.std.pap.StdPDP;
import org.openecomp.policy.xacml.std.pap.StdPDPGroup;
import org.openecomp.policy.xacml.std.pap.StdPDPPolicy;
import org.openecomp.policy.xacml.std.pap.StdPDPStatus;
import org.openecomp.policy.xacml.std.pap.StdPDPItemSetChangeNotifier.StdItemSetChangeListener;
import org.openecomp.policy.xacml.util.XACMLPolicyScanner;

import com.att.research.xacml.util.FactoryException;
import com.att.research.xacml.util.XACMLProperties;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import org.openecomp.policy.common.im.AdministrativeStateException;
import org.openecomp.policy.common.im.ForwardProgressException;

//IntegrityMontitor
import org.openecomp.policy.common.im.IntegrityMonitor;
import org.openecomp.policy.common.im.IntegrityMonitorProperties;
import org.openecomp.policy.common.im.StandbyStatusException;
//IntegrityAudit
import org.openecomp.policy.common.ia.IntegrityAudit;
import org.openecomp.policy.common.logging.flexlogger.FlexLogger; 
import org.openecomp.policy.common.logging.flexlogger.Logger;


/**
 * Servlet implementation class XacmlPapServlet
 * 
 * 
 */
@WebServlet(
		description = "Implements the XACML PAP RESTful API.", 
		urlPatterns = { "/" }, 
		loadOnStartup=1,
		initParams = {
				@WebInitParam(name = "XACML_PROPERTIES_NAME", value = "xacml.pap.properties", description = "The location of the properties file holding configuration information.")
		})

public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeListener, Runnable {
	private static final long serialVersionUID = 1L;
	private static final Logger logger	= FlexLogger.getLogger(XACMLPapServlet.class);

	private static String CONFIG_HOME = getConfigHome();
	private static String ACTION_HOME = getActionHome();

	// audit (transaction) logger
	private static final Logger auditLogger = FlexLogger.getLogger("auditLogger");

	private IntegrityMonitor im;
	private IntegrityAudit ia;

	/*
	 * 
	 * papEngine - This is our engine workhorse that manages the PDP Groups and Nodes.
	 */
	private PAPPolicyEngine papEngine = null;
	/*
	 * This PAP instance's own URL.
	 * 
	 * Need this when creating URLs to send to the PDPs so they can GET the Policy files from this process. 
	 */
	private static String papURL = null;

	/*
	 * These are the parameters needed for DB access from the PAP
	 */
	public static String papDbDriver = null;
	public static String papDbUrl = null;
	public static String papDbUser = null;
	public static String papDbPassword = null;
	private static Integer papTransWait = null;
	private static Integer papTransTimeout = null;
	private static Integer papAuditTimeout = null;
	private static Boolean papAuditFlag = null;
	private static Boolean papFileSystemAudit = null;
	private static Boolean autoPushFlag = false;
	private static String papResourceName = null;
	private static Integer fpMonitorInterval = null; 
	private static Integer failedCounterThreshold = null;
	private static Integer testTransInterval = null;
	private static Integer writeFpcInterval = null;
	private static String papSiteName=null;
	private static String papNodeType=null;	
	private static String papDependencyGroups = null;
	private String storedRequestId = null;
	private static int papIntegrityAuditPeriodSeconds = -1;
	private static String[] papDependencyGroupsFlatArray = null;

	//The entity manager factory for JPA access
	private EntityManagerFactory emf;

	//Persistence Unit for JPA 
	private static final String PERSISTENCE_UNIT = "XACML-PAP-REST";
	private static final String AUDIT_PAP_PERSISTENCE_UNIT = "auditPapPU";


	/*
	 * List of Admin Console URLs.
	 * Used to send notifications when configuration changes.
	 * 
	 * The CopyOnWriteArrayList *should* protect from concurrency errors.
	 * This list is seldom changed but often read, so the costs of this approach make sense.
	 */
	private static final CopyOnWriteArrayList<String> adminConsoleURLStringList = new CopyOnWriteArrayList<String>();

	// Mike M 11/24 Client Headers. 
	private static final String ENVIRONMENT_HEADER = "Environment";
	private static String environment = null;

	/*
	 * This thread may be invoked upon startup to initiate sending PDP policy/pip configuration when
	 * this servlet starts. Its configurable by the admin.
	 */
	private Thread initiateThread = null;

	/*
	// The heartbeat thread.
	 */
	private static Heartbeat heartbeat = null;
	private static Thread heartbeatThread = null;

	private ECOMPLoggingContext baseLoggingContext = null;

	private PolicyDBDao policyDBDao;
	private AutoPushPolicy autoPushPolicy;
	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public XACMLPapServlet() {
		super();
	}
	/*
	 * PDP FIle
	 */
	private static String pdpFile = null;
	public static String getPDPFile(){
		return XACMLPapServlet.pdpFile;
	}

	/**
	 * @see Servlet#init(ServletConfig)
	 */
	public void init(ServletConfig config) throws ServletException {


		try {
			//
			// Logging stuff....
			//
			baseLoggingContext = new ECOMPLoggingContext();
			// fixed data that will be the same in all logging output goes here
			try {
				String hostname = InetAddress.getLocalHost().getCanonicalHostName();
				baseLoggingContext.setServer(hostname);
			} catch (UnknownHostException e) {
				logger.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get hostname for logging");
			}

			//
			// Initialize
			//
			XACMLRest.xacmlInit(config);
			//
			// Load the properties
			//
			XACMLRest.loadXacmlProperties(null, null);

			/*
			 * Retrieve the property values for db access and audits from the xacml.pap.properties
			 */
			//Null string occurs when a property is not present
			try{
				papDbDriver = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_DRIVER);
				if(papDbDriver == null){
					throw new PAPException("papDbDriver is null");
				}
			}
			catch(Exception e){
				PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR: Bad property entry");
				throw e;
			}
			try{
				papDbUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_URL);
				if(papDbUrl == null){
					throw new PAPException("papDbUrl is null");
				}
			} catch(Exception e){
				PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR: Bad property entry");
				throw e;
			}
			try{
				papDbUser = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_USER);
				if(papDbUser == null){
					throw new PAPException("papDbUser is null");
				}
			}catch(Exception e){
				PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR: Bad property entry");
				throw e;
			}
			try{
				papDbPassword = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_PASSWORD);
				if(papDbPassword == null){
					throw new PAPException("papDbPassword is null");
				}
			}catch(Exception e){
				PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR: Bad property entry");
				throw e;
			}

			environment = XACMLProperties.getProperty("ENVIRONMENT", "DEVL");

			//Integer will throw an exception of anything is missing or unrecognized
			papTransWait = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT));
			papTransTimeout = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT));
			papAuditTimeout = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_TIMEOUT));

			//Boolean will default to false if anything is missing or unrecognized
			papAuditFlag = Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_RUN_AUDIT_FLAG));
			papFileSystemAudit = Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_FLAG));

			//PAP Auto Push 
			autoPushFlag = Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PUSH_FLAG));
			// if Auto push then Load with properties. 
			if(autoPushFlag){
				String file;
				try{
					file = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PUSH_FILE);
					if(file.endsWith(".properties")){
						autoPushPolicy = new AutoPushPolicy(file);
					}else{
						throw new Exception();
					}
				}catch(Exception e){
					PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Missing property or not a proper property file check for: " + XACMLRestProperties.PROP_PAP_PUSH_FILE );  
					logger.info("Overriding the autoPushFlag to False...");
					autoPushFlag = false;
				}
			}

			try{
				papResourceName = XACMLProperties.getProperty(XACMLRestProperties.PAP_RESOURCE_NAME);
				if(papResourceName == null){
					throw new PAPException("papResourceName is null");
				}
			}catch(Exception e){
				PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR: Bad property entry");
				throw e;
			}

			try{
				papSiteName = XACMLProperties.getProperty(XACMLRestProperties.PAP_SITE_NAME);
				if(papSiteName == null){
					throw new PAPException("papSiteName is null");
				}
			}catch(Exception e){
				PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR: Bad property entry");
				throw e;
			}
			try{
				papNodeType = XACMLProperties.getProperty(XACMLRestProperties.PAP_NODE_TYPE);
				if(papNodeType == null){
					throw new PAPException("papNodeType is null");
				}
			}catch(Exception e){
				PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR: Bad property entry");
				throw e;
			}
			try{
				papDependencyGroups = XACMLProperties.getProperty(XACMLRestProperties.PAP_DEPENDENCY_GROUPS);
				if(papDependencyGroups == null){
					throw new PAPException("papDependencyGroups is null");
				}
				//Now we have flattened the array into a simple comma-separated list
				papDependencyGroupsFlatArray = papDependencyGroups.split("[;,]");

				//clean up the entries
				for (int i = 0 ; i < papDependencyGroupsFlatArray.length ; i ++){
					papDependencyGroupsFlatArray[i] = papDependencyGroupsFlatArray[i].trim();
				}
				try{
					if(XACMLProperties.getProperty(XACMLRestProperties.PAP_INTEGRITY_AUDIT_PERIOD_SECONDS) != null){
						papIntegrityAuditPeriodSeconds = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PAP_INTEGRITY_AUDIT_PERIOD_SECONDS).trim());
					}else{
						//nothing to do.  The parameter is optional
					}
				}catch(Exception e){
					String msg = "integrity_audit_period_seconds ";
					logger.error("\n\nERROR: " + msg + "Bad property entry: " + e.getMessage() + "\n");
					PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR: " + msg +"Bad property entry");
					throw e;
				}
			}catch(Exception e){
				PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR: Bad property entry");
				throw e;
			}

			//Integer will throw an exception of anything is missing or unrecognized
			fpMonitorInterval = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.FP_MONITOR_INTERVAL));
			failedCounterThreshold = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.FAILED_COUNTER_THRESHOLD));
			testTransInterval = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.TEST_TRANS_INTERVAL));
			writeFpcInterval = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.WRITE_FPC_INTERVAL));

			logger.debug("\n\n\n**************************************"
					+ "\n**************************************"
					+ "\n"
					+ "\n   papDbDriver = " + papDbDriver
					+ "\n   papDbUrl = " + papDbUrl
					+ "\n   papDbUser = " + papDbUser
					+ "\n   papDbPassword = " + papDbPassword
					+ "\n   papTransWait = " + papTransWait
					+ "\n   papTransTimeout = " + papTransTimeout
					+ "\n   papAuditTimeout = " + papAuditTimeout
					+ "\n   papAuditFlag = " + papAuditFlag
					+ "\n   papFileSystemAudit = " + papFileSystemAudit
					+ "\n	autoPushFlag = " + autoPushFlag
					+ "\n	papResourceName = " + papResourceName
					+ "\n	fpMonitorInterval = " + fpMonitorInterval
					+ "\n	failedCounterThreshold = " + failedCounterThreshold
					+ "\n	testTransInterval = " + testTransInterval
					+ "\n	writeFpcInterval = " + writeFpcInterval
					+ "\n	papSiteName = " + papSiteName
					+ "\n	papNodeType = " + papNodeType
					+ "\n	papDependencyGroupsList = " + papDependencyGroups
					+ "\n   papIntegrityAuditPeriodSeconds = " + papIntegrityAuditPeriodSeconds
					+ "\n\n**************************************"
					+ "\n**************************************");

			//
			// Pull custom persistence settings
			//

			Properties properties;
			try {
				properties = XACMLProperties.getProperties();//XACMLRestProperties.getProperties();
				logger.debug("\n\n\n**************************************"
						+ "\n**************************************"
						+ "\n\n"
						+ "properties = " + properties
						+ "\n\n**************************************");

			} catch (IOException e) {
				PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPapServlet", " Error loading properties with: "
						+ "XACMLProperties.getProperties()");
				throw new ServletException(e.getMessage(), e.getCause());
			}

			// Create an IntegrityMonitor
			im = IntegrityMonitor.getInstance(papResourceName,properties);

			// Create an IntegrityAudit
			ia = new IntegrityAudit(papResourceName, AUDIT_PAP_PERSISTENCE_UNIT, properties);
			ia.startAuditThread();

			//
			// Create the entity manager factory
			//
			emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT, properties);
			//
			// Did it get created?
			//
			if (emf == null) {
				PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Error creating entity manager factory with persistence unit: "
						+ PERSISTENCE_UNIT);
				throw new ServletException("Unable to create Entity Manager Factory");
			}
			//
			// we are about to call the PDPs and give them their configuration.
			// To do that we need to have the URL of this PAP so we can construct the Policy file URLs
			//
			XACMLPapServlet.papURL = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL);
			/*
			 * Create the PolicyDBDao singleton
			 */		
			//Create the policyDBDao
			policyDBDao = PolicyDBDao.getPolicyDBDaoInstance(getEmf());
			boolean performFileToDatabaseAudit = false;
			if (Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_RUN_AUDIT_FLAG))){
				if (Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_FLAG))){
					//get an AuditTransaction to lock out all other transactions
					PolicyDBDaoTransaction auditTrans = policyDBDao.getNewAuditTransaction();
					policyDBDao.auditLocalFileSystem();
					//release the transaction lock
					auditTrans.close();
				}else{
					performFileToDatabaseAudit = true;					
				}
			}



			//
			// Load our PAP engine, first create a factory
			//
			ECOMPPapEngineFactory factory = ECOMPPapEngineFactory.newInstance(XACMLProperties.getProperty(XACMLProperties.PROP_PAP_PAPENGINEFACTORY));
			//
			// The factory knows how to go about creating a PAP Engine
			//
			this.papEngine = (PAPPolicyEngine) factory.newEngine();
			PolicyDBDaoTransaction addNewGroup = null;
			try{

				if(((org.openecomp.policy.xacml.std.pap.StdEngine)papEngine).wasDefaultGroupJustAdded){
					addNewGroup = policyDBDao.getNewTransaction();
					EcompPDPGroup group = papEngine.getDefaultGroup();
					addNewGroup.createGroup(group.getId(), group.getName(), group.getDescription(), "automaticallyAdded");
					addNewGroup.commitTransaction();
					addNewGroup = policyDBDao.getNewTransaction();					
					addNewGroup.changeDefaultGroup(group, "automaticallyAdded");
					addNewGroup.commitTransaction();				
				}

			} catch(Exception e){
				PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " Error creating new default group in the database");
				if(addNewGroup != null){
					addNewGroup.rollbackTransaction();
				}
			}

			policyDBDao.setPapEngine((PAPPolicyEngine) this.papEngine);


			if(performFileToDatabaseAudit){
				//get an AuditTransaction to lock out all other transactions
				PolicyDBDaoTransaction auditTrans = policyDBDao.getNewAuditTransaction();
				policyDBDao.auditLocalDatabase((PAPPolicyEngine) this.papEngine);
				//release the transaction lock
				auditTrans.close();
			}

			//
			// PDPId File location 
			//
			XACMLPapServlet.pdpFile = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_IDFILE);
			if (XACMLPapServlet.pdpFile == null) {
				PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + 
						" The PDP Id Authentication File Property is not valid: "
						+ XACMLRestProperties.PROP_PDP_IDFILE);
				throw new PAPException("The PDP Id Authentication File Property :"+ XACMLRestProperties.PROP_PDP_IDFILE+ " is not Valid. ");
			}
			//
			// Sanity check that a URL was defined somewhere, its essential.
			//
			// How to check that its valid? We can validate the form, but since we are in the init() method we
			// are not fully loaded yet so we really couldn't ping ourself to see if the URL will work. One
			// will have to look for errors in the PDP logs to determine if they are failing to initiate a
			// request to this servlet.
			//
			if (XACMLPapServlet.papURL == null) {

				throw new PAPException("The property " + XACMLRestProperties.PROP_PAP_URL + " is not valid: " + XACMLPapServlet.papURL);
			}
			//
			// Configurable - have the PAP servlet initiate sending the latest PDP policy/pip configuration
			// to all its known PDP nodes.
			//
			// Note: parseBoolean will return false if there is no property defined. This is fine for a default.
			//
			if (Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_INITIATE_PDP_CONFIG))) {
				this.initiateThread = new Thread(this);
				this.initiateThread.start();
			}
			//
			// After startup, the PAP does Heartbeats to each of the PDPs periodically
			//
			XACMLPapServlet.heartbeat = new Heartbeat((PAPPolicyEngine) this.papEngine);
			XACMLPapServlet.heartbeatThread = new Thread(XACMLPapServlet.heartbeat);
			XACMLPapServlet.heartbeatThread.start();
		} catch (FactoryException | PAPException e) {
			PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to create engine");
			throw new ServletException (XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP not initialized; error: "+e);
		} catch (Exception e) {
			PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to create engine - unexpected error");
			throw new ServletException (XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP not initialized; unexpected error: "+e);		}
	}

	/**
	 * Thread used only during PAP startup to initiate change messages to all known PDPs.
	 * This must be on a separate thread so that any GET requests from the PDPs during this update can be serviced.
	 */
	@Override
	public void run() {
		//
		// send the current configuration to all the PDPs that we know about
		//
		changed();
	}


	/**
	 * @see Servlet#destroy()
	 * 
	 * Depending on how this servlet is run, we may or may not care about cleaning up the resources.
	 * For now we assume that we do care.
	 */
	public void destroy() {
		//
		// Make sure our threads are destroyed
		//
		if (XACMLPapServlet.heartbeatThread != null) {
			//
			// stop the heartbeat
			//
			try {
				if (XACMLPapServlet.heartbeat != null) {
					XACMLPapServlet.heartbeat.terminate();
				}
				XACMLPapServlet.heartbeatThread.interrupt();
				XACMLPapServlet.heartbeatThread.join();
			} catch (InterruptedException e) {
				PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Error stopping heartbeat");
			}
		}
		if (this.initiateThread != null) {
			try {
				this.initiateThread.interrupt();
				this.initiateThread.join();
			} catch (InterruptedException e) {
				PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Error stopping thread");
			}
		}
	}

	/**
	 * 
	 * Called by:
	 * 	- PDP nodes to register themselves with the PAP, and
	 * 	- Admin Console to make changes in the PDP Groups.
	 * 
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ECOMPLoggingContext loggingContext = ECOMPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);

		loggingContext.transactionStarted();
		loggingContext.setServiceName("PAP.post"); // we may set a more specific value later
		if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
			UUID requestID = UUID.randomUUID();
			loggingContext.setRequestID(requestID.toString());
			PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doPost) so we generated one");
		} else {
			PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doPost)");
		}
		// dummy metric.log example posted below as proof of concept
		loggingContext.metricStarted();
		loggingContext.metricEnded();
		PolicyLogger.metrics("Metric example posted here - 1 of 2");
		loggingContext.metricStarted();
		loggingContext.metricEnded();
		PolicyLogger.metrics("Metric example posted here - 2 of 2");
		// dummy metric.log example posted above as proof of concept
		PolicyDBDaoTransaction pdpTransaction = null;

		//This im.startTransaction() covers all Post transactions
		try {
			im.startTransaction();
		} catch (AdministrativeStateException ae){
			String message = "POST interface called for PAP " + papResourceName + " but it has an Administrative"
					+ " state of " + im.getStateManager().getAdminState()
					+ "\n Exception Message: " + ae.getMessage();
			logger.info(message);
			PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
			loggingContext.transactionEnded();

			PolicyLogger.audit("Transaction Failed - See Error.log");

			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
			return;
		}catch (StandbyStatusException se) {
			se.printStackTrace();
			String message = "POST interface called for PAP " + papResourceName + " but it has a Standby Status"
					+ " of " + im.getStateManager().getStandbyStatus()
					+ "\n Exception Message: " + se.getMessage();
			logger.info(message);
			PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
			loggingContext.transactionEnded();

			PolicyLogger.audit("Transaction Failed - See Error.log");

			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
			return;
		}

		try {

			XACMLRest.dumpRequest(request);

			// since getParameter reads the content string, explicitly get the content before doing that.
			// Simply getting the inputStream seems to protect it against being consumed by getParameter.
			request.getInputStream();


			String groupId = request.getParameter("groupId");
			String apiflag = request.getParameter("apiflag");

			if (groupId != null) {
				// Is this from the Admin Console or API?
				if(apiflag!=null) {
					if (apiflag.equalsIgnoreCase("api")) {
						// this is from the API so we need to check the client credentials before processing the request
						if(authorizeRequest(request)){
							doACPost(request, response, groupId, loggingContext);
							// Mike B - ended loggingContext transacton & added EELF 'Success' EELF Audit.log message
							loggingContext.transactionEnded();
							PolicyLogger.audit("Transaction Ended Successfully");
							im.endTransaction();
							return;
						} else {
							String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
							PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
							loggingContext.transactionEnded();

							PolicyLogger.audit("Transaction Failed - See Error.log");

							response.sendError(HttpServletResponse.SC_FORBIDDEN, message);
							im.endTransaction();
							return;
						}
					}
				}

				// this is from the Admin Console, so handle separately
				doACPost(request, response, groupId, loggingContext);
				loggingContext.transactionEnded();
				PolicyLogger.audit("Transaction Ended Successfully");
				im.endTransaction();
				return;

			}


			//
			//  Request is from a PDP.
			//	It is coming up and asking for its config
			//
			loggingContext.setServiceName("PDP:PAP.register");


			//
			// Get the PDP's ID
			//
			String id = this.getPDPID(request);
			String jmxport = this.getPDPJMX(request);
			//logger.info("doPost from: " + id);
			logger.info("Request(doPost) from PDP coming up: " + id);
			//
			// Get the PDP Object
			//
			EcompPDP pdp = this.papEngine.getPDP(id);
			//
			// Is it known?
			//
			if (pdp == null) {
				logger.info("Unknown PDP: " + id);
				// PDP ID Check is performed Here. 
				if(CheckPDP.validateID(id)){
					pdpTransaction = policyDBDao.getNewTransaction();
					try {
						//this.papEngine.newPDP(id, this.papEngine.getDefaultGroup(), id, "Registered on first startup");
						pdpTransaction.addPdpToGroup(id, this.papEngine.getDefaultGroup().getId(), id, "Registered on first startup", Integer.parseInt(jmxport), "PDP autoregister");
						this.papEngine.newPDP(id, this.papEngine.getDefaultGroup(), id, "Registered on first startup", Integer.parseInt(jmxport));
					} catch (NullPointerException | PAPException | IllegalArgumentException | IllegalStateException | PersistenceException e) {
						pdpTransaction.rollbackTransaction();
						String message = "Failed to create new PDP for id: " + id;
						PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " " + message);
						loggingContext.transactionEnded();

						PolicyLogger.audit("Transaction Failed - See Error.log");

						PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " " + message);
						response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
						im.endTransaction();
						return;
					}
					// get the PDP we just created
					pdp = this.papEngine.getPDP(id);
					if (pdp == null) {
						if(pdpTransaction != null){
							pdpTransaction.rollbackTransaction();
						}
						String message = "Failed to create new PDP for id: " + id;
						PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " " + message);
						loggingContext.transactionEnded();

						PolicyLogger.audit("Transaction Failed - See Error.log");
						response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
						im.endTransaction();
						return;
					}
				} else {
					String message = "PDP is Unauthorized to Connect to PAP: "+ id;
					PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
					loggingContext.transactionEnded();
					response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "PDP not Authorized to connect to this PAP. Please contact the PAP Admin for registration.");
					PolicyLogger.audit("Transaction Failed - See Error.log");
					im.endTransaction();
					return;
				}
				// get the PDP we just created
				pdp = this.papEngine.getPDP(id);
				if (pdp == null) {
					if(pdpTransaction != null){
						pdpTransaction.rollbackTransaction();
					}
					String message = "Failed to create new PDP for id: " + id;
					PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
					loggingContext.transactionEnded();
					PolicyLogger.audit("Transaction Failed - See Error.log");
					response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
					im.endTransaction();
					return;
				}
				try{
					pdpTransaction.commitTransaction();
				} catch(Exception e){
					PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", "Could not commit transaction to put pdp in the database");
				}
			}

			if (jmxport != null && jmxport != ""){
				((StdPDP) pdp).setJmxPort(Integer.valueOf(jmxport));
			}

			//
			// Get the PDP's Group
			//
			EcompPDPGroup group = this.papEngine.getPDPGroup((EcompPDP) pdp);
			if (group == null) {
				PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " PDP not associated with any group, even the default");
				loggingContext.transactionEnded();
				PolicyLogger.audit("Transaction Failed - See Error.log");
				response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "PDP not associated with any group, even the default");
				im.endTransaction();
				return;
			}
			//
			// Determine what group the PDP node is in and get
			// its policy/pip properties.
			//
			Properties policies = group.getPolicyProperties();
			Properties pipconfig = group.getPipConfigProperties();
			//
			// Get the current policy/pip configuration that the PDP has
			//
			Properties pdpProperties = new Properties();
			pdpProperties.load(request.getInputStream());
			logger.info("PDP Current Properties: " + pdpProperties.toString());
			logger.info("Policies: " + (policies != null ? policies.toString() : "null"));
			logger.info("Pip config: " + (pipconfig != null ? pipconfig.toString() : "null"));
			//
			// Validate the node's properties
			//
			boolean isCurrent = this.isPDPCurrent(policies, pipconfig, pdpProperties);
			//
			// Send back current configuration
			//
			if (isCurrent == false) {
				//
				// Tell the PDP we are sending back the current policies/pip config
				//
				logger.info("PDP configuration NOT current.");
				if (policies != null) {
					//
					// Put URL's into the properties in case the PDP needs to
					// retrieve them.
					//
					this.populatePolicyURL(request.getRequestURL(), policies);
					//
					// Copy the properties to the output stream
					//
					policies.store(response.getOutputStream(), "");
				}
				if (pipconfig != null) {
					//
					// Copy the properties to the output stream
					//
					pipconfig.store(response.getOutputStream(), "");
				}
				//
				// We are good - and we are sending them information
				//
				response.setStatus(HttpServletResponse.SC_OK);

				setPDPSummaryStatus(pdp, PDPStatus.Status.OUT_OF_SYNCH);
			} else {
				//
				// Tell them they are good
				//
				response.setStatus(HttpServletResponse.SC_NO_CONTENT);

				setPDPSummaryStatus(pdp, PDPStatus.Status.UP_TO_DATE);

			}
			//
			// tell the AC that something changed
			//
			notifyAC();
			loggingContext.transactionEnded();
			auditLogger.info("Success");
			PolicyLogger.audit("Transaction Ended Successfully");
		} catch (PAPException e) {
			if(pdpTransaction != null){
				pdpTransaction.rollbackTransaction();
			}
			logger.debug(XACMLErrorConstants.ERROR_PROCESS_FLOW + "POST exception: " + e, e);
			loggingContext.transactionEnded();

			PolicyLogger.audit("Transaction Failed - See Error.log");

			response.sendError(500, e.getMessage());
			im.endTransaction();
			return;
		}
		//Catch anything that fell through
		loggingContext.transactionEnded();
		PolicyLogger.audit("Transaction Ended");
		im.endTransaction();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ECOMPLoggingContext loggingContext = ECOMPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
		loggingContext.transactionStarted();
		loggingContext.setServiceName("PAP.get"); // we may set a more specific value later
		if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
			UUID requestID = UUID.randomUUID();
			loggingContext.setRequestID(requestID.toString());
			PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doGet) so we generated one");
		} else {
			PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doGet)");
		}
		// dummy metric.log example posted below as proof of concept
		loggingContext.metricStarted();
		loggingContext.metricEnded();
		PolicyLogger.metrics("Metric example posted here - 1 of 2");
		loggingContext.metricStarted();
		loggingContext.metricEnded();
		PolicyLogger.metrics("Metric example posted here - 2 of 2");
		// dummy metric.log example posted above as proof of concept
		try {
			XACMLRest.dumpRequest(request);
			String pathInfo = request.getRequestURI();
			logger.info("path info: " + pathInfo);
			if (pathInfo != null){
				//DO NOT do a im.startTransaction for the test request
				if (pathInfo.equals("/pap/test")) {
					logger.info("Test request received");
					try {
						im.evaluateSanity();
						//If we make it this far, all is well
						String message = "GET:/pap/test called and PAP " + papResourceName + " is OK";
						logger.info(message);
						loggingContext.transactionEnded();
						PolicyLogger.audit("Transaction Failed - See Error.log");
						response.setStatus(HttpServletResponse.SC_OK);
						return;
					}catch (ForwardProgressException fpe){
						//No forward progress is being made
						String message = "GET:/pap/test called and PAP " + papResourceName + " is not making forward progress."
								+ " Exception Message: " + fpe.getMessage();
						logger.info(message);
						PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
						loggingContext.transactionEnded();

						PolicyLogger.audit("Transaction Failed - See Error.log");
						response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
						return;
					}catch (AdministrativeStateException ase){
						//Administrative State is locked
						String message = "GET:/pap/test called and PAP " + papResourceName + " Administrative State is LOCKED "
								+ " Exception Message: " + ase.getMessage();
						logger.info(message);
						PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
						loggingContext.transactionEnded();

						PolicyLogger.audit("Transaction Failed - See Error.log");
						response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
						return;
					}catch (StandbyStatusException sse){
						//Administrative State is locked
						String message = "GET:/pap/test called and PAP " + papResourceName + " Standby Status is NOT PROVIDING SERVICE "
								+ " Exception Message: " + sse.getMessage();
						logger.info(message);
						PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
						loggingContext.transactionEnded();

						PolicyLogger.audit("Transaction Failed - See Error.log");
						response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
						return;
					}catch (Exception e) {
						//A subsystem is not making progress, is locked, standby or is not responding
						String eMsg = e.getMessage();
						if(eMsg == null){
							eMsg = "No Exception Message";
						}
						String message = "GET:/pap/test called and PAP " + papResourceName + " has had a subsystem failure."
								+ " Exception Message: " + eMsg;
						logger.info(message);
						PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
						loggingContext.transactionEnded();

						PolicyLogger.audit("Transaction Failed - See Error.log");
						//Get the specific list of subsystems that failed
						String ssFailureList = null;
						for(String failedSS : papDependencyGroupsFlatArray){
							if(eMsg.contains(failedSS)){
								if(ssFailureList == null){
									ssFailureList = failedSS;
								}else{
									ssFailureList = ssFailureList.concat(","+failedSS);
								}
							}
						}
						if(ssFailureList == null){
							ssFailureList = "UnknownSubSystem";
						}
						response.addHeader("X-ECOMP-SubsystemFailure", ssFailureList);
						response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
						return;
					}
				}
			}

			//This im.startTransaction() covers all other Get transactions
			try {
				im.startTransaction();
			} catch (AdministrativeStateException ae){
				String message = "GET interface called for PAP " + papResourceName + " but it has an Administrative"
						+ " state of " + im.getStateManager().getAdminState()
						+ "\n Exception Message: " + ae.getMessage();
				logger.info(message);
				PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
				loggingContext.transactionEnded();

				PolicyLogger.audit("Transaction Failed - See Error.log");
				response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
				return;
			}catch (StandbyStatusException se) {
				se.printStackTrace();
				String message = "GET interface called for PAP " + papResourceName + " but it has a Standby Status"
						+ " of " + im.getStateManager().getStandbyStatus()
						+ "\n Exception Message: " + se.getMessage();
				logger.info(message);
				PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
				loggingContext.transactionEnded();

				PolicyLogger.audit("Transaction Failed - See Error.log");
				response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
				return;
			}


			// Request from the API to get the gitPath
			String apiflag = request.getParameter("apiflag");
			if (apiflag!=null) {
				if(authorizeRequest(request)){


					// Request from the API to get the gitPath
					if (apiflag.equalsIgnoreCase("gitPath")) {
						getGitPath(request, response);
						// Mike B - ended loggingContext transacton & added EELF 'Success' EELF Audit.log message
						loggingContext.transactionEnded();
						PolicyLogger.audit("Transaction Ended Successfully");
						im.endTransaction();
						return;
					}

					// Request from the API to get the ActiveVersion from the PolicyVersion table
					if (apiflag.equalsIgnoreCase("version")){
						getActiveVersion(request, response);
						loggingContext.transactionEnded();
						PolicyLogger.audit("Transaction Ended Successfully");
						im.endTransaction();
						return;
					}

					// Request from the API to get the URI from the gitpath
					if (apiflag.equalsIgnoreCase("uri")){
						getSelectedURI(request, response);
						loggingContext.transactionEnded();
						PolicyLogger.audit("Transaction Ended Successfully");
						im.endTransaction();
						return;
					}

				} else {
					String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
					PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
					loggingContext.transactionEnded();

					PolicyLogger.audit("Transaction Failed - See Error.log");
					response.sendError(HttpServletResponse.SC_FORBIDDEN, message);
					im.endTransaction();
					return;
				}

			}


			// Is this from the Admin Console?
			String groupId = request.getParameter("groupId");
			if (groupId != null) {
				// this is from the Admin Console, so handle separately
				doACGet(request, response, groupId, loggingContext);
				loggingContext.transactionEnded();
				PolicyLogger.audit("Transaction Ended Successfully");
				im.endTransaction();
				return;
			}

			//
			// Get the PDP's ID
			//
			String id = this.getPDPID(request);
			logger.info("doGet from: " + id);
			//
			// Get the PDP Object
			//
			EcompPDP pdp = this.papEngine.getPDP(id);
			//
			// Is it known?
			//
			if (pdp == null) {
				//
				// Check if request came from localhost
				//
				if (request.getRemoteHost().equals("localhost") ||
						request.getRemoteHost().equals("127.0.0.1") ||
						request.getRemoteHost().equals(request.getLocalAddr())) {
					//
					// Return status information - basically all the groups
					//
					loggingContext.setServiceName("PAP.getGroups");
					Set<EcompPDPGroup> groups = papEngine.getEcompPDPGroups();

					// convert response object to JSON and include in the response
					ObjectMapper mapper = new ObjectMapper();
					mapper.writeValue(response.getOutputStream(),  groups);
					response.setHeader("content-type", "application/json");
					response.setStatus(HttpServletResponse.SC_OK);
					loggingContext.transactionEnded();
					PolicyLogger.audit("Transaction Ended Successfully");
					im.endTransaction();
					return;
				}
				String message = "Unknown PDP: " + id + " from " + request.getRemoteHost() + " us: " + request.getLocalAddr();
				PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
				loggingContext.transactionEnded();

				PolicyLogger.audit("Transaction Failed - See Error.log");
				response.sendError(HttpServletResponse.SC_UNAUTHORIZED, message);
				im.endTransaction();
				return;
			}

			loggingContext.setServiceName("PAP.getPolicy");

			//
			// Get the PDP's Group
			//
			EcompPDPGroup group = this.papEngine.getPDPGroup((EcompPDP) pdp);
			if (group == null) {
				String message = "No group associated with pdp " + pdp.getId();
				logger.warn(XACMLErrorConstants.ERROR_PERMISSIONS + message);
				loggingContext.transactionEnded();

				PolicyLogger.audit("Transaction Failed - See Error.log");
				response.sendError(HttpServletResponse.SC_UNAUTHORIZED, message);
				im.endTransaction();
				return;
			}
			//
			// Which policy do they want?
			//
			String policyId = request.getParameter("id");
			if (policyId == null) {
				String message = "Did not specify an id for the policy";
				logger.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
				loggingContext.transactionEnded();

				PolicyLogger.audit("Transaction Failed - See Error.log");
				response.sendError(HttpServletResponse.SC_NOT_FOUND, message);
				im.endTransaction();
				return;
			}
			PDPPolicy policy = group.getPolicy(policyId);
			if (policy == null) {
				String message = "Unknown policy: " + policyId;
				logger.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
				loggingContext.transactionEnded();

				PolicyLogger.audit("Transaction Failed - See Error.log");
				response.sendError(HttpServletResponse.SC_NOT_FOUND, message);
				im.endTransaction();
				return;
			}
			//
			// Get its stream
			//
			logger.warn("PolicyDebugging: Policy Validity: " + policy.isValid() + "\n "
					+ "Policy Name : " + policy.getName() + "\n Policy URI: " + policy.getLocation().toString() );
			try (InputStream is = policy.getStream(); OutputStream os = response.getOutputStream()) {
				//
				// Send the policy back
				//
				IOUtils.copy(is, os);

				response.setStatus(HttpServletResponse.SC_OK);
				loggingContext.transactionEnded();
				auditLogger.info("Success");
				PolicyLogger.audit("Transaction Ended Successfully");
			} catch (PAPException e) {
				String message = "Failed to open policy id " + policyId;
				PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
				loggingContext.transactionEnded();
				PolicyLogger.audit("Transaction Failed - See Error.log");
				response.sendError(HttpServletResponse.SC_NOT_FOUND, message);
			}
		}  catch (PAPException e) {
			PolicyLogger.error(MessageCodes.ERROR_UNKNOWN, e, "XACMLPapServlet", " GET exception");
			loggingContext.transactionEnded();

			PolicyLogger.audit("Transaction Failed - See Error.log");
			response.sendError(500, e.getMessage());
			im.endTransaction();
			return;
		}
		loggingContext.transactionEnded();
		PolicyLogger.audit("Transaction Ended");
		im.endTransaction();
	}


	/**
	 * Requests from the PolicyEngine API to update the PDP Group with pushed policy
	 * 
	 * @param request
	 * @param response
	 * @param groupId
	 * @param loggingContext 
	 * @throws ServletException
	 * @throws IOException
	 */
	private void updateGroupsFromAPI(HttpServletRequest request, HttpServletResponse response, String groupId, ECOMPLoggingContext loggingContext) throws IOException {
		PolicyDBDaoTransaction acPutTransaction = policyDBDao.getNewTransaction();
		try {


			// for PUT operations the group may or may not need to exist before the operation can be done
			StdPDPGroup group = (StdPDPGroup) papEngine.getGroup(groupId);

			// get the request content into a String
			String json = null;

			// read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
			java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
			scanner.useDelimiter("\\A");
			json =  scanner.hasNext() ? scanner.next() : "";
			scanner.close();
			logger.info("JSON request from PolicyEngine API: " + json);

			// convert Object sent as JSON into local object
			ObjectMapper mapper = new ObjectMapper();

			Object objectFromJSON = mapper.readValue(json, StdPDPPolicy.class);

			StdPDPPolicy policy = (StdPDPPolicy) objectFromJSON;

			Set<PDPPolicy> policies = new HashSet<PDPPolicy>();

			if(policy!=null){
				policies.add(policy);
			}

			//Get the current policies from the Group and Add the new one
			Set<PDPPolicy> currentPoliciesInGroup = new HashSet<PDPPolicy>();
			currentPoliciesInGroup = group.getPolicies();

			//If the selected policy is in the group we must remove it because the name is default
			Iterator<PDPPolicy> policyIterator = policies.iterator();
			logger.debug("policyIterator....." + policies);
			while (policyIterator.hasNext()) {
				PDPPolicy selPolicy = policyIterator.next();
				for (PDPPolicy existingPolicy : currentPoliciesInGroup) {
					if (existingPolicy.getId().equals(selPolicy.getId())) {
						group.removePolicyFromGroup(existingPolicy);
						logger.debug("Removing policy: " + existingPolicy);
						break;
					}
				}
			}

			if(currentPoliciesInGroup!=null){
				policies.addAll(currentPoliciesInGroup);
			}
			group.setPolicies(policies);

			// Assume that this is an update of an existing PDP Group
			loggingContext.setServiceName("PolicyEngineAPI:PAP.updateGroup");

			try{
				acPutTransaction.updateGroup(group, "XACMLPapServlet.doACPut");
			} catch(Exception e){
				PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while updating group in the database: "
						+"group="+group.getId());
				throw new PAPException(e.getMessage());	
			}

			papEngine.updateGroup(group);
			response.setStatus(HttpServletResponse.SC_NO_CONTENT);
			response.addHeader("operation", "push");
			response.addHeader("policyId", policy.getId());
			response.addHeader("groupId", groupId);
			if (logger.isDebugEnabled()) {		
				logger.debug("Group '" + group.getId() + "' updated");
			}

			acPutTransaction.commitTransaction();

			notifyAC();

			// Group changed, which might include changing the policies	
			groupChanged(group);
			loggingContext.transactionEnded();
			auditLogger.info("Success");
			PolicyLogger.audit("Transaction Ended Successfully");
			return;
		} catch (PAPException e) {
			acPutTransaction.rollbackTransaction();
			PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " API PUT exception");
			loggingContext.transactionEnded();

			PolicyLogger.audit("Transaction Failed - See Error.log");

			String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Exception in request to update group from API - See Error.log on on the PAP.";
			response.sendError(500, e.getMessage());
			response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			response.addHeader("error","addGroupError");
			response.addHeader("message", message);
			return;
		}

	}

	private void getActiveVersion(HttpServletRequest request, HttpServletResponse response) {
		//Setup EntityManager to communicate with the PolicyVersion table of the DB
		EntityManager em = null;
		em = (EntityManager) emf.createEntityManager();

		if (em==null){
			PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Error creating entity manager with persistence unit: " + PERSISTENCE_UNIT);
			try {
				throw new Exception("Unable to create Entity Manager Factory");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		String policyScope = request.getParameter("policyScope");
		String filePrefix = request.getParameter("filePrefix");
		String policyName = request.getParameter("policyName");

		String pvName = policyScope + File.separator + filePrefix + policyName;
		int activeVersion = 0;


		//Get the Active Version to use in the ID
		em.getTransaction().begin();
		Query query = em.createQuery("Select p from PolicyVersion p where p.policyName=:pname");
		query.setParameter("pname", pvName);

		@SuppressWarnings("rawtypes")
		List result = query.getResultList();
		PolicyVersion versionEntity = null;
		if (!result.isEmpty()) {
			versionEntity = (PolicyVersion) result.get(0);
			em.persist(versionEntity);
			activeVersion = versionEntity.getActiveVersion();
			em.getTransaction().commit();
		} else {
			logger.debug("No PolicyVersion using policyName found");
		}

		//clean up connection
		em.close();
		if (String.valueOf(activeVersion)!=null || !String.valueOf(activeVersion).equalsIgnoreCase("")) {							
			response.setStatus(HttpServletResponse.SC_OK);								
			response.addHeader("version", String.valueOf(activeVersion));								
		} else {						
			response.setStatus(HttpServletResponse.SC_NOT_FOUND);								
		}	


	}

	private void getSelectedURI(HttpServletRequest request,
			HttpServletResponse response) {

		String gitPath = request.getParameter("gitPath");

		File file = new File(gitPath);

		logger.debug("The fileItem is : " + file.toString());

		URI selectedURI = file.toURI();

		String uri = selectedURI.toString();

		if (!uri.equalsIgnoreCase("")) {							
			response.setStatus(HttpServletResponse.SC_OK);								
			response.addHeader("selectedURI", uri);								
		} else {						
			response.setStatus(HttpServletResponse.SC_NOT_FOUND);								
		}						
	}

	/*
	 * getGitPath() method to get the gitPath using data from the JSON string 
	 * when deleting policies using doAPIDelete()
	 */
	private File getPolicyFile(String policyName){

		Path workspacePath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WORKSPACE), "admin");
		Path repositoryPath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_REPOSITORY));
		Path gitPath = Paths.get(workspacePath.toString(), repositoryPath.getFileName().toString());

		//getting the fullpath of the gitPath and convert to string
		String fullGitPath = gitPath.toAbsolutePath().toString();
		String finalGitPath = null;

		//creating the parentPath directory for the Admin Console use
		if(fullGitPath.contains("\\")){
			finalGitPath = fullGitPath.replace("ECOMP-PAP-REST", "ecomp-sdk-app");
		}else{
			finalGitPath = fullGitPath.replace("pap",  "console");
		}

		finalGitPath += File.separator + policyName;

		File file = new File(finalGitPath);

		return file;

	}

	/*
	 * getGitPath() method to get the gitPath using data from the http request
	 * and send back in response when pushing policies
	 */
	private void getGitPath(HttpServletRequest request,
			HttpServletResponse response) {

		String policyScope = request.getParameter("policyScope");
		String filePrefix = request.getParameter("filePrefix");
		String policyName = request.getParameter("policyName");
		String activeVersion = request.getParameter("activeVersion");

		Path workspacePath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WORKSPACE), "admin");
		Path repositoryPath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_REPOSITORY));
		Path gitPath = Paths.get(workspacePath.toString(), repositoryPath.getFileName().toString());

		//getting the fullpath of the gitPath and convert to string
		String fullGitPath = gitPath.toAbsolutePath().toString();
		String finalGitPath = null;

		//creating the parentPath directory for the Admin Console use
		if(fullGitPath.contains("\\")){
			finalGitPath = fullGitPath.replace("ECOMP-PAP-REST", "ecomp-sdk-app");
		}else{
			finalGitPath = fullGitPath.replace("pap",  "console");
		}

		finalGitPath += File.separator + policyScope + File.separator + filePrefix + policyName + "." + activeVersion + ".xml";
		File file = new File(finalGitPath);
		URI uri = file.toURI();
		
		//
		// Extract XACML policy information
		//
		Boolean isValid = false;
		String policyId = null;
		String description = null;
		String	version = null;

		URL url;
		try {
			url = uri.toURL();
			Object rootElement = XACMLPolicyScanner.readPolicy(url.openStream());
			if (rootElement == null ||
					(
							! (rootElement instanceof PolicySetType) &&
							! (rootElement instanceof PolicyType)
							)	) {
				logger.warn("No root policy element in URI: " + uri.toString() + " : " + rootElement);
				isValid = false;
			} else {
				if (rootElement instanceof PolicySetType) {
					policyId = ((PolicySetType)rootElement).getPolicySetId();
					description = ((PolicySetType)rootElement).getDescription();
					isValid = true;
					version = ((PolicySetType)rootElement).getVersion();
				} else if (rootElement instanceof PolicyType) {
					policyId = ((PolicyType)rootElement).getPolicyId();
					description = ((PolicyType)rootElement).getDescription();
					version = ((PolicyType)rootElement).getVersion();
					isValid = true;
				} else {
					PolicyLogger.error("Unknown root element: " + rootElement.getClass().getCanonicalName());
				}
			}
		} catch (Exception e) {
			logger.error("Exception Occured While Extracting Policy Information");
		} 

		if (!finalGitPath.equalsIgnoreCase("") || policyId!=null || description!=null || version!=null || isValid!=null) {							
			response.setStatus(HttpServletResponse.SC_OK);								
			response.addHeader("gitPath", finalGitPath);
			response.addHeader("policyId", policyId);
			response.addHeader("description", description);
			response.addHeader("version", version);
			response.addHeader("isValid", isValid.toString());
		} else {						
			response.setStatus(HttpServletResponse.SC_NOT_FOUND);								
		}						

	}

	/**
	 * Given a version string consisting of integers with dots between them, convert it into an array of ints.
	 * 
	 * @param version
	 * @return
	 * @throws NumberFormatException
	 */
	public static int[] versionStringToArray(String version) throws NumberFormatException {
		if (version == null || version.length() == 0) {
			return new int[0];
		}
		String[] stringArray = version.split("\\.");
		int[] resultArray = new int[stringArray.length];
		for (int i = 0; i < stringArray.length; i++) {
			resultArray[i] = Integer.parseInt(stringArray[i]);
		}
		return resultArray;
	}

	protected String	getPDPID(HttpServletRequest request) {
		String pdpURL = request.getHeader(XACMLRestProperties.PROP_PDP_HTTP_HEADER_ID);
		if (pdpURL == null || pdpURL.isEmpty()) {
			//
			// Should send back its port for identification
			//
			logger.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "PDP did not send custom header");
			pdpURL = "";
		}
		return  pdpURL;
	}

	protected String getPDPJMX(HttpServletRequest request) {
		String pdpJMMX = request.getHeader(XACMLRestProperties.PROP_PDP_HTTP_HEADER_JMX_PORT);
		if (pdpJMMX == null || pdpJMMX.isEmpty()) {
			//
			// Should send back its port for identification
			//
			logger.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "PDP did not send custom header for JMX Port so the value of 0 is assigned");
			return null;
		}
		return pdpJMMX;
	}
	private boolean isPDPCurrent(Properties policies, Properties pipconfig, Properties pdpProperties) {
		String localRootPolicies = policies.getProperty(XACMLProperties.PROP_ROOTPOLICIES);
		String localReferencedPolicies = policies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES);
		if (localRootPolicies == null || localReferencedPolicies == null) {
			logger.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "Missing property on PAP server: RootPolicies="+localRootPolicies+"  ReferencedPolicies="+localReferencedPolicies);
			return false;
		}
		//
		// Compare the policies and pipconfig properties to the pdpProperties
		//
		try {
			//
			// the policy properties includes only xacml.rootPolicies and 
			// xacml.referencedPolicies without any .url entries
			//
			Properties pdpPolicies = XACMLProperties.getPolicyProperties(pdpProperties, false);
			Properties pdpPipConfig = XACMLProperties.getPipProperties(pdpProperties);
			if (localRootPolicies.equals(pdpPolicies.getProperty(XACMLProperties.PROP_ROOTPOLICIES)) &&
					localReferencedPolicies.equals(pdpPolicies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES)) &&
					pdpPipConfig.equals(pipconfig)) {
				//
				// The PDP is current
				//
				return true;
			}
		} catch (Exception e) {
			// we get here if the PDP did not include either xacml.rootPolicies or xacml.pip.engines,
			// or if there are policies that do not have a corresponding ".url" property.
			// Either of these cases means that the PDP is not up-to-date, so just drop-through to return false.
			PolicyLogger.error(MessageCodes.ERROR_SCHEMA_INVALID, e, "XACMLPapServlet", " PDP Error");
		}
		return false;
	}

	private void populatePolicyURL(StringBuffer urlPath, Properties policies) {
		String lists[] = new String[2];
		lists[0] = policies.getProperty(XACMLProperties.PROP_ROOTPOLICIES);
		lists[1] = policies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES);
		for (String list : lists) {
			if (list != null && list.isEmpty() == false) {
				for (String id : Splitter.on(',').trimResults().omitEmptyStrings().split(list)) {
					String url = urlPath + "?id=" + id;
					logger.info("Policy URL for " + id + ": " + url);
					policies.setProperty(id + ".url", url);
				}
			}
		}
	}


	/**
	 * @see HttpServlet#doPut(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ECOMPLoggingContext loggingContext = ECOMPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
		storedRequestId = loggingContext.getRequestID();
		loggingContext.transactionStarted();
		loggingContext.setServiceName("PAP.put"); // we may set a more specific value later
		if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
			UUID requestID = UUID.randomUUID();
			loggingContext.setRequestID(requestID.toString());
			PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doPut) so we generated one");
		} else {
			PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doPut)");
		}
		// dummy metric.log example posted below as proof of concept
		loggingContext.metricStarted();
		loggingContext.metricEnded();
		PolicyLogger.metrics("Metric example posted here - 1 of 2");
		loggingContext.metricStarted();
		loggingContext.metricEnded();
		PolicyLogger.metrics("Metric example posted here - 2 of 2");
		//This im.startTransaction() covers all Put transactions
		try {
			im.startTransaction();
		} catch (AdministrativeStateException ae){
			String message = "PUT interface called for PAP " + papResourceName + " but it has an Administrative"
					+ " state of " + im.getStateManager().getAdminState()
					+ "\n Exception Message: " + ae.getMessage();
			logger.info(message);
			PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
			loggingContext.transactionEnded();

			PolicyLogger.audit("Transaction Failed - See Error.log");
			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
			return;
		}catch (StandbyStatusException se) {
			se.printStackTrace();
			String message = "PUT interface called for PAP " + papResourceName + " but it has a Standby Status"
					+ " of " + im.getStateManager().getStandbyStatus()
					+ "\n Exception Message: " + se.getMessage();
			logger.info(message);
			PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
			loggingContext.transactionEnded();

			PolicyLogger.audit("Transaction Failed - See Error.log");
			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
			return;
		}

		XACMLRest.dumpRequest(request);

		//
		// since getParameter reads the content string, explicitly get the content before doing that.
		// Simply getting the inputStream seems to protect it against being consumed by getParameter.
		//
		request.getInputStream();

		//need to check if request is from the API or Admin console
		String apiflag = request.getParameter("apiflag");

		//This would occur if a PolicyDBDao notification was received
		String policyDBDaoRequestUrl = request.getParameter("policydbdaourl");
		if(policyDBDaoRequestUrl != null){
			String policyDBDaoRequestEntityId = request.getParameter("entityid");
			//String policyDBDaoRequestEntityType = request.getParameter("entitytype");
			String policyDBDaoRequestEntityType = request.getParameter("entitytype");
			String policyDBDaoRequestExtraData = request.getParameter("extradata");
			if(policyDBDaoRequestEntityId == null || policyDBDaoRequestEntityType == null){
				response.sendError(400, "entityid or entitytype not supplied");
				loggingContext.transactionEnded();
				PolicyLogger.audit("Transaction Ended Successfully");
				im.endTransaction();
				return;
			}
			policyDBDao.handleIncomingHttpNotification(policyDBDaoRequestUrl,policyDBDaoRequestEntityId,policyDBDaoRequestEntityType,policyDBDaoRequestExtraData,this);			
			response.setStatus(200);
			loggingContext.transactionEnded();
			PolicyLogger.audit("Transaction Ended Successfully");
			im.endTransaction();
			return;
		}

		//This would occur if we received a notification of a policy creation or update
		String policyToCreateUpdate = request.getParameter("policyToCreateUpdate");
		if(policyToCreateUpdate != null){
			if(logger.isDebugEnabled()){
				logger.debug("\nXACMLPapServlet.doPut() - before decoding"
						+ "\npolicyToCreateUpdate = " + policyToCreateUpdate);
			}
			//decode it
			try{
				policyToCreateUpdate = URLDecoder.decode(policyToCreateUpdate, "UTF-8");
				if(logger.isDebugEnabled()){
					logger.debug("\nXACMLPapServlet.doPut() - after decoding"
							+ "\npolicyToCreateUpdate = " + policyToCreateUpdate);
				}
			} catch(UnsupportedEncodingException e){
				PolicyLogger.error("\nXACMLPapServlet.doPut() - Unsupported URL encoding of policyToCreateUpdate (UTF-8)"
						+ "\npolicyToCreateUpdate = " + policyToCreateUpdate);
				response.sendError(500,"policyToCreateUpdate encoding not supported"
						+ "\nfailure with the following exception: " + e);
				loggingContext.transactionEnded();
				PolicyLogger.audit("Transaction Failed - See error.log");
				im.endTransaction();
				return;
			}

			//send it to PolicyDBDao
			PolicyDBDaoTransaction createUpdateTransaction = policyDBDao.getNewTransaction();
			try{
				createUpdateTransaction.createPolicy(policyToCreateUpdate, "XACMLPapServlet.doPut");
			}catch(Exception e){
				createUpdateTransaction.rollbackTransaction();
				response.sendError(500,"createUpdateTransaction.createPolicy(policyToCreateUpdate, XACMLPapServlet.doPut) "
						+ "\nfailure with the following exception: " + e);
				loggingContext.transactionEnded();
				PolicyLogger.audit("Transaction Failed - See error.log");
				im.endTransaction();
				return;
			}
			createUpdateTransaction.commitTransaction();
			// Before sending Ok. Lets call AutoPush. 
			if(autoPushFlag){
				Set<StdPDPGroup> changedGroups = autoPushPolicy.checkGroupsToPush(policyToCreateUpdate,  this.papEngine);
				if(!changedGroups.isEmpty()){
					for(StdPDPGroup group: changedGroups){
						try{
							papEngine.updateGroup(group);
							if (logger.isDebugEnabled()) {		
								logger.debug("Group '" + group.getId() + "' updated");
							}
							notifyAC();
							// Group changed, which might include changing the policies	
							groupChanged(group);
						}catch(Exception e){
							PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " Failed to Push policy. ");
						}
					}
				}
			}
			response.setStatus(HttpServletResponse.SC_OK);
			loggingContext.transactionEnded();
			PolicyLogger.audit("Transaction Ended Successfully");
			im.endTransaction();
			return;
		}

		/*
		 * Request for Micro Service Import
		 */
		String microServiceCreation = request.getParameter("importService");
		if (microServiceCreation != null) {
			if(authorizeRequest(request)){   
				if (microServiceCreation.contains("MICROSERVICE")){
					doImportMicroServicePut(request, response);
					im.endTransaction();
					return;
				}
			} else {
				String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
				logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + message );
				loggingContext.transactionEnded();
				PolicyLogger.audit("Transaction Failed - See Error.log");
				response.sendError(HttpServletResponse.SC_FORBIDDEN, message);
				return;
			}
		}
		//This would occur if we received a notification of a policy rename from AC
		String oldPolicyName = request.getParameter("oldPolicyName");
		String newPolicyName = request.getParameter("newPolicyName");
		if(oldPolicyName != null && newPolicyName != null){
			if(logger.isDebugEnabled()){
				logger.debug("\nXACMLPapServlet.doPut() - before decoding"
						+ "\npolicyToCreateUpdate = " + " ");
			}
			//decode it
			try{
				oldPolicyName = URLDecoder.decode(oldPolicyName, "UTF-8");
				newPolicyName = URLDecoder.decode(newPolicyName, "UTF-8");
				if(logger.isDebugEnabled()){
					logger.debug("\nXACMLPapServlet.doPut() - after decoding"
							+ "\npolicyToCreateUpdate = " + " ");
				}
			} catch(UnsupportedEncodingException e){
				PolicyLogger.error("\nXACMLPapServlet.doPut() - Unsupported URL encoding of policyToCreateUpdate (UTF-8)"
						+ "\npolicyToCreateUpdate = " + " ");
				response.sendError(500,"policyToCreateUpdate encoding not supported"
						+ "\nfailure with the following exception: " + e);
				loggingContext.transactionEnded();
				PolicyLogger.audit("Transaction Failed - See error.log");
				im.endTransaction();
				return;
			}
			//send it to PolicyDBDao
			PolicyDBDaoTransaction renameTransaction = policyDBDao.getNewTransaction();
			try{
				renameTransaction.renamePolicy(oldPolicyName,newPolicyName, "XACMLPapServlet.doPut");
			}catch(Exception e){
				renameTransaction.rollbackTransaction();
				response.sendError(500,"createUpdateTransaction.createPolicy(policyToCreateUpdate, XACMLPapServlet.doPut) "
						+ "\nfailure with the following exception: " + e);
				loggingContext.transactionEnded();
				PolicyLogger.audit("Transaction Failed - See error.log");
				im.endTransaction();
				return;
			}
			renameTransaction.commitTransaction();
			response.setStatus(HttpServletResponse.SC_OK);
			loggingContext.transactionEnded();
			PolicyLogger.audit("Transaction Ended Successfully");
			im.endTransaction();
			return;
		}


		//
		// See if this is Admin Console registering itself with us
		//
		String acURLString = request.getParameter("adminConsoleURL");
		if (acURLString != null) {
			loggingContext.setServiceName("AC:PAP.register");
			//
			// remember this Admin Console for future updates
			//
			if ( ! adminConsoleURLStringList.contains(acURLString)) {
				adminConsoleURLStringList.add(acURLString);
			}
			if (logger.isDebugEnabled()) {
				logger.debug("Admin Console registering with URL: " + acURLString);
			}
			response.setStatus(HttpServletResponse.SC_NO_CONTENT);
			loggingContext.transactionEnded();
			auditLogger.info("Success");
			PolicyLogger.audit("Transaction Ended Successfully");
			im.endTransaction();
			return;
		}

		/*
		 * This is to update the PDP Group with the policy/policies being pushed
		 * Part of a 2 step process to push policie to the PDP that can now be done 
		 * From both the Admin Console and the PolicyEngine API
		 */
		String groupId = request.getParameter("groupId");
		if (groupId != null) {
			if(apiflag!=null){
				if(apiflag.equalsIgnoreCase("addPolicyToGroup")){
					updateGroupsFromAPI(request, response, groupId, loggingContext);
					loggingContext.transactionEnded();
					PolicyLogger.audit("Transaction Ended Successfully");
					im.endTransaction();
					return;
				}
			}
			//
			// this is from the Admin Console, so handle separately
			//
			doACPut(request, response, groupId, loggingContext);
			loggingContext.transactionEnded();
			PolicyLogger.audit("Transaction Ended Successfully");
			im.endTransaction();
			return;
		}

		//
		// Request is for policy validation and creation
		//
		if (apiflag != null && apiflag.equalsIgnoreCase("admin")){
			/*
			 * this request is from the Admin Console
			 */
			loggingContext.transactionEnded();
			PolicyLogger.audit("Transaction Ended Successfully");
			doACPolicyPut(request, response);
			im.endTransaction();
			return;

		} else if (apiflag != null && apiflag.equalsIgnoreCase("api")) {
			/*
			 * this request is from the Policy Creation API
			 */
			// Authenticating the Request here. 
			if(authorizeRequest(request)){
				loggingContext.transactionEnded();
				PolicyLogger.audit("Transaction Ended Successfully");
				doPolicyAPIPut(request, response);
				im.endTransaction();
				return;
			} else {
				String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
				PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
				loggingContext.transactionEnded();

				PolicyLogger.audit("Transaction Failed - See Error.log");
				response.sendError(HttpServletResponse.SC_FORBIDDEN, message);
				im.endTransaction();
				return;
			}

		}


		//
		// We do not expect anything from anywhere else.
		// This method is here in case we ever need to support other operations.
		//
		logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Request does not have groupId or apiflag");
		loggingContext.transactionEnded();

		PolicyLogger.audit("Transaction Failed - See Error.log");
		response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Request does not have groupId or apiflag");
		loggingContext.transactionEnded();
		PolicyLogger.audit("Transaction Failed - See error.log");
		im.endTransaction();
	}

	/**
	 * @see HttpServlet#doDelete(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ECOMPLoggingContext loggingContext = ECOMPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
		loggingContext.transactionStarted();
		loggingContext.setServiceName("PAP.delete"); // we may set a more specific value later
		if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){
			UUID requestID = UUID.randomUUID();
			loggingContext.setRequestID(requestID.toString());
			PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doDelete) so we generated one");
		} else {
			PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doDelete)");
		}
		loggingContext.metricStarted();
		loggingContext.metricEnded();
		PolicyLogger.metrics("Metric example posted here - 1 of 2");
		loggingContext.metricStarted();
		loggingContext.metricEnded();
		PolicyLogger.metrics("Metric example posted here - 2 of 2");	

		//This im.startTransaction() covers all Delete transactions
		try {
			im.startTransaction();
		} catch (AdministrativeStateException ae){
			String message = "DELETE interface called for PAP " + papResourceName + " but it has an Administrative"
					+ " state of " + im.getStateManager().getAdminState()
					+ "\n Exception Message: " + ae.getMessage();
			logger.info(message);
			PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
			loggingContext.transactionEnded();

			PolicyLogger.audit("Transaction Failed - See Error.log");
			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
			return;
		}catch (StandbyStatusException se) {
			se.printStackTrace();
			String message = "PUT interface called for PAP " + papResourceName + " but it has a Standby Status"
					+ " of " + im.getStateManager().getStandbyStatus()
					+ "\n Exception Message: " + se.getMessage();
			logger.info(message);
			PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
			loggingContext.transactionEnded();

			PolicyLogger.audit("Transaction Failed - See Error.log");

			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
			return;
		}

		XACMLRest.dumpRequest(request);

		String groupId = request.getParameter("groupId");
		String apiflag = request.getParameter("apiflag");

		if (groupId != null) {
			// Is this from the Admin Console or API?
			if(apiflag!=null) {
				if (apiflag.equalsIgnoreCase("deletePapApi")) {
					// this is from the API so we need to check the client credentials before processing the request
					if(authorizeRequest(request)){
						doAPIDeleteFromPAP(request, response, loggingContext);
						return;
					} else {
						String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
						PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
						loggingContext.transactionEnded();

						PolicyLogger.audit("Transaction Failed - See Error.log");
						response.sendError(HttpServletResponse.SC_FORBIDDEN, message);
						return;
					}
				} else if (apiflag.equalsIgnoreCase("deletePdpApi")) {
					if(authorizeRequest(request)){
						doAPIDeleteFromPDP(request, response, loggingContext);
						return;
					} else {
						String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
						PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
						loggingContext.transactionEnded();

						PolicyLogger.audit("Transaction Failed - See Error.log");
						response.sendError(HttpServletResponse.SC_FORBIDDEN, message);
						return;
					}
				}
			}

			// this is from the Admin Console, so handle separately
			doACDelete(request, response, groupId, loggingContext);
			loggingContext.transactionEnded();
			PolicyLogger.audit("Transaction Ended Successfully");
			im.endTransaction();
			return;

		}
		//
		// We do not expect anything from anywhere else.
		// This method is here in case we ever need to support other operations.
		//
		PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Request does not have groupId");
		loggingContext.transactionEnded();

		PolicyLogger.audit("Transaction Failed - See Error.log");

		response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Request does not have groupId");

		//Catch anything that fell through
		im.endTransaction();

	}
	//
	// Admin Console request handling
	//

	/**
	 * Requests from the Admin Console to GET info about the Groups and PDPs
	 * 
	 * @param request
	 * @param response
	 * @param groupId
	 * @param loggingContext 
	 * @throws ServletException
	 * @throws IOException
	 */
	private void doACGet(HttpServletRequest request, HttpServletResponse response, String groupId, ECOMPLoggingContext loggingContext) throws ServletException, IOException {
		try {
			String parameterDefault = request.getParameter("default");
			String pdpId = request.getParameter("pdpId");
			String pdpGroup = request.getParameter("getPDPGroup");
			if ("".equals(groupId)) {
				// request IS from AC but does not identify a group by name
				if (parameterDefault != null) {
					// Request is for the Default group (whatever its id)
					loggingContext.setServiceName("AC:PAP.getDefaultGroup");

					EcompPDPGroup group = papEngine.getDefaultGroup();

					// convert response object to JSON and include in the response
					ObjectMapper mapper = new ObjectMapper();
					mapper.writeValue(response.getOutputStream(),  group);

					if (logger.isDebugEnabled()) {
						logger.debug("GET Default group req from '" + request.getRequestURL() + "'");
					}
					response.setStatus(HttpServletResponse.SC_OK);
					response.setHeader("content-type", "application/json");
					response.getOutputStream().close();
					loggingContext.transactionEnded();
					auditLogger.info("Success");
					PolicyLogger.audit("Transaction Ended Successfully");
					return;

				} else if (pdpId != null) {
					// Request is related to a PDP
					if (pdpGroup == null) {
						// Request is for the PDP itself
						// Request is for the (unspecified) group containing a given PDP
						loggingContext.setServiceName("AC:PAP.getPDP");
						EcompPDP pdp = papEngine.getPDP(pdpId);

						// convert response object to JSON and include in the response
						ObjectMapper mapper = new ObjectMapper();
						mapper.writeValue(response.getOutputStream(),  pdp);

						if (logger.isDebugEnabled()) {
							logger.debug("GET pdp '" + pdpId + "' req from '" + request.getRequestURL() + "'");
						}
						response.setStatus(HttpServletResponse.SC_OK);
						response.setHeader("content-type", "application/json");
						response.getOutputStream().close();
						loggingContext.transactionEnded();
						auditLogger.info("Success");
						PolicyLogger.audit("Transaction Ended Successfully");
						return;

					} else {
						// Request is for the group containing a given PDP
						loggingContext.setServiceName("AC:PAP.getGroupForPDP");
						EcompPDP pdp = papEngine.getPDP(pdpId);
						EcompPDPGroup group = papEngine.getPDPGroup((EcompPDP) pdp);

						// convert response object to JSON and include in the response
						ObjectMapper mapper = new ObjectMapper();
						mapper.writeValue(response.getOutputStream(),  group);

						if (logger.isDebugEnabled()) {
							logger.debug("GET PDP '" + pdpId + "' Group req from '" + request.getRequestURL() + "'");
						}
						response.setStatus(HttpServletResponse.SC_OK);
						response.setHeader("content-type", "application/json");
						response.getOutputStream().close();
						loggingContext.transactionEnded();
						auditLogger.info("Success");
						PolicyLogger.audit("Transaction Ended Successfully");
						return;
					}

				} else {
					// request is for top-level properties about all groups
					loggingContext.setServiceName("AC:PAP.getAllGroups");
					Set<EcompPDPGroup> groups = papEngine.getEcompPDPGroups();

					// convert response object to JSON and include in the response
					ObjectMapper mapper = new ObjectMapper();
					mapper.writeValue(response.getOutputStream(),  groups);

					if (logger.isDebugEnabled()) {
						logger.debug("GET All groups req");
					}
					response.setStatus(HttpServletResponse.SC_OK);
					response.setHeader("content-type", "application/json");
					response.getOutputStream().close();
					loggingContext.transactionEnded();
					auditLogger.info("Success");
					PolicyLogger.audit("Transaction Ended Successfully");
					return;
				}
			}

			// for all other GET operations the group must exist before the operation can be done
			EcompPDPGroup group = papEngine.getGroup(groupId);
			if (group == null) {
				String message = "Unknown groupId '" + groupId + "'";
				PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
				loggingContext.transactionEnded();

				PolicyLogger.audit("Transaction Failed - See Error.log");
				response.sendError(HttpServletResponse.SC_NOT_FOUND, message);
				return;
			}


			// Figure out which request this is based on the parameters
			String policyId = request.getParameter("policyId");

			if (policyId != null) {
				// retrieve a policy
				loggingContext.setServiceName("AC:PAP.getPolicy");
				//
				// convert response object to JSON and include in the response
				//
				PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " GET Policy not implemented");
				loggingContext.transactionEnded();

				PolicyLogger.audit("Transaction Failed - See Error.log");

				response.sendError(HttpServletResponse.SC_BAD_REQUEST, "GET Policy not implemented");

			} else {
				// No other parameters, so return the identified Group
				loggingContext.setServiceName("AC:PAP.getGroup");

				// convert response object to JSON and include in the response
				ObjectMapper mapper = new ObjectMapper();
				mapper.writeValue(response.getOutputStream(),  group);

				if (logger.isDebugEnabled()) {
					logger.debug("GET group '" + group.getId() + "' req from '" + request.getRequestURL() + "'");
				}
				response.setStatus(HttpServletResponse.SC_OK);
				response.setHeader("content-type", "application/json");
				response.getOutputStream().close();
				loggingContext.transactionEnded();
				auditLogger.info("Success");
				PolicyLogger.audit("Transaction Ended Successfully");
				return;
			}

			//
			// Currently there are no other GET calls from the AC.
			// The AC uses the "GET All Groups" operation to fill its local cache and uses that cache for all other GETs without calling the PAP.
			// Other GETs that could be called:
			//				Specific Group	(groupId=<groupId>)
			//				A Policy		(groupId=<groupId> policyId=<policyId>)
			//				A PDP			(groupId=<groupId> pdpId=<pdpId>)

			PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " UNIMPLEMENTED ");
			loggingContext.transactionEnded();

			PolicyLogger.audit("Transaction Failed - See Error.log");

			response.sendError(HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
		} catch (PAPException e) {
			PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC Get exception");
			loggingContext.transactionEnded();

			PolicyLogger.audit("Transaction Failed - See Error.log");
			response.sendError(500, e.getMessage());
			return;
		}

	}

	/**
	 * Requests from the Admin Console for validating and creating policies
	 * 
	 * @param request
	 * @param response
	 * @param groupId
	 * @throws JsonMappingException 
	 * @throws JsonParseException 
	 * @throws ServletException
	 * @throws IOException
	 */
	private void doACPolicyPut(HttpServletRequest request,
			HttpServletResponse response) throws JsonParseException, JsonMappingException, IOException {

		String operation = request.getParameter("operation");
		String policyType = request.getParameter("policyType");
		String apiflag = request.getParameter("apiflag"); 

		if ( policyType != null ) {
			PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
			Policy newPolicy = null;
			// get the request content into a String
			String json = null;
			// read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
			java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
			scanner.useDelimiter("\\A");
			json =  scanner.hasNext() ? scanner.next() : "";
			scanner.close();
			logger.info("JSON request from AC: " + json);
			// convert Object sent as JSON into local object
			ObjectMapper mapper = new ObjectMapper();
			Object objectFromJSON = mapper.readValue(json, StdPAPPolicy.class);

			StdPAPPolicy policy = (StdPAPPolicy) objectFromJSON;

			//Set policyAdapter values including parentPath (Common to all policy types)
			//Set values for policy adapter
			try {
				if (operation.equalsIgnoreCase("validate")) {
					policyAdapter.setPolicyName(policy.getPolicyName());
					policyAdapter.setConfigType(policy.getConfigType());
					policyAdapter.setConfigBodyData(policy.getConfigBodyData());
				} else {
					policyAdapter = setDataToPolicyAdapter(policy, policyType, apiflag);
				}
			} catch (Exception e1) {
				logger.error("Exception occured While Setting Values for Policy Adapter"+e1);
			}
			// Calling Component class per policy type
			if (policyType.equalsIgnoreCase("Config")) {
				String configPolicyType = policy.getConfigPolicyType();
				if (configPolicyType != null && configPolicyType.equalsIgnoreCase("Firewall Config")) {
					newPolicy = new FirewallConfigPolicy(policyAdapter);
				} 
				else if (configPolicyType != null && configPolicyType.equalsIgnoreCase("BRMS_Raw")) {
					newPolicy = new CreateBrmsRawPolicy(policyAdapter);
				}else if (configPolicyType != null && configPolicyType.equalsIgnoreCase("BRMS_Param")) {
					policyAdapter.setBrmsParamBody(policy.getDrlRuleAndUIParams());
					newPolicy = new CreateBrmsParamPolicy(policyAdapter);
				}
				else if (configPolicyType != null && configPolicyType.equalsIgnoreCase("Base")) {
					newPolicy =  new ConfigPolicy(policyAdapter);
				}else if (configPolicyType != null && configPolicyType.equalsIgnoreCase("ClosedLoop_Fault")) {
					newPolicy = new ClosedLoopPolicy(policyAdapter);
				}else if (configPolicyType != null && configPolicyType.equalsIgnoreCase("ClosedLoop_PM")) {
					newPolicy = new CreateClosedLoopPerformanceMetrics(policyAdapter);	
				}else if (configPolicyType != null && configPolicyType.equalsIgnoreCase("DCAE Micro Service")) {	
					newPolicy = new MicroServiceConfigPolicy(policyAdapter);
				}

			} else if (policyType.equalsIgnoreCase("Action")) {
				newPolicy = new ActionPolicy(policyAdapter);
			} else if (policyType.equalsIgnoreCase("Decision")) {
				newPolicy = new DecisionPolicy(policyAdapter);	
			}

			// Validation
			if (operation != null && operation.equalsIgnoreCase("validate")) {

				// validate the body data if applicable and return a response to the PAP-ADMIN	(Config Base only)
				if (newPolicy.validateConfigForm()) {					
					response.setStatus(HttpServletResponse.SC_OK);
					response.addHeader("isValidData", "true");					
				} else {	
					response.setStatus(HttpServletResponse.SC_OK);	
					response.addHeader("isValidData", "false");
				}

			}   

			// Create or Update Policy        
			if (operation != null && (operation.equalsIgnoreCase("create") || operation.equalsIgnoreCase("update"))) {

				// create the policy and return a response to the PAP-ADMIN		        
				PolicyDBDaoTransaction policyDBDaoTransaction = policyDBDao.getNewTransaction();
				try {
					Map<String, String> successMap;
					newPolicy.prepareToSave();
					policyDBDaoTransaction.createPolicy(newPolicy, "doACPolicyPut");
					successMap = newPolicy.savePolicies();
					if (successMap.containsKey("success")) {
						policyDBDaoTransaction.commitTransaction();
						response.setStatus(HttpServletResponse.SC_OK);
						response.addHeader("successMapKey", "success");		    						    				
						response.addHeader("finalPolicyPath", policyAdapter.getFinalPolicyPath());	
					} else {								
						policyDBDaoTransaction.rollbackTransaction();
						response.setStatus(HttpServletResponse.SC_OK);								
					}	
				} catch (Exception e) {	
					policyDBDaoTransaction.rollbackTransaction();
					PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Could not save policy ");
					response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
				}		        	
			}

		}

	}

	private void doPolicyAPIPut(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		String operation = request.getParameter("operation");
		String policyType = request.getParameter("policyType");
		String apiflag = request.getParameter("apiflag");

		
		if ( policyType != null ) {
			PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
			Policy newPolicy = null;

			// get the request content into a String
			String json = null;

			// read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
			java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
			scanner.useDelimiter("\\A");
			json =  scanner.hasNext() ? scanner.next() : "";
			scanner.close();
			logger.info("JSON request from API: " + json);

			// convert Object sent as JSON into local object
			ObjectMapper mapper = new ObjectMapper();

			Object objectFromJSON = mapper.readValue(json, StdPAPPolicy.class);

			StdPAPPolicy policy = (StdPAPPolicy) objectFromJSON;

			//Set policyAdapter values including parentPath (Common to all policy types)
			try {
				policyAdapter = setDataToPolicyAdapter(policy, policyType, apiflag);
			} catch (Exception e1) {
				logger.error(XACMLErrorConstants.ERROR_UNKNOWN + 
						"Could not set data to policy adapter ",e1);
			}

			// Calling Component class per policy type
			if (policyType.equalsIgnoreCase("Config")) {
				String configPolicyType = policy.getConfigPolicyType();
				if (configPolicyType != null && configPolicyType.equalsIgnoreCase("Firewall Config")) {

					newPolicy = new FirewallConfigPolicy(policyAdapter);

				} 
				else if (configPolicyType != null && configPolicyType.equalsIgnoreCase("BRMS_Raw")) { 

					newPolicy = new CreateBrmsRawPolicy(policyAdapter);

				}else if (configPolicyType != null && configPolicyType.equalsIgnoreCase("BRMS_Param")) {

					policyAdapter.setBrmsParamBody(policy.getDrlRuleAndUIParams());
					//check for valid actionAttributes
					//Setup EntityManager to communicate with the PolicyVersion table of the DB
					EntityManager em = null;
					em = (EntityManager) emf.createEntityManager();

					Map<String,String> ruleAndUIValue=policyAdapter.getBrmsParamBody();
					String modelName= ruleAndUIValue.get("templateName");
					logger.info("Template name from API is: "+modelName);

					Query getModel = em.createNamedQuery("BRMSParamTemplate.findAll");	
					List<?> modelList = getModel.getResultList(); 	
					Boolean isValidService = false;
					for (Object id : modelList) {
						BRMSParamTemplate value = (BRMSParamTemplate)id;
						logger.info("Template value from dictionary is: "+value);
						if (modelName.equals(value.getRuleName())) {
							isValidService = true;
							break;
						}
					}

					em.close();

					if (isValidService) {
						newPolicy = new CreateBrmsParamPolicy(policyAdapter);
					} else {
						logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Template.  The template name, " 
								+ modelName 
								+ " was not found in the dictionary.");
						response.addHeader("error", "missingTemplate");	
						response.addHeader("modelName", modelName);
						response.setStatus(HttpServletResponse.SC_BAD_REQUEST);								
						return;
					}
				}
				else if (configPolicyType != null && configPolicyType.equalsIgnoreCase("Base")) {

					newPolicy =  new ConfigPolicy(policyAdapter);

				}else if (configPolicyType != null && configPolicyType.equalsIgnoreCase("ClosedLoop_Fault")) {

					newPolicy = new ClosedLoopPolicy(policyAdapter);

				}else if (configPolicyType != null && configPolicyType.equalsIgnoreCase("ClosedLoop_PM")) {

					newPolicy = new CreateClosedLoopPerformanceMetrics(policyAdapter);

				}else if (configPolicyType != null && configPolicyType.equalsIgnoreCase("DCAE Micro Service")) {

					//check for valid actionAttributes
					//Setup EntityManager to communicate with the PolicyVersion table of the DB
					EntityManager em = null;
					em = (EntityManager) emf.createEntityManager();

					String modelName = policy.getServiceType();
					String modelVersion = policy.getVersion();

					Query getModel = em.createNamedQuery("MicroServiceModels.findAll");	
					List<?> modelList = getModel.getResultList(); 	
					Boolean isValidService = false;
					for (Object id : modelList) {
						MicroServiceModels value = (MicroServiceModels)id;
						if (modelName.equals(value.getModelName()) && modelVersion.equals(value.getVersion())) {
							isValidService = true;
							break;
						}
					}

					em.close();

					if (isValidService) {
						newPolicy = new MicroServiceConfigPolicy(policyAdapter);
					} else {
						logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Service or Version.  The Service Model, " 
								+ modelName + " of version " + modelVersion 
								+ " was not found in the dictionary.");
						response.addHeader("error", "serviceModelDB");	
						response.addHeader("modelName", modelName);
						response.addHeader("modelVersion", modelVersion);
						response.setStatus(HttpServletResponse.SC_BAD_REQUEST);								
						return;
					}

				}

			} else if (policyType.equalsIgnoreCase("Action")) {

				//check for valid actionAttributes
				//Setup EntityManager to communicate with the PolicyVersion table of the DB
				EntityManager em = null;
				em = (EntityManager) emf.createEntityManager();

				String attributeName = policy.getActionAttribute();

				Query getActionAttributes = em.createNamedQuery("ActionPolicyDict.findAll");	
				List<?> actionAttributesList = getActionAttributes.getResultList(); 	
				Boolean isAttribute = false;
				for (Object id : actionAttributesList) {
					ActionPolicyDict value = (ActionPolicyDict)id;
					if (attributeName.equals(value.getAttributeName())) {
						isAttribute = true;
						break;
					}
				}

				em.close();

				if (isAttribute) {
					newPolicy = new ActionPolicy(policyAdapter);
				} else {
					logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Could not fine " + attributeName + " in the ActionPolicyDict table.");
					response.addHeader("error", "actionPolicyDB");	
					response.addHeader("actionAttribute", attributeName);
					response.setStatus(HttpServletResponse.SC_BAD_REQUEST);								
					return;
				}

			} else if (policyType.equalsIgnoreCase("Decision")) {

				newPolicy = new DecisionPolicy(policyAdapter);

			}

			// Create or Update Policy        
			if (operation != null && (operation.equalsIgnoreCase("create") || operation.equalsIgnoreCase("update"))) {

				// create the policy and return a response to the PAP-ADMIN		        
				if (newPolicy.validateConfigForm()) {		        		
					PolicyDBDaoTransaction policyDBDaoTransaction = policyDBDao.getNewTransaction();
					try {	

						// added check for existing policy when new policy is created to 
						// unique API error for "policy already exists" 
						Boolean isNewPolicy = newPolicy.prepareToSave();
						if(isNewPolicy){
							policyDBDaoTransaction.createPolicy(newPolicy, "doPolicyAPIPut");
						}
						Map<String, String> successMap = newPolicy.savePolicies();							
						if (successMap.containsKey("success")) {
							
							EntityManager apiEm = null;
							apiEm = (EntityManager) emf.createEntityManager();
							//
							// Did it get created?
							//
							if (apiEm == null) {
								PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE +  " Error creating entity manager with persistence unit: " + PERSISTENCE_UNIT);	
								ServletException e = new ServletException("Unable to create Entity Manager Factory");
								e.printStackTrace();
								throw e;
							}
							
							String finalPath = policyAdapter.getFinalPolicyPath();
		    				//
		    				//Check the database entry if a scope is available in PolicyEditorScope table or not.
		    				//If not exists create a new entry.
		    				//
		    				String dirName = finalPath.toString().substring(finalPath.toString().indexOf("repository")+11, finalPath.toString().lastIndexOf(File.separator));
		    				apiEm.getTransaction().begin();
		    				Query query = apiEm.createQuery("Select p from PolicyEditorScopes p where p.scopeName=:sname");
		    				query.setParameter("sname", dirName);
		    				
		    				@SuppressWarnings("rawtypes")
		    				List result = query.getResultList();
		    				if(result.isEmpty()){
		    					PolicyEditorScopes scopeEntity = new PolicyEditorScopes();
		    					scopeEntity.setScopeName(dirName);
		    					UserInfo user = new UserInfo();
		    					user.setUserLoginId("API");
		    					user.setUserName("API");
		    					scopeEntity.setUserCreatedBy(user);
		    					scopeEntity.setUserModifiedBy(user);
		    					try{
		    						apiEm.persist(scopeEntity);
			    					apiEm.getTransaction().commit();
		    					}catch(Exception e){
		    						PolicyLogger.error("Exception Occured while inserting a new Entry to PolicyEditorScopes table"+e);
		    						apiEm.getTransaction().rollback();
		    					}finally{
		    						apiEm.close();
		    					}
		    				}else{
	    						PolicyLogger.info("Scope Already Exists in PolicyEditorScopes table, Hence Closing the Transaction");
	    						apiEm.close();
	    					}
		    				
							policyDBDaoTransaction.commitTransaction();
							response.setStatus(HttpServletResponse.SC_OK);								
							response.addHeader("successMapKey", "success");								
							response.addHeader("policyName", policyAdapter.getPolicyName());

							if (operation.equalsIgnoreCase("update")) {
								response.addHeader("operation",  "update");
							} else {
								response.addHeader("operation", "create");
							}
						} else if (successMap.containsKey("EXISTS")) {
							policyDBDaoTransaction.rollbackTransaction();
							response.setStatus(HttpServletResponse.SC_CONFLICT);
							response.addHeader("error", "policyExists");
							response.addHeader("policyName", policyAdapter.getPolicyName());
						} else if (successMap.containsKey("fwdberror")) {
							policyDBDaoTransaction.rollbackTransaction();
							response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
							response.addHeader("error", "FWDBError");
							response.addHeader("policyName", policyAdapter.getPolicyName());
						}else {						
							policyDBDaoTransaction.rollbackTransaction();
							response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);								
							response.addHeader("error", "error");							
						}						
					} catch (Exception e) {							
						policyDBDaoTransaction.rollbackTransaction();
						String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + 
								"Could not save policy " + e;
						PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Could not save policy");
						response.setStatus(HttpServletResponse.SC_BAD_REQUEST);	
						response.addHeader("error", "savePolicy");
						response.addHeader("message", message);
					}		        	
				}
			}
		}
	}

	private PolicyRestAdapter setDataToPolicyAdapter(StdPAPPolicy policy, String policyType, String apiflag) throws Exception {
		PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
		int highestVersion = 0;

		if (policy.getHighestVersion()!=null) {	
			highestVersion = policy.getHighestVersion();
		}

		EntityManager apiEm = null;
		apiEm = (EntityManager) emf.createEntityManager();

		//
		// Did it get created?
		//
		if (apiEm == null) {
			PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + 
					" Error creating entity manager with persistence unit: "
					+ PERSISTENCE_UNIT);	
			throw new ServletException("Unable to create Entity Manager Factory");
		}

		Path workspacePath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WORKSPACE), "admin");
		Path repositoryPath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_REPOSITORY));
		Path gitPath = Paths.get(workspacePath.toString(), repositoryPath.getFileName().toString());

		/*
		 * Getting and Setting the parent path for Admin Console use when reading the policy files
		 */
		//domain chosen by the client to store the policy action files 
		String domain = policy.getDomainDir();

		//adding the domain to the gitPath
		Path path;
		String gitPathString = gitPath.toString();

		if (gitPathString.contains("\\")) {
			path = Paths.get(gitPath + "\\" + policy.getDomainDir());
		} else {
			path = Paths.get(gitPath + "/" + policy.getDomainDir());

		}
		logger.debug("path is: " + path.toString());

		//getting the fullpath of the gitPath and convert to string
		String policyDir = path.toAbsolutePath().toString();
		String parentPath = null;

		//creating the parentPath directory for the Admin Console use
		File file;
		if(policyDir.contains("\\"))
		{
			parentPath = policyDir.replace("ECOMP-PAP-REST", "ecomp-sdk-app");
			file = new File(parentPath);
		}
		else
		{
			parentPath = policyDir.replace("pap",  "console");
			file = new File(parentPath);

		}

		//Get the policy file from the git repository
		String filePrefix = null;
		if (policyType.equalsIgnoreCase("Config")) {
			if (policy.getConfigPolicyType().equalsIgnoreCase("Firewall Config")) {
				filePrefix = "Config_FW_";
			}else if (policy.getConfigPolicyType().equalsIgnoreCase("ClosedLoop_Fault")) {
				filePrefix = "Config_Fault_";
			}else if (policy.getConfigPolicyType().equalsIgnoreCase("ClosedLoop_PM")) {
				filePrefix = "Config_PM_";
			}else if (policy.getConfigPolicyType().equalsIgnoreCase("DCAE Micro Service")) {
				filePrefix = "Config_MS_";
			} else if (policy.getConfigPolicyType().equalsIgnoreCase("BRMS_Raw")) {
				filePrefix = "Config_BRMS_Raw_";
			} else if (policy.getConfigPolicyType().equalsIgnoreCase("BRMS_Param")) {
				filePrefix = "Config_BRMS_Param_";
			}
			else {
				filePrefix = "Config_";
			}
		} else if (policyType.equalsIgnoreCase("Action")) {
			filePrefix = "Action_";
		} else if (policyType.equalsIgnoreCase("Decision")) {
			filePrefix = "Decision_";
		}


		String pvName = domain + File.separator + filePrefix + policy.getPolicyName();

		//create the directory if it does not exist
		Boolean fileDir=true;
		if (!file.exists()){
			fileDir = new File(parentPath).mkdirs();
		}

		//set the parent path in the policy adapter
		if (!fileDir){
			logger.debug("Unable to create the policy directory");
		}

		logger.debug("ParentPath is: " + parentPath.toString());
		policyAdapter.setParentPath(parentPath.toString());
		policyAdapter.setApiflag(apiflag);

		if (policy.isEditPolicy()) {

			if(apiflag.equalsIgnoreCase("api")) {

				//Get the Highest Version to Update
				apiEm.getTransaction().begin();
				Query query = apiEm.createQuery("Select p from PolicyVersion p where p.policyName=:pname");
				query.setParameter("pname", pvName);

				@SuppressWarnings("rawtypes")
				List result = query.getResultList();
				PolicyVersion versionEntity = null;
				if (!result.isEmpty()) {
					versionEntity = (PolicyVersion) result.get(0);
					apiEm.persist(versionEntity);
					highestVersion = versionEntity.getHigherVersion();
					int activeVersion = versionEntity.getActiveVersion();

					Calendar calendar = Calendar.getInstance();
					Timestamp modifyDate = new Timestamp(calendar.getTime().getTime());

					//update table with highestVersion
					try{
						versionEntity.setHigherVersion(highestVersion+1);
						versionEntity.setActiveVersion(activeVersion+1);
						versionEntity.setCreatedBy("API");
						versionEntity.setModifiedBy("API");
						versionEntity.setModifiedDate(modifyDate);

						apiEm.getTransaction().commit();

					}catch(Exception e){
						apiEm.getTransaction().rollback();
						PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR");
					} finally {
						apiEm.close();
					}
				} else {
					logger.debug("\nNo PolicyVersion using policyName found");
				}		

			}

			File policyFile = null;
			if(policy.getOldPolicyFileName() != null && policy.getOldPolicyFileName().endsWith("Draft.1")) {
				policyFile = new File(parentPath.toString() + File.separator + policy.getOldPolicyFileName() + ".xml");
			} else {
				policyFile = new File(parentPath.toString() + File.separator + filePrefix + policy.getPolicyName() +"."+(highestVersion)+ ".xml");
			}

			if (policyFile.exists()) {
				DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
				DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
				Document doc = dBuilder.parse(policyFile);

				doc.getDocumentElement().normalize();

				String version = doc.getDocumentElement().getAttribute("Version");

				NodeList rList = doc.getElementsByTagName("Rule");
				Node rNode = rList.item(0);
				Element rElement = (Element) rNode;

				String ruleID = null;
				if (rNode!=null){
					ruleID = rElement.getAttribute("RuleId");
				} else {
					ruleID = newRuleID();
				}

				policyAdapter.setPolicyID(newPolicyID());
				policyAdapter.setRuleID(ruleID);
				policyAdapter.setVersion(version);

			} else {
				PolicyLogger.error(MessageCodes.ERROR_UNKNOWN + " The policy file at the path " + policyFile + " does not exist.");
			}

		} else {

			highestVersion = 1;
			if (apiflag.equalsIgnoreCase("api")) {
				Calendar calendar = Calendar.getInstance();
				Timestamp createdDate = new Timestamp(calendar.getTime().getTime());

				apiEm.getTransaction().begin();
				Query query = apiEm.createQuery("Select p from PolicyVersion p where p.policyName=:pname");
				query.setParameter("pname", pvName);

				@SuppressWarnings("rawtypes")
				List result = query.getResultList();

				if (result.isEmpty()) {

					try{
						PolicyVersion versionEntity = new PolicyVersion();
						apiEm.persist(versionEntity);
						versionEntity.setPolicyName(pvName);
						versionEntity.setHigherVersion(highestVersion);
						versionEntity.setActiveVersion(highestVersion);
						versionEntity.setCreatedBy("API");
						versionEntity.setModifiedBy("API");
						versionEntity.setCreatedDate(createdDate);
						versionEntity.setModifiedDate(createdDate);

						apiEm.getTransaction().commit();

					}catch(Exception e){
						apiEm.getTransaction().rollback();
						PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR");
					} finally {
						apiEm.close();
					}		
				}
			}

			policyAdapter.setPolicyID(newPolicyID());
			policyAdapter.setRuleID(newRuleID());	

		}

		/*
		 * set policy adapter values for Building JSON object containing policy data
		 */
		//Common among policy types
		policyAdapter.setPolicyName(policy.getPolicyName());
		policyAdapter.setPolicyDescription(policy.getPolicyDescription());
		policyAdapter.setEcompName(policy.getEcompName()); //Config Base and Decision Policies
		policyAdapter.setHighestVersion(highestVersion);
		policyAdapter.setRuleCombiningAlgId("urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:permit-overrides");
		policyAdapter.setUserGitPath(gitPath.toString());
		policyAdapter.setPolicyType(policyType);
		policyAdapter.setDynamicFieldConfigAttributes(policy.getDynamicFieldConfigAttributes());
		policyAdapter.setEditPolicy(policy.isEditPolicy());
		policyAdapter.setEntityManagerFactory(getEmf());


		//Config Specific
		policyAdapter.setConfigName(policy.getConfigName());  //Base and Firewall
		policyAdapter.setConfigBodyData(policy.getConfigBodyData()); //Base
		policyAdapter.setConfigType(policy.getConfigType());  //Base
		policyAdapter.setJsonBody(policy.getJsonBody()); //Firewall, ClosedLoop, and GoC
		policyAdapter.setConfigPolicyType(policy.getConfigPolicyType());
		policyAdapter.setDraft(policy.isDraft()); //ClosedLoop_Fault
		policyAdapter.setServiceType(policy.getServiceType()); //ClosedLoop_PM
		policyAdapter.setUuid(policy.getUuid()); //Micro Service
		policyAdapter.setLocation(policy.getMsLocation()); //Micro Service
		policyAdapter.setPriority(policy.getPriority()); //Micro Service
		policyAdapter.setPolicyScope(policy.getDomainDir());
		policyAdapter.setRiskType(policy.getRiskType()); //Safe Policy Attributes
		policyAdapter.setRiskLevel(policy.getRiskLevel());//Safe Policy Attributes
		policyAdapter.setGuard(policy.getGuard());//Safe Policy Attributes
		policyAdapter.setTtlDate(policy.getTTLDate());//Safe Policy Attributes

		//Action Policy Specific
		policyAdapter.setActionAttribute(policy.getActionAttribute());  //comboDictValue
		policyAdapter.setActionPerformer(policy.getActionPerformer());
		policyAdapter.setDynamicRuleAlgorithmLabels(policy.getDynamicRuleAlgorithmLabels());
		policyAdapter.setDynamicRuleAlgorithmCombo(policy.getDynamicRuleAlgorithmCombo());
		policyAdapter.setDynamicRuleAlgorithmField1(policy.getDynamicRuleAlgorithmField1());
		policyAdapter.setDynamicRuleAlgorithmField2(policy.getDynamicRuleAlgorithmField2());

		//Decision Policy Specific
		policyAdapter.setDynamicSettingsMap(policy.getDynamicSettingsMap());
		policyAdapter.setProviderComboBox(policy.getProviderComboBox());

		return policyAdapter;
	}

	public String	newPolicyID() {
		return Joiner.on(':').skipNulls().join((XACMLPapServlet.getDomain().startsWith("urn") ? null : "urn"),
				XACMLPapServlet.getDomain().replaceAll("[/\\\\.]", ":"), 
				"xacml", "policy", "id", UUID.randomUUID());
	}

	public String	newRuleID() {
		return Joiner.on(':').skipNulls().join((XACMLPapServlet.getDomain().startsWith("urn") ? null : "urn"),
				XACMLPapServlet.getDomain().replaceAll("[/\\\\.]", ":"), 
				"xacml", "rule", "id", UUID.randomUUID());
	}

	public static String	getDomain() {
		return XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DOMAIN, "urn");
	}


	/**
	 * Requests from the Admin Console for operations not on single specific objects
	 * 
	 * @param request
	 * @param response
	 * @param groupId
	 * @param loggingContext
	 * @throws ServletException
	 * @throws IOException
	 */
	private void doACPost(HttpServletRequest request, HttpServletResponse response, String groupId, ECOMPLoggingContext loggingContext) throws ServletException, IOException {
		PolicyDBDaoTransaction doACPostTransaction = null;

		try {
			String groupName = request.getParameter("groupName");
			String groupDescription = request.getParameter("groupDescription");
			String apiflag = request.getParameter("apiflag");

			if (groupName != null && groupDescription != null) {
				// Args:	      group=<groupId> groupName=<name> groupDescription=<description>            <= create a new group
				loggingContext.setServiceName("AC:PAP.createGroup");

				String unescapedName = URLDecoder.decode(groupName, "UTF-8");
				String unescapedDescription = URLDecoder.decode(groupDescription, "UTF-8");
				PolicyDBDaoTransaction newGroupTransaction = policyDBDao.getNewTransaction();
				try {					
					newGroupTransaction.createGroup(PolicyDBDao.createNewPDPGroupId(unescapedName), unescapedName, unescapedDescription,"XACMLPapServlet.doACPost");
					papEngine.newGroup(unescapedName, unescapedDescription);
					newGroupTransaction.commitTransaction();
				} catch (Exception e) {
					newGroupTransaction.rollbackTransaction();
					PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Unable to create new group");
					loggingContext.transactionEnded();

					PolicyLogger.audit("Transaction Failed - See Error.log");
					response.sendError(500, "Unable to create new group '" + groupId + "'");
					return;
				}
				response.setStatus(HttpServletResponse.SC_NO_CONTENT);
				if (logger.isDebugEnabled()) {
					logger.debug("New Group '" + groupId + "' created");
				}
				// tell the Admin Consoles there is a change
				notifyAC();
				// new group by definition has no PDPs, so no need to notify them of changes
				loggingContext.transactionEnded();
				PolicyLogger.audit("Transaction Failed - See Error.log");
				auditLogger.info("Success");
				PolicyLogger.audit("Transaction Ended Successfully");
				return;
			}

			// for all remaining POST operations the group must exist before the operation can be done
			EcompPDPGroup group = papEngine.getGroup(groupId);
			if (group == null) {
				String message = "Unknown groupId '" + groupId + "'";
				PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
				loggingContext.transactionEnded();

				PolicyLogger.audit("Transaction Failed - See Error.log");
				if (apiflag!=null){
					response.addHeader("error", "unknownGroupId");
					response.addHeader("operation", "push");
					response.addHeader("message", message);
					response.setStatus(HttpServletResponse.SC_NOT_FOUND);
				} else {
					response.sendError(HttpServletResponse.SC_NOT_FOUND, message);
				}
				return;
			}

			// determine the operation needed based on the parameters in the request
			if (request.getParameter("policyId") != null) {
				//	Args:        group=<groupId> policy=<policyId>		<= copy file
				// copy a policy from the request contents into a file in the group's directory on this machine
				if(apiflag!=null){
					loggingContext.setServiceName("PolicyEngineAPI:PAP.postPolicy");
				} else {
					loggingContext.setServiceName("AC:PAP.postPolicy");
				}

				String policyId = request.getParameter("policyId");
				PolicyDBDaoTransaction addPolicyToGroupTransaction = policyDBDao.getNewTransaction();
				try {
					InputStream is = null;
					if (apiflag != null){
						// get the request content into a String if the request is from API 
						String json = null;
						// read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
						java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
						scanner.useDelimiter("\\A");
						json =  scanner.hasNext() ? scanner.next() : "";
						scanner.close();
						logger.info("JSON request from API: " + json);

						// convert Object sent as JSON into local object
						ObjectMapper mapper = new ObjectMapper();

						Object objectFromJSON = mapper.readValue(json, StdPAPPolicy.class);

						StdPAPPolicy policy = (StdPAPPolicy) objectFromJSON;

						is = new FileInputStream(new File(policy.getLocation()));
					} else {
						is = request.getInputStream();

					}

					addPolicyToGroupTransaction.addPolicyToGroup(group.getId(), policyId,"XACMLPapServlet.doACPost");
					((StdPDPGroup) group).copyPolicyToFile(policyId, is);
					addPolicyToGroupTransaction.commitTransaction();

				} catch (Exception e) {
					addPolicyToGroupTransaction.rollbackTransaction();
					String message = "Policy '" + policyId + "' not copied to group '" + groupId +"': " + e;
					PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " " + message);
					loggingContext.transactionEnded();

					PolicyLogger.audit("Transaction Failed - See Error.log");

					if (apiflag!=null){
						response.addHeader("error", "policyCopyError");
						response.addHeader("message", message);
						response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
					} else {
						response.sendError(500, message);
					}
					return;
				}

				// policy file copied ok and the Group was updated on the PDP
				response.setStatus(HttpServletResponse.SC_NO_CONTENT);
				response.addHeader("operation", "push");
				response.addHeader("policyId", policyId);
				response.addHeader("groupId", groupId);
				if (logger.isDebugEnabled()) {
					logger.debug("policy '" + policyId + "' copied to directory for group '" + groupId + "'");
				}

				loggingContext.transactionEnded();
				auditLogger.info("Success");
				PolicyLogger.audit("Transaction Ended Successfully");
				return;

			} else if (request.getParameter("default") != null) {
				// Args:       group=<groupId> default=true               <= make default
				// change the current default group to be the one identified in the request.
				loggingContext.setServiceName("AC:PAP.setDefaultGroup");
				//
				// This is a POST operation rather than a PUT "update group" because of the side-effect that the current default group is also changed.
				// It should never be the case that multiple groups are currently marked as the default, but protect against that anyway.
				PolicyDBDaoTransaction setDefaultGroupTransaction = policyDBDao.getNewTransaction();
				try {
					setDefaultGroupTransaction.changeDefaultGroup(group, "XACMLPapServlet.doACPost");
					papEngine.SetDefaultGroup(group);
					setDefaultGroupTransaction.commitTransaction();
				} catch (Exception e) {
					setDefaultGroupTransaction.rollbackTransaction();
					PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Unable to set group");
					loggingContext.transactionEnded();

					PolicyLogger.audit("Transaction Failed - See Error.log");
					response.sendError(500, "Unable to set group '" + groupId + "' to default");
					return;
				}

				response.setStatus(HttpServletResponse.SC_NO_CONTENT);
				if (logger.isDebugEnabled()) {
					logger.debug("Group '" + groupId + "' set to be default");
				}
				// Notify the Admin Consoles that something changed
				// For now the AC cannot handle anything more detailed than the whole set of PDPGroups, so just notify on that
				//TODO - Future: FIGURE OUT WHAT LEVEL TO NOTIFY: 2 groups or entire set - currently notify AC to update whole configuration of all groups
				notifyAC();
				// This does not affect any PDPs in the existing groups, so no need to notify them of this change
				loggingContext.transactionEnded();
				auditLogger.info("Success");
				PolicyLogger.audit("Transaction Ended Successfully");
				return;

			} else if (request.getParameter("pdpId") != null) {
				doACPostTransaction = policyDBDao.getNewTransaction();
				// Args:       group=<groupId> pdpId=<pdpId>               <= move PDP to group
				loggingContext.setServiceName("AC:PAP.movePDP");

				String pdpId = request.getParameter("pdpId");
				EcompPDP pdp = papEngine.getPDP(pdpId);

				EcompPDPGroup originalGroup = papEngine.getPDPGroup((EcompPDP) pdp);
				try{
					doACPostTransaction.movePdp(pdp, group, "XACMLPapServlet.doACPost");
				}catch(Exception e){	
					PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", 
							" Error while moving pdp in the database: "
									+"pdp="+pdp.getId()+",to group="+group.getId());
					throw new PAPException(e.getMessage());
				}
				papEngine.movePDP((EcompPDP) pdp, group);

				response.setStatus(HttpServletResponse.SC_NO_CONTENT);
				if (logger.isDebugEnabled()) {
					logger.debug("PDP '" + pdp.getId() +"' moved to group '" + group.getId() + "' set to be default");
				}

				// update the status of both the original group and the new one
				((StdPDPGroup)originalGroup).resetStatus();
				((StdPDPGroup)group).resetStatus();

				// Notify the Admin Consoles that something changed
				// For now the AC cannot handle anything more detailed than the whole set of PDPGroups, so just notify on that
				notifyAC();
				// Need to notify the PDP that it's config may have changed
				pdpChanged(pdp);
				doACPostTransaction.commitTransaction();
				loggingContext.transactionEnded();
				auditLogger.info("Success");
				PolicyLogger.audit("Transaction Ended Successfully");
				return;


			}
		} catch (PAPException e) {
			if(doACPostTransaction != null){
				doACPostTransaction.rollbackTransaction();
			}
			PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC POST exception");
			loggingContext.transactionEnded();

			PolicyLogger.audit("Transaction Failed - See Error.log");
			response.sendError(500, e.getMessage());
			return;
		}
	}

	/**
	 * Requests from the Admin Console to create new items or update existing ones
	 * 
	 * @param request
	 * @param response
	 * @param groupId
	 * @param loggingContext 
	 * @throws ServletException
	 * @throws IOException
	 */
	private void doACPut(HttpServletRequest request, HttpServletResponse response, String groupId, ECOMPLoggingContext loggingContext) throws ServletException, IOException {
		PolicyDBDaoTransaction acPutTransaction = policyDBDao.getNewTransaction();
		try {


			// for PUT operations the group may or may not need to exist before the operation can be done
			EcompPDPGroup group = papEngine.getGroup(groupId);

			// determine the operation needed based on the parameters in the request

			// for remaining operations the group must exist before the operation can be done
			if (group == null) {
				String message = "Unknown groupId '" + groupId + "'";
				PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
				loggingContext.transactionEnded();

				PolicyLogger.audit("Transaction Failed - See Error.log");
				response.sendError(HttpServletResponse.SC_NOT_FOUND, message);
				return;
			}
			if (request.getParameter("policy") != null) {
				//        group=<groupId> policy=<policyId> contents=policy file               <= Create new policy file in group dir, or replace it if it already exists (do not touch properties)
				loggingContext.setServiceName("AC:PAP.putPolicy");
				PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " PARTIALLY IMPLEMENTED!!!  ACTUAL CHANGES SHOULD BE MADE BY PAP SERVLET!!! ");
				response.setStatus(HttpServletResponse.SC_NO_CONTENT);
				loggingContext.transactionEnded();
				PolicyLogger.audit("Transaction Failed - See Error.log");
				auditLogger.info("Success");
				PolicyLogger.audit("Transaction Ended Successfully");
				return;
			} else if (request.getParameter("pdpId") != null) {
				// ARGS:        group=<groupId> pdpId=<pdpId/URL>          <= create a new PDP or Update an Existing one

				String pdpId = request.getParameter("pdpId");
				if (papEngine.getPDP(pdpId) == null) {
					loggingContext.setServiceName("AC:PAP.createPDP");
				} else {
					loggingContext.setServiceName("AC:PAP.updatePDP");
				}

				// get the request content into a String
				String json = null;
				// read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
				java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
				scanner.useDelimiter("\\A");
				json =  scanner.hasNext() ? scanner.next() : "";
				scanner.close();
				logger.info("JSON request from AC: " + json);

				// convert Object sent as JSON into local object
				ObjectMapper mapper = new ObjectMapper();

				Object objectFromJSON = mapper.readValue(json, StdPDP.class);

				if (pdpId == null ||
						objectFromJSON == null ||
						! (objectFromJSON instanceof StdPDP) ||
						((StdPDP)objectFromJSON).getId() == null ||
						! ((StdPDP)objectFromJSON).getId().equals(pdpId)) {
					PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " PDP new/update had bad input. pdpId=" + pdpId + " objectFromJSON="+objectFromJSON);
					loggingContext.transactionEnded();

					PolicyLogger.audit("Transaction Failed - See Error.log");
					response.sendError(500, "Bad input, pdpid="+pdpId+" object="+objectFromJSON);
				}
				StdPDP pdp = (StdPDP) objectFromJSON;

				if (papEngine.getPDP(pdpId) == null) {
					// this is a request to create a new PDP object
					try{
						acPutTransaction.addPdpToGroup(pdp.getId(), group.getId(), pdp.getName(), pdp.getDescription(), pdp.getJmxPort(),"XACMLPapServlet.doACPut");
					} catch(Exception e){
						PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while adding pdp to group in the database: "
								+"pdp="+pdp.getId()+",to group="+group.getId());
						throw new PAPException(e.getMessage());
					}
					papEngine.newPDP(pdp.getId(), group, pdp.getName(), pdp.getDescription(), pdp.getJmxPort());
				} else {
					try{
						acPutTransaction.updatePdp(pdp, "XACMLPapServlet.doACPut");
					} catch(Exception e){
						PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while updating pdp in the database: "
								+"pdp="+pdp.getId());
						throw new PAPException(e.getMessage());
					}
					// this is a request to update the pdp
					papEngine.updatePDP(pdp);
				}

				response.setStatus(HttpServletResponse.SC_NO_CONTENT);
				if (logger.isDebugEnabled()) {
					logger.debug("PDP '" + pdpId + "' created/updated");
				}

				// adjust the group's state including the new PDP
				((StdPDPGroup)group).resetStatus();

				// tell the Admin Consoles there is a change
				notifyAC();
				// this might affect the PDP, so notify it of the change
				pdpChanged(pdp);
				acPutTransaction.commitTransaction();
				loggingContext.transactionEnded();
				auditLogger.info("Success");
				PolicyLogger.audit("Transaction Ended Successfully");
				return;
			} else if (request.getParameter("pipId") != null) {
				//                group=<groupId> pipId=<pipEngineId> contents=pip properties              <= add a PIP to pip config, or replace it if it already exists (lenient operation) 
				loggingContext.setServiceName("AC:PAP.putPIP");
				PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED");
				loggingContext.transactionEnded();

				PolicyLogger.audit("Transaction Failed - See Error.log");
				response.sendError(HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
				return;
			} else {
				// Assume that this is an update of an existing PDP Group
				// ARGS:        group=<groupId>         <= Update an Existing Group
				loggingContext.setServiceName("AC:PAP.updateGroup");

				// get the request content into a String
				String json = null;
				// read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
				java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
				scanner.useDelimiter("\\A");
				json =  scanner.hasNext() ? scanner.next() : "";
				scanner.close();
				logger.info("JSON request from AC: " + json);

				// convert Object sent as JSON into local object
				ObjectMapper mapper = new ObjectMapper();

				Object objectFromJSON  = mapper.readValue(json, StdPDPGroup.class);

				if (objectFromJSON == null ||
						! (objectFromJSON instanceof StdPDPGroup) ||
						! ((StdPDPGroup)objectFromJSON).getId().equals(group.getId())) {
					PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Group update had bad input. id=" + group.getId() + " objectFromJSON="+objectFromJSON);
					loggingContext.transactionEnded();

					PolicyLogger.audit("Transaction Failed - See Error.log");
					response.sendError(500, "Bad input, id="+group.getId() +" object="+objectFromJSON);
				}

				// The Path on the PAP side is not carried on the RESTful interface with the AC
				// (because it is local to the PAP)
				// so we need to fill that in before submitting the group for update
				((StdPDPGroup)objectFromJSON).setDirectory(((StdPDPGroup)group).getDirectory());

				try{
					acPutTransaction.updateGroup((StdPDPGroup)objectFromJSON, "XACMLPapServlet.doACPut");
				} catch(Exception e){
					PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " Error while updating group in the database: "
							+"group="+group.getId());
					throw new PAPException(e.getMessage());
				}
				papEngine.updateGroup((StdPDPGroup)objectFromJSON);


				response.setStatus(HttpServletResponse.SC_NO_CONTENT);
				if (logger.isDebugEnabled()) {
					logger.debug("Group '" + group.getId() + "' updated");
				}
				acPutTransaction.commitTransaction();
				// tell the Admin Consoles there is a change
				notifyAC();
				// Group changed, which might include changing the policies
				groupChanged(group);

				loggingContext.transactionEnded();
				auditLogger.info("Success");
				PolicyLogger.audit("Transaction Ended Successfully");
				return;
			}
		} catch (PAPException e) {
			acPutTransaction.rollbackTransaction();
			PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC PUT exception");
			loggingContext.transactionEnded();

			PolicyLogger.audit("Transaction Failed - See Error.log");
			response.sendError(500, e.getMessage());
			return;
		}
	}

	/**
	 * Requests from the Admin Console to delete/remove items
	 * 
	 * @param request
	 * @param response
	 * @param groupId
	 * @param loggingContext 
	 * @throws ServletException
	 * @throws IOException
	 */
	private void doACDelete(HttpServletRequest request, HttpServletResponse response, String groupId, ECOMPLoggingContext loggingContext) throws ServletException, IOException {

		//This is temporary code to allow deletes to propagate to the database since delete is not implemented
		String isDeleteNotify = request.getParameter("isDeleteNotify");
		if(isDeleteNotify != null){
			String policyToDelete = request.getParameter("policyToDelete");
			try{
				policyToDelete = URLDecoder.decode(policyToDelete,"UTF-8");
			} catch(UnsupportedEncodingException e){
				PolicyLogger.error("Unsupported URL encoding of policyToDelete (UTF-8");
				response.sendError(500,"policyToDelete encoding not supported");
				return;
			}
			PolicyDBDaoTransaction deleteTransaction = policyDBDao.getNewTransaction();
			try{
				deleteTransaction.deletePolicy(policyToDelete);
			} catch(Exception e){
				deleteTransaction.rollbackTransaction();
				response.sendError(500,"deleteTransaction.deleteTransaction(policyToDelete) "
						+ "\nfailure with the following exception: " + e);
				return;
			}
			deleteTransaction.commitTransaction();
			response.setStatus(HttpServletResponse.SC_OK);
			return;
		}
		PolicyDBDaoTransaction removePdpOrGroupTransaction = policyDBDao.getNewTransaction();
		try {
			// for all DELETE operations the group must exist before the operation can be done
			loggingContext.setServiceName("AC:PAP.delete");
			EcompPDPGroup group = papEngine.getGroup(groupId);
			if (group == null) {
				String message = "Unknown groupId '" + groupId + "'";
				PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
				loggingContext.transactionEnded();

				PolicyLogger.audit("Transaction Failed - See Error.log");
				response.sendError(HttpServletResponse.SC_NOT_FOUND, "Unknown groupId '" + groupId +"'");
				return;
			}


			// determine the operation needed based on the parameters in the request
			if (request.getParameter("policy") != null) {
				//        group=<groupId> policy=<policyId>  [delete=<true|false>]       <= delete policy file from group
				loggingContext.setServiceName("AC:PAP.deletePolicy");
				PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED");
				//DATABASE so can policies not be deleted? or doesn't matter maybe as long as this gets called
				loggingContext.transactionEnded();

				PolicyLogger.audit("Transaction Failed - See Error.log");
				response.sendError(HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
				return;
			} else if (request.getParameter("pdpId") != null) {
				// ARGS:        group=<groupId> pdpId=<pdpId>                  <= delete PDP 
				String pdpId = request.getParameter("pdpId");
				EcompPDP pdp = papEngine.getPDP(pdpId);

				try{
					removePdpOrGroupTransaction.removePdpFromGroup(pdp.getId(),"XACMLPapServlet.doACDelete");
				} catch(Exception e){
					throw new PAPException();
				}
				papEngine.removePDP((EcompPDP) pdp);

				// adjust the status of the group, which may have changed when we removed this PDP
				((StdPDPGroup)group).resetStatus();

				response.setStatus(HttpServletResponse.SC_NO_CONTENT);
				notifyAC();

				// update the PDP and tell it that it has NO Policies (which prevents it from serving PEP Requests)
				pdpChanged(pdp);
				removePdpOrGroupTransaction.commitTransaction();
				loggingContext.transactionEnded();
				auditLogger.info("Success");
				PolicyLogger.audit("Transaction Ended Successfully");
				return;
			} else if (request.getParameter("pipId") != null) {
				//        group=<groupId> pipId=<pipEngineId> <= delete PIP config for given engine

				loggingContext.setServiceName("AC:PAP.deletePIPConfig");
				PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED");
				loggingContext.transactionEnded();

				PolicyLogger.audit("Transaction Failed - See Error.log");
				response.sendError(HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
				return;
			} else {
				// ARGS:      group=<groupId> movePDPsToGroupId=<movePDPsToGroupId>            <= delete a group and move all its PDPs to the given group
				String moveToGroupId = request.getParameter("movePDPsToGroupId");
				EcompPDPGroup moveToGroup = null;
				if (moveToGroupId != null) {
					moveToGroup = papEngine.getGroup(moveToGroupId);
				}

				// get list of PDPs in the group being deleted so we can notify them that they got changed
				Set<EcompPDP> movedPDPs = new HashSet<EcompPDP>();
				movedPDPs.addAll(group.getEcompPdps());

				// do the move/remove
				try{
					removePdpOrGroupTransaction.deleteGroup(group, moveToGroup,"XACMLPapServlet.doACDelete");
				} catch(Exception e){
					PolicyLogger.error(MessageCodes.ERROR_UNKNOWN, e, "XACMLPapServlet", " Failed to delete PDP Group. Exception");
					e.printStackTrace();
					throw new PAPException(e.getMessage());
				}
				papEngine.removeGroup(group, moveToGroup);

				response.setStatus(HttpServletResponse.SC_NO_CONTENT);
				notifyAC();
				// notify any PDPs in the removed set that their config may have changed
				for (EcompPDP pdp : movedPDPs) {
					pdpChanged(pdp);
				}
				removePdpOrGroupTransaction.commitTransaction();
				loggingContext.transactionEnded();
				auditLogger.info("Success");
				PolicyLogger.audit("Transaction Ended Successfully");
				return;
			}

		} catch (PAPException e) {
			removePdpOrGroupTransaction.rollbackTransaction();
			PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC DELETE exception");
			loggingContext.transactionEnded();

			PolicyLogger.audit("Transaction Failed - See Error.log");
			PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Exception in request processing");
			response.sendError(500, e.getMessage());
			return;
		}
	}


	/**
	 * Requests from the API to delete/remove items
	 * 
	 * @param request
	 * @param response
	 * @param groupId
	 * @param loggingContext 
	 * @throws ServletException
	 * @throws IOException
	 */
	private void doAPIDeleteFromPAP(HttpServletRequest request, HttpServletResponse response, ECOMPLoggingContext loggingContext) throws ServletException, IOException {

		// get the request content into a String
		String json = null;

		// read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
		java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
		scanner.useDelimiter("\\A");
		json =  scanner.hasNext() ? scanner.next() : "";
		scanner.close();
		logger.info("JSON request from API: " + json);

		// convert Object sent as JSON into local object
		ObjectMapper mapper = new ObjectMapper();

		Object objectFromJSON = mapper.readValue(json, StdPAPPolicy.class);

		StdPAPPolicy policy = (StdPAPPolicy) objectFromJSON;

		String policyName = policy.getPolicyName();
		String fileSeparator = File.separator;
		policyName = policyName.replaceFirst("\\.", "\\"+fileSeparator);

		File file = getPolicyFile(policyName);
		String domain = getParentPathSubScopeDir(file);
		Boolean policyFileDeleted = false;
		Boolean configFileDeleted = false;
		Boolean policyVersionScoreDeleted = false;

		if (policy.getDeleteCondition().equalsIgnoreCase("All Versions")){

			//check for extension in policyName
			String removexmlExtension = null;
			String removeVersion = null;
			if (policyName.contains("xml")) {
				removexmlExtension = file.toString().substring(0, file.toString().lastIndexOf("."));
				removeVersion = removexmlExtension.substring(0, removexmlExtension.lastIndexOf("."));
			} else {
				removeVersion = file.toString();
			}

			File dirXML = new File(file.getParent());
			File[] listofXMLFiles = dirXML.listFiles();

			for (File files : listofXMLFiles) {
				//delete the xml files from the Repository
				if (files.isFile() && files.toString().contains(removeVersion)) {
					JPAUtils jpaUtils = null;
					try {
						jpaUtils = JPAUtils.getJPAUtilsInstance(emf);
					} catch (Exception e) {
						PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " Could not create JPAUtils instance on the PAP");
						e.printStackTrace();
						response.addHeader("error", "jpautils");
						response.addHeader("operation", "delete");
						response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
						return;
					}

					if (jpaUtils.dbLockdownIgnoreErrors()) {
						logger.warn("Policies are locked down");
						response.addHeader("operation", "delete");
						response.addHeader("lockdown", "true");
						response.setStatus(HttpServletResponse.SC_ACCEPTED);
						return;
					}

					//Propagates delete to the database 
					Boolean deletedFromDB = notifyDBofDelete(files.toString());

					if (deletedFromDB) {
						logger.info("Policy deleted from the database.  Continuing with file delete");
					} else {
						PolicyLogger.error("Failed to delete Policy from database. Aborting file delete");
						response.addHeader("error", "deleteDB");
						response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
						return;
					}

					if (files.delete()) {
						if (logger.isDebugEnabled()) {
							logger.debug("Deleted file: " + files.toString());
						}
						policyFileDeleted = true;
					} else {
						logger.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + 
								"Cannot delete the policy file in specified location: " + files.getAbsolutePath());	
						response.addHeader("error", "deleteFile");
						response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
						return;
					}

					// Get tomcat home directory for deleting config data
					logger.info("print the path:" +domain);
					String path = domain.replace('\\', '.');
					if(path.contains("/")){
						path = path.replace('/', '.');
						logger.info("print the path:" +path);
					}
					String fileName = FilenameUtils.removeExtension(file.getName());
					String removeVersionInFileName = fileName.substring(0, fileName.lastIndexOf("."));
					String fileLocation = null;

					if(CONFIG_HOME == null){
						CONFIG_HOME = getConfigHome();
					}
					if(ACTION_HOME == null){
						ACTION_HOME = getActionHome();
					}


					if (fileName != null && fileName.contains("Config_")) {
						fileLocation = CONFIG_HOME;
					} else if (fileName != null && fileName.contains("Action_")) {
						fileLocation = ACTION_HOME;
					}

					if (logger.isDebugEnabled()) {
						logger.debug("Attempting to rename file from the location: "+ fileLocation);
					}

					if(!files.toString().contains("Decision_")){
						// Get the file from the saved location
						File dir = new File(fileLocation);
						File[] listOfFiles = dir.listFiles();

						for (File file1 : listOfFiles) {
							if (file1.isFile() && file1.getName().contains( path + removeVersionInFileName)) {
								try {
									if (file1.delete()) {
										if (logger.isDebugEnabled()) {
											logger.debug("Deleted file: " + file1.toString());
										}
										configFileDeleted = true;
									} else {
										logger.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + 
												"Cannot delete the configuration or action body file in specified location: " + file1.getAbsolutePath());	
										response.addHeader("error", "deleteConfig");
										response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
										return;
									}
								} catch (Exception e) {
									PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " Failed to Delete file");	
								}
							}
							configFileDeleted = true;
						}
					} else {
						configFileDeleted = true;
					}

					//Delete the Policy from Database Policy Version table
					if (policyFileDeleted && configFileDeleted) {
						String removeExtension = domain + removeVersionInFileName;
						EntityManager em = (EntityManager) emf.createEntityManager();

						Query getPolicyVersion = em.createQuery("Select p from PolicyVersion p where p.policyName=:pname");
						Query getPolicyScore = em.createQuery("Select p from PolicyScore p where p.PolicyName=:pname");
						getPolicyVersion.setParameter("pname", removeExtension);
						getPolicyScore.setParameter("pname", removeExtension);

						@SuppressWarnings("rawtypes")
						List pvResult = getPolicyVersion.getResultList();
						@SuppressWarnings("rawtypes")
						List psResult = getPolicyScore.getResultList();


						try{
							em.getTransaction().begin();
							if (!pvResult.isEmpty()) {
								for (Object id : pvResult) {
									PolicyVersion versionEntity = (PolicyVersion)id;	
									em.remove(versionEntity);
								}
							} else {
								logger.debug("No PolicyVersion record found in database.");
							}

							if (!psResult.isEmpty()) {				
								for (Object id : psResult) {
									PolicyScore scoreEntity = (PolicyScore)id;	
									em.remove(scoreEntity);
								}
							} else {
								PolicyLogger.error("No PolicyScore record found in database.");
							}
							em.getTransaction().commit();
							policyVersionScoreDeleted = true;
						}catch(Exception e){
							em.getTransaction().rollback();
							PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR");
							response.addHeader("error", "deleteDB");
							response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
							return;
						} finally {
							em.close();
						}
					}
				}
			}
			//If Specific version is requested for delete
		} else if (policy.getDeleteCondition().equalsIgnoreCase("Current Version")) {
			String policyScoreName = domain + file.getName().toString();
			String policyVersionName = policyScoreName.substring(0, policyScoreName.indexOf("."));
			String versionExtension = policyScoreName.substring(policyScoreName.indexOf(".")+1);
			String removexmlExtension = file.toString().substring(0, file.toString().lastIndexOf("."));
			String getVersion = removexmlExtension.substring(removexmlExtension.indexOf(".")+1);
			String removeVersion = removexmlExtension.substring(0, removexmlExtension.lastIndexOf("."));


			JPAUtils jpaUtils = null;
			try {
				jpaUtils = JPAUtils.getJPAUtilsInstance(emf);
			} catch (Exception e) {
				PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " Could not create JPAUtils instance on the PAP");
				e.printStackTrace();
				response.addHeader("error", "jpautils");
				response.addHeader("operation", "delete");
				response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
				return;
			}

			if (jpaUtils.dbLockdownIgnoreErrors()) {
				logger.warn("Policies are locked down");
				response.addHeader("lockdown", "true");
				response.addHeader("operation", "delete");
				response.setStatus(HttpServletResponse.SC_ACCEPTED);
				return;
			}

			//Propagates delete to the database 
			Boolean deletedFromDB = notifyDBofDelete(file.toString());

			if (deletedFromDB) {
				logger.info("Policy deleted from the database.  Continuing with file delete");
			} else {
				PolicyLogger.error("Failed to delete Policy from database. Aborting file delete");
				response.addHeader("error", "deleteDB");
				response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
				return;
			}

			if (file.delete()) {
				if (logger.isDebugEnabled()) {
					logger.debug("Deleted file: " + file.toString());
				}
				policyFileDeleted = true;
			} else {
				logger.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + 
						"Cannot delete the policy file in specified location: " + file.getAbsolutePath());	
				response.addHeader("error", "deleteFile");
				response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
				return;
			}

			// Get tomcat home directory for deleting config data
			logger.info("print the path:" +domain);
			String path = domain.replace('\\', '.');
			if(path.contains("/")){
				path = path.replace('/', '.');
				logger.info("print the path:" +path);
			}
			String fileName = FilenameUtils.removeExtension(file.getName());
			String removeVersionInFileName = fileName.substring(0, fileName.lastIndexOf("."));
			String fileLocation = null;

			if(CONFIG_HOME == null){
				CONFIG_HOME = getConfigHome();
			}
			if(ACTION_HOME == null){
				ACTION_HOME = getActionHome();
			}


			if (fileName != null && fileName.contains("Config_")) {
				fileLocation = CONFIG_HOME;
			} else if (fileName != null && fileName.contains("Action_")) {
				fileLocation = ACTION_HOME;
			}

			if (logger.isDebugEnabled()) {
				logger.debug("Attempting to rename file from the location: "+ fileLocation);
			}

			if(!file.toString().contains("Decision_")){
				// Get the file from the saved location
				File dir = new File(fileLocation);
				File[] listOfFiles = dir.listFiles();

				for (File file1 : listOfFiles) {
					if (file1.isFile() && file1.getName().contains( path + fileName)) {
						try {
							if (file1.delete()) {
								if (logger.isDebugEnabled()) {
									logger.debug("Deleted file: " + file1.toString());
								}
								configFileDeleted = true;
							} else {
								logger.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + 
										"Cannot delete the configuration or action body file in specified location: " + file1.getAbsolutePath());	
								response.addHeader("error", "deleteConfig");
								response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
								return;
							}
						} catch (Exception e) {
							PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " Failed to Delete file");		
						}
					}
					configFileDeleted = true;
				}
			} else {
				configFileDeleted = true;
			}

			//Delete the Policy from Database and set Active Version based on the deleted file.
			int highestVersion = 0;
			if (policyFileDeleted && configFileDeleted) {
				String removeExtension = domain + removeVersionInFileName;
				EntityManager em = (EntityManager) emf.createEntityManager();

				Query getPolicyVersion = em.createQuery("Select p from PolicyVersion p where p.policyName=:pname");
				Query getPolicyScore = em.createQuery("Select p from PolicyScore p where p.PolicyName=:pname");
				getPolicyVersion.setParameter("pname", removeExtension);
				getPolicyScore.setParameter("pname", removeExtension);

				@SuppressWarnings("rawtypes")
				List pvResult = getPolicyVersion.getResultList();
				@SuppressWarnings("rawtypes")
				List psResult = getPolicyScore.getResultList();


				try{
					em.getTransaction().begin();
					if (!pvResult.isEmpty()) {
						PolicyVersion versionEntity = null;
						for (Object id : pvResult) {
							versionEntity = (PolicyVersion)id;
							if(versionEntity.getPolicyName().equals(removeExtension)){
								highestVersion = versionEntity.getHigherVersion();
								em.remove(versionEntity);
							}
						}

						int i = 0;
						int version = Integer.parseInt(getVersion);

						if(version == highestVersion) {
							for(i = highestVersion; i>=1; i--){
								highestVersion = highestVersion - 1;
								String dirXML = removeVersion + "." + highestVersion + ".xml";
								File filenew = new File(dirXML);

								if(filenew.exists()){
									break;
								}

							}
						}

						versionEntity.setPolicyName(removeExtension);
						versionEntity.setHigherVersion(highestVersion);
						versionEntity.setActiveVersion(highestVersion);
						versionEntity.setModifiedBy("API");	

						em.persist(versionEntity);

					} else {
						logger.debug("No PolicyVersion record found in database.");
					}

					if (!psResult.isEmpty()) {				
						for (Object id : psResult) {
							PolicyScore scoreEntity = (PolicyScore)id;	
							if(scoreEntity.getPolicyName().equals(policyVersionName) && scoreEntity.getVersionExtension().equals(versionExtension)){
								em.remove(scoreEntity);
							}
						}
					} else {
						PolicyLogger.error("No PolicyScore record found in database.");
					}
					em.getTransaction().commit();
					policyVersionScoreDeleted = true;
				}catch(Exception e){
					em.getTransaction().rollback();
					PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR");
					response.addHeader("error", "deleteDB");
					response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
					return;
				} finally {
					em.close();
				}
			}
		}

		if (policyFileDeleted && configFileDeleted && policyVersionScoreDeleted) {
			response.setStatus(HttpServletResponse.SC_OK);
			response.addHeader("successMapKey", "success");
			response.addHeader("operation", "delete");
			return;				
		} else {
			PolicyLogger.error(MessageCodes.ERROR_UNKNOWN + "Failed to delete the policy for an unknown reason.  Check the file system and other logs for further information.");

			response.addHeader("error", "unknown");
			response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
			return;
		}

	}

	private void doImportMicroServicePut(HttpServletRequest request, HttpServletResponse response) {
		String importServiceCreation = request.getParameter("importService");;
		String fileName = request.getParameter("fileName");
		String version = request.getParameter("version");
		String serviceName = request.getParameter("serviceName");
		CreateNewMicroSerivceModel newMS = null;

		String randomID = UUID.randomUUID().toString();

		if ( importServiceCreation != null  || fileName != null) {
			File extracDir = new File("ExtractDir");
			if (!extracDir.exists()){
				extracDir.mkdirs();
			}
			if (fileName.contains(".xmi")){
				// get the request content into a String
				String xmi = null;

				// read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
				java.util.Scanner scanner;
				try {
					scanner = new java.util.Scanner(request.getInputStream());
					scanner.useDelimiter("\\A");
					xmi =  scanner.hasNext() ? scanner.next() : "";
					scanner.close();
				} catch (IOException e1) {
					logger.error("Error in reading in file from API call");
					return;
				}

				logger.info("XML request from API for import new Service");

				//Might need to seperate by , for more than one file. 

				try (Writer writer = new BufferedWriter(new OutputStreamWriter(
						new FileOutputStream("ExtractDir" + File.separator + randomID+".xmi"), "utf-8"))) {
					writer.write(xmi);
				} catch (IOException e) {
					logger.error("Error in reading in file from API call");
					return;
				}
			}else{ 
				try {	
					InputStream inputStream = request.getInputStream() ; 

					FileOutputStream outputStream = new FileOutputStream("ExtractDir" + File.separator + randomID+".zip"); 
					byte[] buffer = new byte[4096];
					int bytesRead = -1 ; 
					while ((bytesRead = inputStream.read(buffer)) != -1) { 
						outputStream.write(buffer, 0, bytesRead) ; 
					} 

					outputStream.close() ; 
					inputStream.close() ;

				} catch (IOException e) {
					logger.error("Error in reading in Zip File from API call");
					return;
				}
			}

			newMS =  new CreateNewMicroSerivceModel(fileName, serviceName, "API IMPORT", version, randomID);
			Map<String, String> successMap = newMS.addValuesToNewModel();
			if (successMap.containsKey("success")) {
				successMap.clear();
				successMap = newMS.saveImportService();
			}


			// create the policy and return a response to the PAP-ADMIN		    
			if (successMap.containsKey("success")) {							
				response.setStatus(HttpServletResponse.SC_OK);								
				response.addHeader("successMapKey", "success");								
				response.addHeader("operation", "import");
				response.addHeader("service", serviceName);
			} else if (successMap.containsKey("DBError")) {
				if (successMap.get("DBError").contains("EXISTS")){
					response.setStatus(HttpServletResponse.SC_CONFLICT);
					response.addHeader("service", serviceName);
					response.addHeader("error", "modelExistsDB");
				}else{
					response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
					response.addHeader("error", "importDB");
				}
				response.addHeader("operation", "import");
				response.addHeader("service", serviceName);
			}else if (successMap.get("error").contains("MISSING")){
				response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
				response.addHeader("error", "missing");	
				response.addHeader("operation", "import");
				response.addHeader("service", serviceName);
			}
		}
	}

	private void doAPIDeleteFromPDP(HttpServletRequest request, HttpServletResponse response, ECOMPLoggingContext loggingContext) throws ServletException, IOException {

		String policyName = request.getParameter("policyName");
		String groupId = request.getParameter("groupId");
		String responseString = null;

		// for PUT operations the group may or may not need to exist before the operation can be done
		EcompPDPGroup group = null;
		try {
			group = papEngine.getGroup(groupId);
		} catch (PAPException e) {
			logger.error("Exception occured While PUT operation is performing for PDP Group"+e);
		}

		if (group == null) {
			String message = "Unknown groupId '" + groupId + "'";
			PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
			loggingContext.transactionEnded();

			PolicyLogger.audit("Transaction Failed - See Error.log");
			response.addHeader("error", "UnknownGroup");
			response.sendError(HttpServletResponse.SC_NOT_FOUND, message);
			return;
		} else {

			loggingContext.setServiceName("API:PAP.deletPolicyFromPDPGroup");

			if (policyName.contains("xml")) {
				logger.debug("The full file name including the extension was provided for policyName.. continue.");
			} else {
				String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid policyName... "
						+ "policyName must be the full name of the file to be deleted including version and extension";
				PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Invalid policyName... "
						+ "policyName must be the full name of the file to be deleted including version and extension");
				response.addHeader("error", "invalidPolicyName");
				response.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
				return;
			}
			RemoveGroupPolicy removePolicy = new RemoveGroupPolicy((StdPDPGroup) group);

			PDPPolicy policy =  group.getPolicy(policyName);

			if (policy != null) {
				removePolicy.prepareToRemove(policy);
				EcompPDPGroup updatedGroup = removePolicy.getUpdatedObject();
				responseString = deletePolicyFromPDPGroup(updatedGroup, loggingContext);
			} else {
				String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Policy does not exist on the PDP.";
				PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Policy does not exist on the PDP.");
				response.addHeader("error", "noPolicyExist");
				response.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
				return;
			}			
		}

		if (responseString.equals("success")) {
			logger.info("Policy successfully deleted!");
			PolicyLogger.audit("Policy successfully deleted!");
			response.setStatus(HttpServletResponse.SC_OK);
			response.addHeader("successMapKey", "success");
			response.addHeader("operation", "delete");
			return;		
		} else if (responseString.equals("No Group")) {
			String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Group update had bad input.";
			PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Group update had bad input.");
			response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			response.addHeader("error", "groupUpdate");
			response.addHeader("message", message);
			return;	
		} else if (responseString.equals("DB Error")) {
			PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " Error while updating group in the database");
			response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			response.addHeader("error", "deleteDB");
			return;
		} else {
			PolicyLogger.error(MessageCodes.ERROR_UNKNOWN + " Failed to delete the policy for an unknown reason.  Check the file system and other logs for further information.");
			response.addHeader("error", "unknown");
			response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
			return;
		}

	}

	protected String getParentPathSubScopeDir(File file) {
		String domain1 = null;

		Path workspacePath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WORKSPACE), "admin");
		Path repositoryPath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_REPOSITORY));
		Path gitPath = Paths.get(workspacePath.toString(), repositoryPath.getFileName().toString());

		String policyDir = file.getAbsolutePath();
		int startIndex = policyDir.indexOf(gitPath.toString()) + gitPath.toString().length() + 1;
		policyDir = policyDir.substring(startIndex, policyDir.length());
		if(policyDir.contains("Config_")){
			domain1 = policyDir.substring(0,policyDir.indexOf("Config_"));
		}else if(policyDir.contains("Action_")){
			domain1 = policyDir.substring(0,policyDir.indexOf("Action_"));	
		}else{
			domain1 = policyDir.substring(0,policyDir.indexOf("Decision_"));	
		}
		logger.info("print the main domain value"+policyDir);

		return domain1;
	}

	/*
	 * method to delete the policy from the database and return notification when using API
	 */
	private Boolean notifyDBofDelete (String policyToDelete) {
		//String policyToDelete = request.getParameter("policyToDelete");
		try{
			policyToDelete = URLDecoder.decode(policyToDelete,"UTF-8");
		} catch(UnsupportedEncodingException e){
			PolicyLogger.error("Unsupported URL encoding of policyToDelete (UTF-8)");
			return false;
		}
		PolicyDBDaoTransaction deleteTransaction = policyDBDao.getNewTransaction();
		try{
			deleteTransaction.deletePolicy(policyToDelete);
		} catch(Exception e){
			deleteTransaction.rollbackTransaction();
			return false;
		}
		deleteTransaction.commitTransaction();
		return true;
	}

	private String deletePolicyFromPDPGroup (EcompPDPGroup group, ECOMPLoggingContext loggingContext){
		PolicyDBDaoTransaction acPutTransaction = policyDBDao.getNewTransaction();

		String response = null;
		loggingContext.setServiceName("API:PAP.updateGroup");

		EcompPDPGroup existingGroup = null;
		try {
			existingGroup = papEngine.getGroup(group.getId());
		} catch (PAPException e1) {
			logger.error("Exception occured While Deleting Policy From PDP Group"+e1);
		}

		if (group == null ||
				! (group instanceof StdPDPGroup) ||
				! (group.getId().equals(existingGroup.getId()))) {
			PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Group update had bad input. id=" + existingGroup.getId() + " objectFromJSON="+group);
			loggingContext.transactionEnded();

			PolicyLogger.audit("Transaction Failed - See Error.log");

			response = "No Group";
			return response;
		}

		// The Path on the PAP side is not carried on the RESTful interface with the AC
		// (because it is local to the PAP)
		// so we need to fill that in before submitting the group for update
		((StdPDPGroup)group).setDirectory(((StdPDPGroup)existingGroup).getDirectory());

		try{
			acPutTransaction.updateGroup(group, "XACMLPapServlet.doAPIDelete");
		} catch(Exception e){
			PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while updating group in the database: "
					+"group="+existingGroup.getId());
			response = "DB Error";
			return response;
		}

		try {
			papEngine.updateGroup(group);
		} catch (PAPException e) {
			logger.error("Exception occured While Updating PDP Groups"+e);
			response = "error in updateGroup method";
		}

		if (logger.isDebugEnabled()) {
			logger.debug("Group '" + group.getId() + "' updated");
		}

		acPutTransaction.commitTransaction();

		// Group changed, which might include changing the policies
		try {
			groupChanged(existingGroup);
		}  catch (Exception e) {
			logger.error("Exception occured in Group Change Method"+e);
			response = "error in groupChanged method";
		}

		if (response==null){
			response = "success";
			PolicyLogger.audit("Policy successfully deleted!");
			PolicyLogger.audit("Transaction Ended Successfully");
		}

		loggingContext.transactionEnded();
		PolicyLogger.audit("Transaction Ended");
		return response;
	}


	//
	// Heartbeat thread - periodically check on PDPs' status
	//

	/**
	 * Heartbeat with all known PDPs.
	 * 
	 * Implementation note:
	 * 
	 * The PDPs are contacted Sequentially, not in Parallel.
	 * 
	 * If we did this in parallel using multiple threads we would simultaneously use
	 * 		- 1 thread and
	 * 		- 1 connection
	 * for EACH PDP.
	 * This could become a resource problem since we already use multiple threads and connections for updating the PDPs
	 * when user changes occur.
	 * Using separate threads can also make it tricky dealing with timeouts on PDPs that are non-responsive.
	 * 
	 * The Sequential operation does a heartbeat request to each PDP one at a time.
	 * This has the flaw that any PDPs that do not respond will hold up the entire heartbeat sequence until they timeout.
	 * If there are a lot of non-responsive PDPs and the timeout is large-ish (the default is 20 seconds)
	 * it could take a long time to cycle through all of the PDPs.
	 * That means that this may not notice a PDP being down in a predictable time.
	 * 
	 *
	 */
	private class Heartbeat implements Runnable {
		private PAPPolicyEngine papEngine;
		private Set<EcompPDP> pdps = new HashSet<EcompPDP>();
		private int heartbeatInterval;
		private int heartbeatTimeout;

		public volatile boolean isRunning = false;

		public synchronized boolean isRunning() {
			return this.isRunning;
		}

		public synchronized void terminate() {
			this.isRunning = false;
		}

		public Heartbeat(PAPPolicyEngine papEngine2) {
			this.papEngine = papEngine2;
			this.heartbeatInterval = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_HEARTBEAT_INTERVAL, "10000"));
			this.heartbeatTimeout = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_HEARTBEAT_TIMEOUT, "10000"));
		}

		@Override
		public void run() {
			//
			// Set ourselves as running
			//
			synchronized(this) {
				this.isRunning = true;
			}
			HashMap<String, URL> idToURLMap = new HashMap<String, URL>();
			try {
				while (this.isRunning()) {
					// Wait the given time
					Thread.sleep(heartbeatInterval);

					// get the list of PDPs (may have changed since last time)
					pdps.clear();
					synchronized(papEngine) {
						try {
							for (EcompPDPGroup g : papEngine.getEcompPDPGroups()) {
								for (EcompPDP p : g.getEcompPdps()) {
									pdps.add(p);
								}
							}
						} catch (PAPException e) {
							PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", "Heartbeat unable to read PDPs from PAPEngine");
						}
					}
					//
					// Check for shutdown
					//
					if (this.isRunning() == false) {
						logger.info("isRunning is false, getting out of loop.");
						break;
					}

					// try to get the summary status from each PDP
					boolean changeSeen = false;
					for (EcompPDP pdp : pdps) {
						//
						// Check for shutdown
						//
						if (this.isRunning() == false) {
							logger.info("isRunning is false, getting out of loop.");
							break;
						}
						// the id of the PDP is its url (though we add a query parameter)
						URL pdpURL = idToURLMap.get(pdp.getId());
						if (pdpURL == null) {
							// haven't seen this PDP before
							String fullURLString = null;
							try {
								// Check PDP ID
								if(CheckPDP.validateID(pdp.getId())){
									fullURLString = pdp.getId() + "?type=hb";
									pdpURL = new URL(fullURLString);
									idToURLMap.put(pdp.getId(), pdpURL);
								}
							} catch (MalformedURLException e) {
								PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPapServlet", " PDP id '" + fullURLString + "' is not a valid URL");
								continue;
							}
						}

						// Do a GET with type HeartBeat
						String newStatus = "";

						HttpURLConnection connection = null;
						try {

							//
							// Open up the connection
							//
							connection = (HttpURLConnection)pdpURL.openConnection();
							//
							// Setup our method and headers
							//
							connection.setRequestMethod("GET");
							connection.setConnectTimeout(heartbeatTimeout);
							// Added for Authentication
							String encoding = CheckPDP.getEncoding(pdp.getId());
							if(encoding !=null){
								connection.setRequestProperty("Authorization", "Basic " + encoding);
							}
							//
							// Do the connect
							//
							connection.connect();
							if (connection.getResponseCode() == 204) {
								newStatus = connection.getHeaderField(XACMLRestProperties.PROP_PDP_HTTP_HEADER_HB);
								if (logger.isDebugEnabled()) {
									logger.debug("Heartbeat '" + pdp.getId() + "' status='" + newStatus + "'");
								}
							} else {
								// anything else is an unexpected result
								newStatus = PDPStatus.Status.UNKNOWN.toString();
								PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " Heartbeat connect response code " + connection.getResponseCode() + ": " + pdp.getId());
							}
						} catch (UnknownHostException e) {
							newStatus = PDPStatus.Status.NO_SUCH_HOST.toString();
							PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Heartbeat '" + pdp.getId() + "' NO_SUCH_HOST");
						} catch (SocketTimeoutException e) {
							newStatus = PDPStatus.Status.CANNOT_CONNECT.toString();
							PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Heartbeat '" + pdp.getId() + "' connection timeout");
						} catch (ConnectException e) {
							newStatus = PDPStatus.Status.CANNOT_CONNECT.toString();
							PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Heartbeat '" + pdp.getId() + "' cannot connect");
						} catch (Exception e) {
							newStatus = PDPStatus.Status.UNKNOWN.toString();
							PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", "Heartbeat '" + pdp.getId() + "' connect exception");
						} finally {
							// cleanup the connection
							connection.disconnect();
						}

						if ( ! pdp.getStatus().getStatus().toString().equals(newStatus)) {
							if (logger.isDebugEnabled()) {
								logger.debug("previous status='" + pdp.getStatus().getStatus()+"'  new Status='" + newStatus + "'");
							}
							try {
								setPDPSummaryStatus(pdp, newStatus);
							} catch (PAPException e) {
								PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", "Unable to set state for PDP '" + pdp.getId());
							}
							changeSeen = true;
						}

					}
					//
					// Check for shutdown
					//
					if (this.isRunning() == false) {
						logger.info("isRunning is false, getting out of loop.");
						break;
					}

					// if any of the PDPs changed state, tell the ACs to update
					if (changeSeen) {
						notifyAC();
					}

				}
			} catch (InterruptedException e) {
				PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " Heartbeat interrupted.  Shutting down");
				this.terminate();
			}
		}
	}


	//
	// HELPER to change Group status when PDP status is changed
	//
	// (Must NOT be called from a method that is synchronized on the papEngine or it may deadlock)
	//

	private void setPDPSummaryStatus(EcompPDP pdp, PDPStatus.Status newStatus) throws PAPException {
		setPDPSummaryStatus(pdp, newStatus.toString());
	}

	private void setPDPSummaryStatus(EcompPDP pdp, String newStatus) throws PAPException {
		synchronized(papEngine) {
			StdPDPStatus status = new StdPDPStatus();
			status.setStatus(PDPStatus.Status.valueOf(newStatus));
			((StdPDP)pdp).setStatus(status);

			// now adjust the group
			StdPDPGroup group = (StdPDPGroup)papEngine.getPDPGroup((EcompPDP) pdp);
			// if the PDP was just deleted it may transiently exist but not be in a group
			if (group != null) {
				group.resetStatus();
			}
		}
	}


	//
	// Callback methods telling this servlet to notify PDPs of changes made by the PAP StdEngine
	//	in the PDP group directories
	//

	@Override
	public void changed() {
		// all PDPs in all groups need to be updated/sync'd
		Set<EcompPDPGroup> groups;
		try {
			groups = papEngine.getEcompPDPGroups();
		} catch (PAPException e) {
			PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " getPDPGroups failed");
			throw new RuntimeException(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get Groups: " + e);
		}
		for (EcompPDPGroup group : groups) {
			groupChanged(group);
		}
	}

	@Override
	public void groupChanged(EcompPDPGroup group) {
		// all PDPs within one group need to be updated/sync'd
		for (EcompPDP pdp : group.getEcompPdps()) {
			pdpChanged(pdp);
		}
	}

	@Override
	public void pdpChanged(EcompPDP pdp) {
		// kick off a thread to do an event notification for each PDP.
		// This needs to be on a separate thread so that PDPs that do not respond (down, non-existent, etc)
		// do not block the PSP response to the AC, which would freeze the GUI until all PDPs sequentially respond or time-out.
		// begin - Fix to maintain requestId - including storedRequestId in UpdatePDPThread to be used later when calling PDP
		// Thread t = new Thread(new UpdatePDPThread(pdp));
		Thread t = new Thread(new UpdatePDPThread(pdp, storedRequestId));
		// end   - Fix to maintain requestId
		if(CheckPDP.validateID(pdp.getId())){
			t.start();
		}
	}

	private class UpdatePDPThread implements Runnable {
		private EcompPDP pdp;
		// begin - Fix to maintain requestId - define requestId under class to be used later when calling PDP
		private String requestId;
		// end   - Fix to maintain requestId

		// remember which PDP to notify
		public UpdatePDPThread(EcompPDP pdp) {
			this.pdp = pdp;
		}

		// begin - Fix to maintain requestId - clone UpdatePDPThread method with different method signature so to include requestId to be used later when calling PDP
		public UpdatePDPThread(EcompPDP pdp, String storedRequestId) {
			this.pdp = pdp;
			requestId = storedRequestId;
		}
		// end   - Fix to maintain requestId

		public void run() {
			// send the current configuration to one PDP
			HttpURLConnection connection = null;
			// get a new logging context for the thread
			ECOMPLoggingContext loggingContext = new ECOMPLoggingContext(baseLoggingContext);
			try {
				loggingContext.setServiceName("PAP:PDP.putConfig");
				// get a new transaction (request) ID and update the logging context.
				// begin - Fix to maintain requestId - replace unconditioned generation of new requestID so it won't be used later when calling PDP
				// If a requestId was provided, use it, otherwise generate one; post to loggingContext to be used later when calling PDP
				// UUID requestID = UUID.randomUUID();
				// loggingContext.setRequestID(requestID.toString());
				if ((requestId == null) || (requestId == "")) {
					UUID requestID = UUID.randomUUID();
					loggingContext.setRequestID(requestID.toString());
					PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (UpdatePDPThread) so we generated one:  " + loggingContext.getRequestID());
				} else {
					loggingContext.setRequestID(requestId);
					PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (UpdatePDPThread):  " + loggingContext.getRequestID());
				}
				// end   - Fix to maintain requestId
				loggingContext.transactionStarted();
				// dummy metric.log example posted below as proof of concept
				loggingContext.metricStarted();
				loggingContext.metricEnded();
				PolicyLogger.metrics("Metric example posted here - 1 of 2");
				loggingContext.metricStarted();
				loggingContext.metricEnded();
				PolicyLogger.metrics("Metric example posted here - 2 of 2");
				// dummy metric.log example posted above as proof of concept

				//
				// the Id of the PDP is its URL
				//
				if (logger.isDebugEnabled()) {
					logger.debug("creating url for id '" + pdp.getId() + "'");
				}
				//TODO - currently always send both policies and pips.  Do we care enough to add code to allow sending just one or the other?
				//TODO		(need to change "cache=", implying getting some input saying which to change)
				URL url = new URL(pdp.getId() + "?cache=all");

				//
				// Open up the connection
				//
				connection = (HttpURLConnection)url.openConnection();
				//
				// Setup our method and headers
				//
				connection.setRequestMethod("PUT");
				// Added for Authentication
				String encoding = CheckPDP.getEncoding(pdp.getId());
				if(encoding !=null){
					connection.setRequestProperty("Authorization", "Basic " + encoding);
				}
				connection.setRequestProperty("Content-Type", "text/x-java-properties");
				// begin - Fix to maintain requestId - post requestID from loggingContext in PDP request header for call to PDP, then reinit storedRequestId to null
				// connection.setRequestProperty("X-ECOMP-RequestID", requestID.toString());
				connection.setRequestProperty("X-ECOMP-RequestID", loggingContext.getRequestID());
				storedRequestId = null;
				// end   - Fix to maintain requestId 
				//
				// Adding this in. It seems the HttpUrlConnection class does NOT
				// properly forward our headers for POST re-direction. It does so
				// for a GET re-direction.
				//
				// So we need to handle this ourselves.
				//
				//TODO - is this needed for a PUT?  seems better to leave in for now?
				//	            connection.setInstanceFollowRedirects(false);
				//
				// PLD - MUST be able to handle re-directs.
				//
				connection.setInstanceFollowRedirects(true);
				connection.setDoOutput(true);
				try (OutputStream os = connection.getOutputStream()) {

					EcompPDPGroup group = papEngine.getPDPGroup((EcompPDP) pdp);
					// if the PDP was just deleted, there is no group, but we want to send an update anyway
					if (group == null) {
						// create blank properties files
						Properties policyProperties = new Properties();
						policyProperties.put(XACMLProperties.PROP_ROOTPOLICIES, "");
						policyProperties.put(XACMLProperties.PROP_REFERENCEDPOLICIES, "");
						policyProperties.store(os, "");

						Properties pipProps = new Properties();
						pipProps.setProperty(XACMLProperties.PROP_PIP_ENGINES, "");
						pipProps.store(os, "");

					} else {
						// send properties from the current group
						group.getPolicyProperties().store(os, "");
						Properties policyLocations = new Properties();
						for (PDPPolicy policy : group.getPolicies()) {
							policyLocations.put(policy.getId() + ".url", XACMLPapServlet.papURL + "?id=" + policy.getId());
						}
						policyLocations.store(os, "");
						group.getPipConfigProperties().store(os, "");
					}

				} catch (Exception e) {
					PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to send property file to " + pdp.getId());
					// Since this is a server-side error, it probably does not reflect a problem on the client,
					// so do not change the PDP status.
					return;
				}
				//
				// Do the connect
				//
				connection.connect();
				if (connection.getResponseCode() == 204) {
					logger.info("Success. We are configured correctly.");
					loggingContext.transactionEnded();
					auditLogger.info("Success. PDP is configured correctly.");
					PolicyLogger.audit("Transaction Success. PDP is configured correctly.");
					setPDPSummaryStatus(pdp, PDPStatus.Status.UP_TO_DATE);
				} else if (connection.getResponseCode() == 200) {
					logger.info("Success. PDP needs to update its configuration.");
					loggingContext.transactionEnded();
					auditLogger.info("Success. PDP needs to update its configuration.");
					PolicyLogger.audit("Transaction Success. PDP is configured correctly.");
					setPDPSummaryStatus(pdp, PDPStatus.Status.OUT_OF_SYNCH);
				} else {
					logger.warn("Failed: " + connection.getResponseCode() + "  message: " + connection.getResponseMessage());
					loggingContext.transactionEnded();
					auditLogger.warn("Failed: " + connection.getResponseCode() + "  message: " + connection.getResponseMessage());
					PolicyLogger.audit("Transaction Failed: " + connection.getResponseCode() + "  message: " + connection.getResponseMessage());

					setPDPSummaryStatus(pdp, PDPStatus.Status.UNKNOWN);
				}
			} catch (Exception e) {
				PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Unable to sync config with PDP '" + pdp.getId() + "'");
				loggingContext.transactionEnded();
				PolicyLogger.audit("Transaction Failed: Unable to sync config with PDP '" + pdp.getId() + "': " + e);
				try {
					setPDPSummaryStatus(pdp, PDPStatus.Status.UNKNOWN);
				} catch (PAPException e1) {
					PolicyLogger.audit("Transaction Failed: Unable to set status of PDP " + pdp.getId() + " to UNKNOWN: " + e);

					PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Unable to set status of PDP '" + pdp.getId() + "' to UNKNOWN");
				}
			} finally {
				// cleanup the connection
				connection.disconnect();

				// tell the AC to update it's status info
				notifyAC();
			}

		}
	}

	//
	// RESTful Interface from PAP to ACs notifying them of changes
	//

	private void notifyAC() {
		// kick off a thread to do one event notification for all registered ACs
		// This needs to be on a separate thread so that ACs can make calls back to PAP to get the updated Group data
		// as part of processing this message on their end.
		Thread t = new Thread(new NotifyACThread());
		t.start();
	}

	private class NotifyACThread implements Runnable {

		public void run() {
			List<String> disconnectedACs = new ArrayList<String>();

			// There should be no Concurrent exception here because the list is a CopyOnWriteArrayList.
			// The "for each" loop uses the collection's iterator under the covers, so it should be correct.
			for (String acURL : adminConsoleURLStringList) {
				HttpURLConnection connection = null;
				try {

					acURL += "?PAPNotification=true";

					//TODO - Currently we just tell AC that "Something changed" without being specific.  Do we want to tell it which group/pdp changed?
					//TODO - If so, put correct parameters into the Query string here
					acURL += "&objectType=all" + "&action=update";

					if (logger.isDebugEnabled()) {
						logger.debug("creating url for id '" + acURL + "'");
					}
					//TODO - currently always send both policies and pips.  Do we care enough to add code to allow sending just one or the other?
					//TODO		(need to change "cache=", implying getting some input saying which to change)

					URL url = new URL(acURL );

					//
					// Open up the connection
					//
					connection = (HttpURLConnection)url.openConnection();
					//
					// Setup our method and headers
					//
					connection.setRequestMethod("PUT");
					connection.setRequestProperty("Content-Type", "text/x-java-properties");
					//
					// Adding this in. It seems the HttpUrlConnection class does NOT
					// properly forward our headers for POST re-direction. It does so
					// for a GET re-direction.
					//
					// So we need to handle this ourselves.
					//
					//TODO - is this needed for a PUT?  seems better to leave in for now?
					connection.setInstanceFollowRedirects(false);
					//
					// Do not include any data in the PUT because this is just a
					// notification to the AC.
					// The AC will use GETs back to the PAP to get what it needs
					// to fill in the screens.
					//

					//
					// Do the connect
					//
					connection.connect();
					if (connection.getResponseCode() == 204) {
						logger.info("Success. We updated correctly.");
					} else {
						logger.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed: " + connection.getResponseCode() + "  message: " + connection.getResponseMessage());
					}

				} catch (Exception e) {
					//TODO:EELF Cleanup - Remove logger
					//logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to sync config AC '" + acURL + "': " + e, e);
					PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Unable to sync config AC '" + acURL + "'");
					disconnectedACs.add(acURL);
				} finally {
					// cleanup the connection
					connection.disconnect();
				}
			}

			// remove any ACs that are no longer connected
			if (disconnectedACs.size() > 0) {
				adminConsoleURLStringList.removeAll(disconnectedACs);
			}

		}
	}

	/*
	 * Added by Mike M in 1602 release for Authorizing the PEP Requests for Granularity. 
	 */
	private boolean authorizeRequest(HttpServletRequest request) {
		if(request instanceof HttpServletRequest) {

			// Get the client Credentials from the Request header. 
			String clientCredentials = request.getHeader(ENVIRONMENT_HEADER);

			// Check if the Client is Authorized. 
			if(clientCredentials!=null && clientCredentials.equalsIgnoreCase(environment)){
				return true;
			}else{
				return false;
			}
		} else {
			return false;
		}
	}

	public static String getConfigHome(){
		try {
			loadWebapps();
		} catch (Exception e) {
			return null;
		}
		return CONFIG_HOME;
	}

	public static String getActionHome(){
		try {
			loadWebapps();
		} catch (Exception e) {
			return null;
		}
		return ACTION_HOME;
	}

	private static void loadWebapps() throws Exception{
		if(ACTION_HOME == null || CONFIG_HOME == null){
			Path webappsPath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS));
			//Sanity Check
			if (webappsPath == null) {
				PolicyLogger.error("Invalid Webapps Path Location property : " + XACMLRestProperties.PROP_PAP_WEBAPPS);
				throw new Exception("Invalid Webapps Path Location property : " + XACMLRestProperties.PROP_PAP_WEBAPPS);
			}
			Path webappsPathConfig;
			Path webappsPathAction;
			if(webappsPath.toString().contains("\\"))
			{
				webappsPathConfig = Paths.get(webappsPath.toString()+"\\Config");
				webappsPathAction = Paths.get(webappsPath.toString()+"\\Action");
			}
			else
			{
				webappsPathConfig = Paths.get(webappsPath.toString()+"/Config");
				webappsPathAction = Paths.get(webappsPath.toString()+"/Action");
			}
			if (Files.notExists(webappsPathConfig)) 
			{
				try {
					Files.createDirectories(webappsPathConfig);
				} catch (IOException e) {
					PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Failed to create config directory: "
							+ webappsPathConfig.toAbsolutePath().toString());
				}
			}
			if (Files.notExists(webappsPathAction)) 
			{
				try {
					Files.createDirectories(webappsPathAction);
				} catch (IOException e) {
					logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to create config directory: "
							+ webappsPathAction.toAbsolutePath().toString(), e);
				}
			}
			ACTION_HOME = webappsPathAction.toString();
			CONFIG_HOME = webappsPathConfig.toString();
		}
	}

	/**
	 * @return the emf
	 */
	public EntityManagerFactory getEmf() {
		return emf;
	}
	public IntegrityMonitor getIm() {
		return im;
	}

	public IntegrityAudit getIa() {
		return ia;
	}
}