aboutsummaryrefslogtreecommitdiffstats
path: root/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/XACMLPapServlet.java
blob: 85d79f74aee1a4412622da4cb825e7e14f42b559 (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
/*-
 * ============LICENSE_START=======================================================
 * ONAP-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.onap.policy.pap.xacml.rest;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
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.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Scanner;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArrayList;

import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceException;
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 org.apache.commons.io.IOUtils;
import org.onap.policy.common.ia.IntegrityAudit;
import org.onap.policy.common.im.AdministrativeStateException;
import org.onap.policy.common.im.ForwardProgressException;
import org.onap.policy.common.im.IntegrityMonitor;
import org.onap.policy.common.im.IntegrityMonitorProperties;
import org.onap.policy.common.im.StandbyStatusException;
import org.onap.policy.common.logging.ONAPLoggingContext;
import org.onap.policy.common.logging.ONAPLoggingUtils;
import org.onap.policy.common.logging.eelf.MessageCodes;
import org.onap.policy.common.logging.eelf.PolicyLogger;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
import org.onap.policy.pap.xacml.rest.components.PolicyDBDao;
import org.onap.policy.pap.xacml.rest.components.PolicyDBDaoTransaction;
import org.onap.policy.pap.xacml.rest.handler.APIRequestHandler;
import org.onap.policy.pap.xacml.rest.handler.PushPolicyHandler;
import org.onap.policy.pap.xacml.rest.handler.SavePolicyHandler;
import org.onap.policy.pap.xacml.restAuth.CheckPDP;
import org.onap.policy.rest.XACMLRest;
import org.onap.policy.rest.XACMLRestProperties;
import org.onap.policy.rest.dao.PolicyDBException;
import org.onap.policy.utils.PolicyUtils;
import org.onap.policy.xacml.api.XACMLErrorConstants;
import org.onap.policy.xacml.api.pap.ONAPPapEngineFactory;
import org.onap.policy.xacml.api.pap.OnapPDP;
import org.onap.policy.xacml.api.pap.OnapPDPGroup;
import org.onap.policy.xacml.api.pap.PAPPolicyEngine;
import org.onap.policy.xacml.std.pap.StdPAPPolicy;
import org.onap.policy.xacml.std.pap.StdPDP;
import org.onap.policy.xacml.std.pap.StdPDPGroup;
import org.onap.policy.xacml.std.pap.StdPDPItemSetChangeNotifier.StdItemSetChangeListener;
import org.onap.policy.xacml.std.pap.StdPDPPolicy;
import org.onap.policy.xacml.std.pap.StdPDPStatus;

import com.att.research.xacml.api.pap.PAPException;
import com.att.research.xacml.api.pap.PDPPolicy;
import com.att.research.xacml.api.pap.PDPStatus;
import com.att.research.xacml.util.FactoryException;
import com.att.research.xacml.util.XACMLProperties;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Splitter;

/**
 * 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);
	// audit (transaction) LOGGER
	private static final Logger auditLogger = FlexLogger.getLogger("auditLogger");
	//Persistence Unit for JPA 
	private static final String PERSISTENCE_UNIT = "XACML-PAP-REST";
	private static final String AUDIT_PAP_PERSISTENCE_UNIT = "auditPapPU";
	// Client Headers. 
	private static final String ENVIRONMENT_HEADER = "Environment";
	/*
	 * 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<>();	
	
	private static String configHome;
	private static String actionHome;
	/*
	 * 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;
	// The heartbeat thread.
	private static Heartbeat heartbeat = null;
	private static Thread heartbeatThread = null;
	//The entity manager factory for JPA access
	private static EntityManagerFactory emf;
	private static PolicyDBDao policyDBDao;
	/*
	 * papEngine - This is our engine workhorse that manages the PDP Groups and Nodes.
	 */
	private static PAPPolicyEngine papEngine = null;
	/*
	 * These are the parameters needed for DB access from the PAP
	 */
	private static int papIntegrityAuditPeriodSeconds = -1;
	private static String papDbDriver = null;
	private static String papDbUrl = null;
	private static String papDbUser = null;
	private static String papDbPassword = null;
	private static String papResourceName = null;
	private static String[] papDependencyGroupsFlatArray = null;
	private static String environment = null;
	private static String pdpFile = null;
	
	private transient IntegrityMonitor im;
	private transient IntegrityAudit ia;
	
	//MicroService Model Properties
	private static String msOnapName;
	private static String msPolicyName;
	/*
	 * This thread may be invoked upon startup to initiate sending PDP policy/pip configuration when
	 * this servlet starts. Its configurable by the admin.
	 */
	private static transient Thread initiateThread = null;
	private transient ONAPLoggingContext baseLoggingContext = null;
	
	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public XACMLPapServlet() {
		super();
	}

	/**
	 * @see Servlet#init(ServletConfig)
	 */
	public void init(ServletConfig config) throws ServletException {
		try {
			// Logging
			baseLoggingContext = new ONAPLoggingContext();
			// 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", e);
			}
			// Initialize
			XACMLRest.xacmlInit(config);
			// Load the properties
			XACMLRest.loadXacmlProperties(null, null);
			/*
			 * Retrieve the property values
			 */
			setCommonProperties();
			String papSiteName = XACMLProperties.getProperty(XACMLRestProperties.PAP_SITE_NAME);
			if(papSiteName == null){
				PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papSiteName property entry");
				throw new PAPException("papSiteName is null");
			}
			String papNodeType = XACMLProperties.getProperty(XACMLRestProperties.PAP_NODE_TYPE);
			if(papNodeType == null){
				PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papNodeType property entry");
				throw new PAPException("papNodeType is null");
			}
			//Integer will throw an exception of anything is missing or unrecognized
			int papTransWait = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT));
			int papTransTimeout = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT));
			int papAuditTimeout = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_TIMEOUT));
			//Boolean will default to false if anything is missing or unrecognized
			boolean papAuditFlag = Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_RUN_AUDIT_FLAG));
			boolean papFileSystemAudit = Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_FLAG));
			String papDependencyGroups = XACMLProperties.getProperty(XACMLRestProperties.PAP_DEPENDENCY_GROUPS);
			if(papDependencyGroups == null){
				throw new PAPException("papDependencyGroups is null");
			}
			setPAPDependencyGroups(papDependencyGroups);
			//Integer will throw an exception of anything is missing or unrecognized
			int fpMonitorInterval = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.FP_MONITOR_INTERVAL));
			int failedCounterThreshold = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.FAILED_COUNTER_THRESHOLD));
			int testTransInterval = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.TEST_TRANS_INTERVAL));
			int 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	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();
				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
			setEMF(properties);
			// 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
			setPAPURL(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL));
			//Create the policyDBDao
			setPolicyDBDao();
			// Load our PAP engine, first create a factory
			ONAPPapEngineFactory factory = ONAPPapEngineFactory.newInstance(XACMLProperties.getProperty(XACMLProperties.PROP_PAP_PAPENGINEFACTORY));
			// The factory knows how to go about creating a PAP Engine
			setPAPEngine((PAPPolicyEngine) factory.newEngine());
			PolicyDBDaoTransaction addNewGroup = null;
            if (((org.onap.policy.xacml.std.pap.StdEngine) papEngine).wasDefaultGroupJustAdded) {
                try {
                    addNewGroup = policyDBDao.getNewTransaction();
                    OnapPDPGroup 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) XACMLPapServlet.papEngine);
    		if (Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_RUN_AUDIT_FLAG))){
    			/*
    			 * Auditing the local File System groups to be in sync with the Database
    			 */
    			
    			//get an AuditTransaction to lock out all other transactions
    			PolicyDBDaoTransaction auditTrans = policyDBDao.getNewAuditTransaction();
    			
    			LOGGER.info("PapServlet: calling auditLocalFileSystem for PDP group audit");
                LOGGER.info("PapServlet: old group is " + papEngine.getDefaultGroup().toString());
    			//get the current filesystem group and update from the database if needed
                StdPDPGroup group = (StdPDPGroup) papEngine.getDefaultGroup();
                StdPDPGroup updatedGroup = policyDBDao.auditLocalFileSystem(group);
                if(updatedGroup!=null) {
                	papEngine.updateGroup(updatedGroup);
                }    
                LOGGER.info("PapServlet:  updated group is " + papEngine.getDefaultGroup().toString());
                
    			//release the transaction lock
    			auditTrans.close();
    		}
		
			// Sanity check for URL.
			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.
			if (Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_INITIATE_PDP_CONFIG))) {
			    startInitiateThreadService(new Thread(this));
			}
			// After startup, the PAP does Heartbeat's to each of the PDPs periodically
			startHeartBeatService(new Heartbeat((PAPPolicyEngine) XACMLPapServlet.papEngine));

		} 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);
		}
	}

	private static void startInitiateThreadService(Thread thread) {
	    initiateThread = thread;
        initiateThread.start();
    }

    private static void mapperWriteValue(ObjectMapper mapper,  HttpServletResponse response, Object value) {
        try {
            mapper.writeValue(response.getOutputStream(), value);
        } catch (Exception e) {
            LOGGER.error(e);
        }
    }

    private static void startHeartBeatService(Heartbeat heartbeat) {
	    XACMLPapServlet.heartbeat = heartbeat;
        XACMLPapServlet.heartbeatThread = new Thread(XACMLPapServlet.heartbeat);
        XACMLPapServlet.heartbeatThread.start();
    }

    private static void setPolicyDBDao() throws ServletException {
	    try {
            policyDBDao = PolicyDBDao.getPolicyDBDaoInstance(getEmf());
        } catch (Exception e) {
            throw new ServletException("Unable to Create Policy DBDao Instance",e);
        }
    }

    private static void setEMF(Properties properties) throws ServletException {
	    emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT, properties);
        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");
        }
    }

    private static void setPAPURL(String papURL) {
	    XACMLPapServlet.papURL = papURL;
    }

    private static void setPAPEngine(PAPPolicyEngine newEngine) {
	    XACMLPapServlet.papEngine = newEngine;
    }

    private static void setPAPDependencyGroups(String papDependencyGroups) throws PAPException {
	    try{
            //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());
                }
            }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 new PAPException(e);
        }
    }

    private static void setCommonProperties() throws PAPException {
	    setConfigHome();
        setActionHome();
        papDbDriver = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_DRIVER);
        if(papDbDriver == null){
            PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbDriver property entry");
            throw new PAPException("papDbDriver is null");
        }
        setPapDbDriver(papDbDriver);
        papDbUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_URL);
        if(papDbUrl == null){
            PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbUrl property entry");
            throw new PAPException("papDbUrl is null");
        }
        setPapDbUrl(papDbUrl);
        papDbUser = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_USER);
        if(papDbUser == null){
            PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbUser property entry");
            throw new PAPException("papDbUser is null");
        }
        setPapDbUser(papDbUser);
        papDbPassword = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_PASSWORD);
        if(papDbPassword == null){
            PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbPassword property entry");
            throw new PAPException("papDbPassword is null");
        }
        setPapDbPassword(papDbPassword);
        papResourceName = XACMLProperties.getProperty(XACMLRestProperties.PAP_RESOURCE_NAME);
        if(papResourceName == null){
            PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papResourceName property entry");
            throw new PAPException("papResourceName is null");
        }
        environment = XACMLProperties.getProperty("ENVIRONMENT", "DEVL");
        //Micro Service Properties
        msOnapName=XACMLProperties.getProperty("xacml.policy.msOnapName");
        setMsOnapName(msOnapName);
        msPolicyName=XACMLProperties.getProperty("xacml.policy.msPolicyName");
        setMsPolicyName(msPolicyName);
        // 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. ");
        }
    }

    /**
	 * 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.
	 */
	@Override
	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) {
			    XACMLPapServlet.heartbeatThread.interrupt();
				PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Error stopping heartbeat");
			}
		}
		if (initiateThread != null) {
			try {
				initiateThread.interrupt();
				initiateThread.join();
			} catch (InterruptedException e) {
			    initiateThread.interrupt();
				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 {
		ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
		loggingContext.transactionStarted();
		loggingContext.setServiceName("PAP.post");
		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)");
		}
		PolicyDBDaoTransaction pdpTransaction = null;
		loggingContext.metricStarted();
		try {
			im.startTransaction();
			loggingContext.metricEnded();
			PolicyLogger.metrics("XACMLPapServlet doPost 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.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message, ae);
			loggingContext.metricEnded();
			PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction");
			loggingContext.transactionEnded();			
			PolicyLogger.audit("Transaction Failed - See Error.log");
			setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
			return;
		}catch (StandbyStatusException se) {
			String message = "POST interface called for PAP " + papResourceName + " but it has a Standby Status"
					+ " of " + im.getStateManager().getStandbyStatus()
					+ "\n Exception Message: " + se.getMessage();
			LOGGER.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message, se);
			loggingContext.metricEnded();
			PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction");
			loggingContext.transactionEnded();
			PolicyLogger.audit("Transaction Failed - See Error.log");
			setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
			return;
		}
		try {
			loggingContext.metricStarted();
			XACMLRest.dumpRequest(request);
			loggingContext.metricEnded();
			PolicyLogger.metrics("XACMLPapServlet doPost dumpRequest");
			// 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 && apiflag.equalsIgnoreCase("api")) {
					// this is from the API so we need to check the client credentials before processing the request
					if(!authorizeRequest(request)){
						String message = "PEP not Authorized for making this Request!!";
						PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
						loggingContext.transactionEnded();
						PolicyLogger.audit("Transaction Failed - See Error.log");
						setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message);
						im.endTransaction();
						return;
					}
				}
				loggingContext.metricStarted();
				doACPost(request, response, groupId, loggingContext);
				loggingContext.metricEnded();
				PolicyLogger.metrics("XACMLPapServlet doPost doACPost");
				loggingContext.transactionEnded();
				PolicyLogger.audit("Transaction Ended Successfully");
				im.endTransaction();
				return;
			}
			// Request is from a PDP 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("Request(doPost) from PDP coming up: " + id);
			// Get the PDP Object
			OnapPDP pdp = XACMLPapServlet.papEngine.getPDP(id);
			// Is it known?
			if (pdp == null) {
				LOGGER.info("Unknown PDP: " + id);
				// Check PDP ID
				if(CheckPDP.validateID(id)){
					pdpTransaction = policyDBDao.getNewTransaction();
					try {
						pdpTransaction.addPdpToGroup(id, XACMLPapServlet.papEngine.getDefaultGroup().getId(), id, "Registered on first startup", Integer.parseInt(jmxport), "PDP autoregister");
						XACMLPapServlet.papEngine.newPDP(id, XACMLPapServlet.papEngine.getDefaultGroup(), id, "Registered on first startup", Integer.parseInt(jmxport));
					} catch (NullPointerException | PAPException | IllegalArgumentException | IllegalStateException | PersistenceException | PolicyDBException 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");
						setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
						im.endTransaction();
						return;
					}
					// get the PDP we just created
		            try{
		                pdp = XACMLPapServlet.papEngine.getPDP(id);
		            }catch(PAPException e){
		                LOGGER.error(e);
		            }
					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");
						setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
						im.endTransaction();
						return;
					}
				} else {
					String message = "PDP is Unauthorized to Connect to PAP: "+ id;
					loggingContext.transactionEnded();
					PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
					setResponseError(response, 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;
				}
				try{
					loggingContext.metricStarted();
					pdpTransaction.commitTransaction();
					loggingContext.metricEnded();
					PolicyLogger.metrics("XACMLPapServlet doPost 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 != ""){
			    try{
	                ((StdPDP) pdp).setJmxPort(Integer.valueOf(jmxport));
			    }catch(NumberFormatException e){
			        LOGGER.error(e);
			    }
			}
			// Get the PDP's Group
			OnapPDPGroup group =null;
			try{
	            group= XACMLPapServlet.papEngine.getPDPGroup((OnapPDP) pdp);
			}catch(PAPException e){
			    LOGGER.error(e);
			}
			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");
				setResponseError(response, 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();
			try{
	            pdpProperties.load(request.getInputStream());
			}catch(IOException e){
			    LOGGER.error(e);
			}
			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
					try{
					    policies.store(response.getOutputStream(), "");
					}catch(IOException e){
		                LOGGER.error(e);
		            }
				}
				if (pipconfig != null) {
					// Copy the properties to the output stream
					try{
					    pipconfig.store(response.getOutputStream(), "");
					}catch(IOException e){
		                LOGGER.error(e);
		            }
				}
				// We are good - and we are sending them information
				response.setStatus(HttpServletResponse.SC_OK);
				try{
				    setPDPSummaryStatus(pdp, PDPStatus.Status.OUT_OF_SYNCH);
				}catch(PAPException e){
	                LOGGER.error(e);
	            }
			} else {
				// Tell them they are good
				response.setStatus(HttpServletResponse.SC_NO_CONTENT);
				try{
				    setPDPSummaryStatus(pdp, PDPStatus.Status.UP_TO_DATE);
				}catch(PAPException e){
	                LOGGER.error(e);
	            }
			}
			// tell the AC that something changed
			loggingContext.metricStarted();
			notifyAC();
			loggingContext.metricEnded();
			PolicyLogger.metrics("XACMLPapServlet doPost notifyAC");
			loggingContext.transactionEnded();
			auditLogger.info("Success");
			PolicyLogger.audit("Transaction Ended Successfully");
		} catch (PAPException | IOException | NumberFormatException 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");
			setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
			im.endTransaction();
			return;
		}
		//Catch anything that fell through
		loggingContext.transactionEnded();
		PolicyLogger.audit("Transaction Ended");
		im.endTransaction();
	}

	private void setResponseError(HttpServletResponse response,int responseCode, String message) {
	    try {
            response.sendError(responseCode, message);
        } catch (IOException e) {
            LOGGER.error("Error setting Error response Header ", e);
        }
	    return;
    }

    /**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
		loggingContext.transactionStarted();
		loggingContext.setServiceName("PAP.get");
		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)");
		}
		try {
			loggingContext.metricStarted();
			XACMLRest.dumpRequest(request);
			loggingContext.metricEnded();
			PolicyLogger.metrics("XACMLPapServlet doGet dumpRequest");
			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")) {
					try {
						testService(loggingContext, response);
					} catch (IOException e) {
						LOGGER.debug(e);
					}
					return;
				}
			}
			//This im.startTransaction() covers all other Get transactions
			try {
				loggingContext.metricStarted();
				im.startTransaction();
				loggingContext.metricEnded();
				PolicyLogger.metrics("XACMLPapServlet doGet 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, ae);
				PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
				loggingContext.transactionEnded();
				PolicyLogger.audit("Transaction Failed - See Error.log");
				setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
				return;
			}catch (StandbyStatusException se) {
				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, se);
				PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
				loggingContext.transactionEnded();
				PolicyLogger.audit("Transaction Failed - See Error.log");
				setResponseError(response, 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)){
					APIRequestHandler apiRequestHandler = new APIRequestHandler();
					try{				
						loggingContext.metricStarted();
					    apiRequestHandler.doGet(request,response, apiflag);
						loggingContext.metricEnded();
						PolicyLogger.metrics("XACMLPapServlet doGet apiRequestHandler doGet");
					}catch(IOException e){
					    LOGGER.error(e);
					}
					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");
					setResponseError(response, 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
				try{
					loggingContext.metricStarted();
				    doACGet(request, response, groupId, loggingContext);
					loggingContext.metricEnded();
					PolicyLogger.metrics("XACMLPapServlet doGet doACGet");
				} catch(IOException e){
                    LOGGER.error(e);
                }
				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
			OnapPDP pdp = null;
			try{
			    pdp = XACMLPapServlet.papEngine.getPDP(id);
			}catch(PAPException e){
			    LOGGER.error(e);
			}
			// Is it known?
			if (pdp == null) {
				// Check if request came from localhost
				if (request.getRemoteHost().equals("localhost") ||
						request.getRemoteHost().equals(request.getLocalAddr())) {
					// Return status information - basically all the groups
					loggingContext.setServiceName("PAP.getGroups");
					Set<OnapPDPGroup> groups = papEngine.getOnapPDPGroups();
					// convert response object to JSON and include in the response
					mapperWriteValue(new ObjectMapper(), response,  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");
				setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, message);
				im.endTransaction();
				return;
			}
			loggingContext.setServiceName("PAP.getPolicy");
			// Get the PDP's Group
			OnapPDPGroup group = null;
			try {
			    group = XACMLPapServlet.papEngine.getPDPGroup((OnapPDP) pdp);
			} catch (PAPException e) {
			    LOGGER.error(e);
			}
			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");
				setResponseError(response, 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");
				setResponseError(response,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");
				setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
				im.endTransaction();
				return;
			}
			try{
	            LOGGER.warn("PolicyDebugging: Policy Validity: " + policy.isValid() + "\n "
	                    + "Policy Name : " + policy.getName() + "\n Policy URI: " + policy.getLocation().toString());
			} catch (PAPException| IOException e){
			    LOGGER.error(e);
			}
			try (InputStream is = new FileInputStream(((StdPDPGroup)group).getDirectory().toString()+File.separator+policyId); 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 (IOException e) {
				String message = "Failed to open policy id " + policyId;
				LOGGER.debug(e);
				PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
				loggingContext.transactionEnded();
				PolicyLogger.audit("Transaction Failed - See Error.log");
				setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
			}
		}  catch (PAPException e) {
			LOGGER.debug(e);
			PolicyLogger.error(MessageCodes.ERROR_UNKNOWN, e, "XACMLPapServlet", " GET exception");
			loggingContext.transactionEnded();
			PolicyLogger.audit("Transaction Failed - See Error.log");
			setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
			im.endTransaction();
			return;
		}
		loggingContext.transactionEnded();
		PolicyLogger.audit("Transaction Ended");
		im.endTransaction();
	}
	
	/**
	 * @see HttpServlet#doPut(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
		loggingContext.transactionStarted();
		loggingContext.setServiceName("PAP.put");
		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)");
		}
		try {
			loggingContext.metricStarted();
			im.startTransaction();
			loggingContext.metricEnded();
			PolicyLogger.metrics("XACMLPapServlet doPut im startTransaction");
		} catch (AdministrativeStateException | StandbyStatusException e) {
			String message = "PUT interface called for PAP " + papResourceName;
			if (e instanceof AdministrativeStateException) {
				message += " but it has an Administrative state of "
					+ im.getStateManager().getAdminState();
			} else if (e instanceof StandbyStatusException) {
				message += " but it has a Standby Status of "
					+ im.getStateManager().getStandbyStatus();

			}
			message += "\n Exception Message: " + e.getMessage();

			LOGGER.info(message, e);
			PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
			loggingContext.transactionEnded();
			PolicyLogger.audit("Transaction Failed - See Error.log");
			setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
			return;
		}

		loggingContext.metricStarted();
		XACMLRest.dumpRequest(request);
		loggingContext.metricEnded();
		PolicyLogger.metrics("XACMLPapServlet doPut dumpRequest");
		//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 policyDBDaoRequestExtraData = request.getParameter("extradata");
			if(policyDBDaoRequestEntityId == null || policyDBDaoRequestEntityType == null){
				setResponseError(response,400, "entityid or entitytype not supplied");
				loggingContext.transactionEnded();
				PolicyLogger.audit("Transaction Ended Successfully");
				im.endTransaction();
				return;
			}
			loggingContext.metricStarted();		
			policyDBDao.handleIncomingHttpNotification(policyDBDaoRequestUrl,policyDBDaoRequestEntityId,policyDBDaoRequestEntityType,policyDBDaoRequestExtraData,this);
			loggingContext.metricEnded();
			PolicyLogger.metrics("XACMLPapServlet doPut handle incoming http notification");
			response.setStatus(200);
			loggingContext.transactionEnded();
			PolicyLogger.audit("Transaction Ended Successfully");
			im.endTransaction();
			return;
		}
		/*
		 * Request for ImportService 
		 */
		String importService = request.getParameter("importService");
		if (importService != null) {
			if(authorizeRequest(request)){
				APIRequestHandler apiRequestHandler = new APIRequestHandler();
				try{
					loggingContext.metricStarted();	
				    apiRequestHandler.doPut(request, response, importService);
					loggingContext.metricEnded();
					PolicyLogger.metrics("XACMLPapServlet doPut apiRequestHandler doPut");
				}catch(IOException e){
				    LOGGER.error(e);
				}
				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");
				setResponseError(response,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 = " + " ");
				setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR,"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();
				setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR,"createUpdateTransaction.createPolicy(policyToCreateUpdate, XACMLPapServlet.doPut) "
						+ "\nfailure with the following exception: " + e);
				loggingContext.transactionEnded();
				PolicyLogger.audit("Transaction Failed - See error.log");
				im.endTransaction();
				return;
			}
			loggingContext.metricStarted();
			renameTransaction.commitTransaction();
			loggingContext.metricEnded();
			PolicyLogger.metrics("XACMLPapServlet goPut 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 policies 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(!authorizeRequest(request)){
					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");
					setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message);
					return;
				}
				if(apiflag.equalsIgnoreCase("addPolicyToGroup")){
				    try{
				        updateGroupsFromAPI(request, response, groupId, loggingContext);
				    }catch(IOException e){
				        LOGGER.error(e);
				    }
					loggingContext.transactionEnded();
					PolicyLogger.audit("Transaction Ended Successfully");
					im.endTransaction();
					return;
				}
			}
			// this is from the Admin Console, so handle separately
			try {
				loggingContext.metricEnded();
			    doACPut(request, response, groupId, loggingContext);
				loggingContext.metricEnded();
				PolicyLogger.metrics("XACMLPapServlet goPut doACPut");
			} catch (IOException e) {
                LOGGER.error(e);
            }
			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
			SavePolicyHandler savePolicyHandler = SavePolicyHandler.getInstance();
			try{
				loggingContext.metricStarted();
			    savePolicyHandler.doPolicyAPIPut(request, response);
				loggingContext.metricEnded();
				PolicyLogger.metrics("XACMLPapServlet goPut savePolicyHandler");
			} catch (IOException e) {
                LOGGER.error(e);
            }
			loggingContext.transactionEnded();
			PolicyLogger.audit("Transaction Ended Successfully");
			im.endTransaction();
			return;
		} else if (apiflag != null && apiflag.equalsIgnoreCase("api")) {
			// this request is from the Policy Creation API 
			if(authorizeRequest(request)){
				APIRequestHandler apiRequestHandler = new APIRequestHandler();
				try{
					loggingContext.metricStarted();
				    apiRequestHandler.doPut(request, response, request.getHeader("ClientScope"));
					loggingContext.metricEnded();
					PolicyLogger.metrics("XACMLPapServlet goPut apiRequestHandler doPut");
	            } catch (IOException e) {
	                LOGGER.error(e);
	            }
				loggingContext.transactionEnded();
				PolicyLogger.audit("Transaction Ended Successfully");
				im.endTransaction();
				return;
			} else {
				String message = "PEP not Authorized for making this Request!!";
				PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
				loggingContext.transactionEnded();
				PolicyLogger.audit("Transaction Failed - See Error.log");
				setResponseError(response,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");
		setResponseError(response,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 {
		ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
		loggingContext.transactionStarted();
		loggingContext.setServiceName("PAP.delete");
		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)");
		}
		try {
			loggingContext.metricStarted();
			im.startTransaction();
			loggingContext.metricEnded();
			PolicyLogger.metrics("XACMLPapServlet doDelete 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, ae);
			PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
			loggingContext.transactionEnded();
			PolicyLogger.audit("Transaction Failed - See Error.log");
			setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
			return;
		}catch (StandbyStatusException se) {
			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, se);
			PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
			loggingContext.transactionEnded();
			PolicyLogger.audit("Transaction Failed - See Error.log");
			setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
			return;
		}
		loggingContext.metricStarted();
		XACMLRest.dumpRequest(request);
		loggingContext.metricEnded();
		PolicyLogger.metrics("XACMLPapServlet doDelete dumpRequest");
		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(!authorizeRequest(request)){
					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");
					setResponseError(response,HttpServletResponse.SC_FORBIDDEN, message);
					return;
				}
				APIRequestHandler apiRequestHandler = new APIRequestHandler();
				try {
					loggingContext.metricStarted();
					apiRequestHandler.doDelete(request, response, loggingContext, apiflag);
					loggingContext.metricEnded();
					PolicyLogger.metrics("XACMLPapServlet doDelete apiRequestHandler doDelete");
				} catch (Exception e) {
					LOGGER.error("Exception Occured"+e);
				}
				if(apiRequestHandler.getNewGroup()!=null){
					groupChanged(apiRequestHandler.getNewGroup(), loggingContext);
				}
				return;
			}
			// this is from the Admin Console, so handle separately
			try{
				loggingContext.metricStarted();
			    doACDelete(request, response, groupId, loggingContext);
				loggingContext.metricEnded();
				PolicyLogger.metrics("XACMLPapServlet doDelete doACDelete");
			} catch (IOException e) {
                LOGGER.error(e);
            }
			loggingContext.transactionEnded();
			PolicyLogger.audit("Transaction Ended Successfully");
			im.endTransaction();
			return;
		}
		//Catch anything that fell through
		PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Request does not have groupId");
		loggingContext.transactionEnded();
		PolicyLogger.audit("Transaction Failed - See Error.log");
		setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "Request does not have groupId");
		im.endTransaction();
	}

	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);
				}
			}
		}
	}

	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;
	}
	
	/**
	 * 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
	 */
	public void updateGroupsFromAPI(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws IOException {
		PolicyDBDaoTransaction acPutTransaction = policyDBDao.getNewTransaction();
		PolicyLogger.audit("PolicyDBDaoTransaction started for updateGroupsFromAPI");
		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 input stream content into a String
			String json = null;
			java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
			scanner.useDelimiter("\\A");
			json =  scanner.hasNext() ? scanner.next() : "";
			scanner.close();

			PolicyLogger.info("pushPolicy request from API: " + json);
			
			// convert Object sent as JSON into local object
			StdPDPPolicy policy = PolicyUtils.jsonStringToObject(json, StdPDPPolicy.class);
			
			//Get the current policies from the Group and Add the new one
			Set<PDPPolicy> currentPoliciesInGroup = new HashSet<>();
			currentPoliciesInGroup = group.getPolicies();
			//If the selected policy is in the group we must remove the old version of it
			LOGGER.info("Removing old version of the policy");
			for(PDPPolicy existingPolicy : currentPoliciesInGroup) {
				if (existingPolicy.getName().equals(policy.getName())){
					if (!existingPolicy.getId().equals(policy.getId())) {
						group.removePolicy(existingPolicy);
						LOGGER.info("Removing policy: " + existingPolicy);
						break;
					}
				}
			}
			
			// 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());	
			}
			
			LOGGER.info("Calling updatGroup() with new group");
			papEngine.updateGroup(group);
			
			String policyId = "empty";
			if(policy!=null){
				policyId = policy.getId();
			}
			response.setStatus(HttpServletResponse.SC_NO_CONTENT);
			response.addHeader("operation", "push");
			response.addHeader("policyId", policyId);
			response.addHeader("groupId", groupId);
			
			LOGGER.info("Group '" + group.getId() + "' updated");
			
			loggingContext.metricStarted();
			acPutTransaction.commitTransaction();
			loggingContext.metricEnded();
			PolicyLogger.metrics("XACMLPapServlet updateGroupsFromAPI commitTransaction");
			loggingContext.metricStarted();
			notifyAC();
			loggingContext.metricEnded();
			PolicyLogger.metrics("XACMLPapServlet updateGroupsFromAPI notifyAC");

			// Group changed, which might include changing the policies	
			groupChanged(group, loggingContext);
			loggingContext.transactionEnded();
			LOGGER.info("Success");

			if (policy != null && ((policy.getId().contains("Config_MS_")) || (policy.getId().contains("BRMS_Param")))) {
				PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance();
				if (pushPolicyHandler.preSafetyCheck(policy, configHome)) {
					LOGGER.debug("Precheck Successful.");
				}
			}

			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.";
			setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
			response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			response.addHeader("error","addGroupError");
			response.addHeader("message", message);
			return;
		}
	}

	/**
	 * 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, ONAPLoggingContext 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 = null;
				String unescapedDescription = null;
				try{
				    unescapedName = URLDecoder.decode(groupName, "UTF-8");
				    unescapedDescription = URLDecoder.decode(groupDescription, "UTF-8");
				} catch (UnsupportedEncodingException e) {
				    LOGGER.error(e);
				}
				PolicyDBDaoTransaction newGroupTransaction = policyDBDao.getNewTransaction();
				try {					
					newGroupTransaction.createGroup(PolicyDBDao.createNewPDPGroupId(unescapedName), unescapedName, unescapedDescription,"XACMLPapServlet.doACPost");
					papEngine.newGroup(unescapedName, unescapedDescription);
					loggingContext.metricStarted();
					newGroupTransaction.commitTransaction();
					loggingContext.metricEnded();
					PolicyLogger.metrics("XACMLPapServlet doACPost 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");
					setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "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
				loggingContext.metricStarted();
				notifyAC();
				loggingContext.metricEnded();
				PolicyLogger.metrics("XACMLPapServlet doACPost 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
			OnapPDPGroup group = null;
			try{
			    group = papEngine.getGroup(groupId);
			} catch (PAPException e){
			    LOGGER.error(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");
				if (apiflag!=null){
					response.addHeader("error", "unknownGroupId");
					response.addHeader("operation", "push");
					response.addHeader("message", message);
					response.setStatus(HttpServletResponse.SC_NOT_FOUND);
				} else {
					setResponseError(response,HttpServletResponse.SC_NOT_FOUND, message);
				}
				return;
			}
			
			// If the request contains a policyId then we know we are pushing the policy to PDP
			if (request.getParameter("policyId") != null) {
				
				if(apiflag!=null){
					loggingContext.setServiceName("PolicyEngineAPI:PAP.postPolicy");
				} else {
					loggingContext.setServiceName("AC:PAP.postPolicy");
				}
				
				String policyId = request.getParameter("policyId");
				PolicyDBDaoTransaction addPolicyToGroupTransaction = policyDBDao.getNewTransaction();
				StdPDPGroup updatedGroup = null;
				try {
					//Copying the policy to the file system and updating groups in database
					LOGGER.info("PapServlet: calling PolicyDBDao.addPolicyToGroup()");
					updatedGroup = addPolicyToGroupTransaction.addPolicyToGroup(group.getId(), policyId,"XACMLPapServlet.doACPost");
					loggingContext.metricStarted();
					addPolicyToGroupTransaction.commitTransaction();
					loggingContext.metricEnded();
					PolicyLogger.metrics("XACMLPapServlet doACPost commitTransaction");
					LOGGER.info("PapServlet: addPolicyToGroup() succeeded, transaction was committed");
					
				} 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 {
						setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
					}
					return;
				}
				
				// Get new transaction to perform updateGroup()
				PolicyDBDaoTransaction acPutTransaction = policyDBDao.getNewTransaction();
				try {
					/*
					 * If request comes from the API we need to run the PolicyDBDao updateGroup() to notify other paps of the change.
					 * The GUI does this from the POLICY-SDK-APP code.
					 */
					if(apiflag != null){

						// get the request content into a String
						String json = null;
						// read the inputStream into a buffer
						java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());
						scanner.useDelimiter("\\A");
						json =  scanner.hasNext() ? scanner.next() : "";
						scanner.close();
						LOGGER.info("PushPolicy API request: " + json);
						
						// convert Object sent as JSON into local object
						ObjectMapper mapper = new ObjectMapper();
						Object objectFromJSON = mapper.readValue(json, StdPDPPolicy.class);
						StdPDPPolicy policy = (StdPDPPolicy) objectFromJSON;
						
						// Assume that this is an update of an existing PDP Group
						loggingContext.setServiceName("PolicyEngineAPI:PAP.updateGroup");
						try{
							acPutTransaction.updateGroup(updatedGroup, "XACMLPapServlet.doACPut");
						} catch(Exception e){
							PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error occurred when notifying PAPs of a group change: "
									+ e);
							throw new PAPException(e.getMessage());	
						}
						
						LOGGER.info("Calling updatGroup() with new group");
						papEngine.updateGroup(updatedGroup);
						
						LOGGER.info("Group '" + updatedGroup.getId() + "' updated");
						
						// Commit transaction to send notification to other PAPs
						loggingContext.metricStarted();
						acPutTransaction.commitTransaction();
						loggingContext.metricEnded();
						PolicyLogger.metrics("XACMLPapServlet updateGroupsFromAPI commitTransaction");
						loggingContext.metricStarted();
						
						notifyAC();
						loggingContext.metricEnded();
						PolicyLogger.metrics("XACMLPapServlet updateGroupsFromAPI notifyAC");
						
						// Group changed to send notification to PDPs, which might include changing the policies	
						groupChanged(updatedGroup,loggingContext);
						loggingContext.transactionEnded();
						LOGGER.info("Success");

						if (policy != null && ((policy.getName().contains("Config_MS_")) || (policy.getId().contains("BRMS_Param")))) {
							PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance();
							if (pushPolicyHandler.preSafetyCheck(policy, configHome)) {
								LOGGER.debug("Precheck Successful.");
							}
						}
						
						//delete temporary policy file from the bin directory
						Files.deleteIfExists(Paths.get(policy.getId()));
						
					}
				} catch (Exception 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 occurred when updating the group from API.";
					LOGGER.error(message);
					setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
					response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
					response.addHeader("error","addGroupError");
					response.addHeader("message", 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);
				
				LOGGER.info("policy '" + policyId + "' copied to directory for group '" + groupId + "'");
				loggingContext.transactionEnded();
				auditLogger.info("Success");
				LOGGER.info("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);
					loggingContext.metricStarted();
					setDefaultGroupTransaction.commitTransaction();
					loggingContext.metricEnded();
					PolicyLogger.metrics("XACMLPapServlet doACPost 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");
					setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "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
				loggingContext.metricStarted();
				notifyAC();
				// This does not affect any PDPs in the existing groups, so no need to notify them of this change
				loggingContext.metricEnded();
				PolicyLogger.metrics("XACMLPapServlet doACPost notifyAC");
				loggingContext.transactionEnded();
				auditLogger.info("Success");
				LOGGER.info("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");
				OnapPDP pdp = papEngine.getPDP(pdpId);
				OnapPDPGroup originalGroup = papEngine.getPDPGroup((OnapPDP) pdp);
				try{
					doACPostTransaction.movePdp(pdp, group, "XACMLPapServlet.doACPost");
				}catch(Exception e){	
					doACPostTransaction.rollbackTransaction();
					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((OnapPDP) 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
				loggingContext.metricStarted();
				notifyAC();
				loggingContext.metricEnded();
				PolicyLogger.metrics("XACMLPapServlet doACPost notifyAC");
				// Need to notify the PDP that it's config may have changed
				pdpChanged(pdp, loggingContext);
				loggingContext.metricStarted();
				doACPostTransaction.commitTransaction();
				loggingContext.metricEnded();
				PolicyLogger.metrics("XACMLPapServlet doACPost commitTransaction");
				loggingContext.transactionEnded();
				auditLogger.info("Success");
				PolicyLogger.audit("Transaction Ended Successfully");
				return;
			}
		} catch (PAPException e) {
			PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC POST exception");
			loggingContext.transactionEnded();
			PolicyLogger.audit("Transaction Failed - See Error.log");
			setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
			return;
		}
	}

	/**
	 * 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, ONAPLoggingContext loggingContext) throws 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");
					OnapPDPGroup group = papEngine.getDefaultGroup();
					// convert response object to JSON and include in the response
					mapperWriteValue(new ObjectMapper(), response,  group);
					if (LOGGER.isDebugEnabled()) {
						LOGGER.debug("GET Default group req from '" + request.getRequestURL() + "'");
					}
					response.setStatus(HttpServletResponse.SC_OK);
					response.setHeader("content-type", "application/json");
					try{
                        response.getOutputStream().close();
                    } catch (IOException e){
                        LOGGER.error(e);
                    }
					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 (unspecified) group containing a given PDP
						loggingContext.setServiceName("AC:PAP.getPDP");
						OnapPDP pdp = null;
						try{
						    pdp = papEngine.getPDP(pdpId);
						}catch(PAPException e){
						    LOGGER.error(e);
						}
						// convert response object to JSON and include in the response
						mapperWriteValue(new ObjectMapper(), response,  pdp);
						if (LOGGER.isDebugEnabled()) {
							LOGGER.debug("GET pdp '" + pdpId + "' req from '" + request.getRequestURL() + "'");
						}
						response.setStatus(HttpServletResponse.SC_OK);
						response.setHeader("content-type", "application/json");
						try{
                            response.getOutputStream().close();
                        } catch (IOException e){
                            LOGGER.error(e);
                        }
						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");
						OnapPDPGroup group =null;
						try{
						    OnapPDP pdp = papEngine.getPDP(pdpId);
	                        group = papEngine.getPDPGroup((OnapPDP) pdp);
						}catch(PAPException e){
						    LOGGER.error(e);
						}
						// convert response object to JSON and include in the response
						mapperWriteValue(new ObjectMapper(), response,  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");
						try{
	                        response.getOutputStream().close();
	                    } catch (IOException e){
	                        LOGGER.error(e);
	                    }
						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<OnapPDPGroup> groups = papEngine.getOnapPDPGroups();
					// convert response object to JSON and include in the response
					mapperWriteValue(new ObjectMapper(), response,  groups);
					if (LOGGER.isDebugEnabled()) {
						LOGGER.debug("GET All groups req");
					}
					response.setStatus(HttpServletResponse.SC_OK);
					response.setHeader("content-type", "application/json");
					try{
	                    response.getOutputStream().close();
	                } catch (IOException e){
	                    LOGGER.error(e);
	                }
					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
			OnapPDPGroup group = null;
			try{
			    group = papEngine.getGroup(groupId);
			} catch(PAPException e){
			    LOGGER.error(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");
				setResponseError(response,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");
				setResponseError(response,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
				mapperWriteValue(new ObjectMapper(), response,  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");
				try{
				    response.getOutputStream().close();
				} catch (IOException e){
				    LOGGER.error(e);
				}
				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");
			setResponseError(response,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");
			setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, 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, ONAPLoggingContext 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
			OnapPDPGroup 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");
				setResponseError(response,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)
				try{
				    Scanner scanner = new Scanner(request.getInputStream());
				    scanner.useDelimiter("\\A");
	                json =  scanner.hasNext() ? scanner.next() : "";
	                scanner.close();
				}catch(IOException e){
				    LOGGER.error(e);
				}
				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");
					setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Bad input, pdpid="+pdpId+" object="+objectFromJSON);
				}
				StdPDP pdp = (StdPDP) objectFromJSON;
				if(pdp != null){
				    OnapPDP oPDP = null;
				    try{
				        oPDP = papEngine.getPDP(pdpId);
				    }catch (PAPException e){
				        LOGGER.error(e);
				    }
					if (oPDP == 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());
						}
						try{
						    papEngine.newPDP(pdp.getId(), group, pdp.getName(), pdp.getDescription(), pdp.getJmxPort());
						}catch(PAPException e){
						    LOGGER.error(e);
						}
					} 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
						try{
						    papEngine.updatePDP(pdp);
						}catch(PAPException e){
                            LOGGER.error(e);
                        }
					}
					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
					loggingContext.metricStarted();
					notifyAC();
					loggingContext.metricEnded();
					PolicyLogger.metrics("XACMLPapServlet doACPut notifyAC");
					// this might affect the PDP, so notify it of the change
					pdpChanged(pdp, loggingContext);
					loggingContext.metricStarted();
					acPutTransaction.commitTransaction();
					loggingContext.metricEnded();
					PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction");
					loggingContext.transactionEnded();
					auditLogger.info("Success");
					PolicyLogger.audit("Transaction Ended Successfully");
					return;
				}else{
					try{
						PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, "XACMLPapServlet", " Error while adding pdp to group in the database: "
								+"pdp=null" + ",to group="+group.getId());
						throw new PAPException("PDP is null");
					} catch(Exception e){
						throw new PAPException("PDP is null" + e.getMessage() +e);
					}
				}
			} 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");
				setResponseError(response,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)
                try{
                    Scanner scanner = new Scanner(request.getInputStream());
                    scanner.useDelimiter("\\A");
                    json =  scanner.hasNext() ? scanner.next() : "";
                    scanner.close();
                }catch(IOException e){
                    LOGGER.error(e);
                }
				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");
					setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "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
				if(objectFromJSON != null){
					((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());
					LOGGER.error(e);
					throw new PAPException(e.getMessage());
				}
				
				PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance();	
				OnapPDPGroup updatedGroup = (StdPDPGroup)objectFromJSON;	
				if (pushPolicyHandler.preSafetyCheck(updatedGroup, configHome)) {		
					LOGGER.debug("Precheck Successful.");
				}
				try{
				    papEngine.updateGroup((StdPDPGroup)objectFromJSON);
				}catch(PAPException e){
				    LOGGER.error(e);
				}
				response.setStatus(HttpServletResponse.SC_NO_CONTENT);
				if (LOGGER.isDebugEnabled()) {
					LOGGER.debug("Group '" + group.getId() + "' updated");
				}
				loggingContext.metricStarted();
				acPutTransaction.commitTransaction();
				loggingContext.metricEnded();
				PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction");
				// tell the Admin Consoles there is a change
				loggingContext.metricStarted();
				notifyAC();
				loggingContext.metricEnded();
				PolicyLogger.metrics("XACMLPapServlet doACPut notifyAC");
				// Group changed, which might include changing the policies
				groupChanged(group, loggingContext);
				loggingContext.transactionEnded();
				auditLogger.info("Success");
				PolicyLogger.audit("Transaction Ended Successfully");
				return;
			}
		} catch (PAPException e) {
			LOGGER.debug(e);
			acPutTransaction.rollbackTransaction();
			PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC PUT exception");
			loggingContext.transactionEnded();
			PolicyLogger.audit("Transaction Failed - See Error.log");
			setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, 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, ONAPLoggingContext loggingContext) throws IOException {
		//This code is 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){
				LOGGER.error("Unsupported URL encoding of policyToDelete (UTF-8", e);
				setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR,"policyToDelete encoding not supported");
				return;
			}
			PolicyDBDaoTransaction deleteTransaction = policyDBDao.getNewTransaction();
			try{
				deleteTransaction.deletePolicy(policyToDelete);
			} catch(Exception e){
				deleteTransaction.rollbackTransaction();
				setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR,"deleteTransaction.deleteTransaction(policyToDelete) "
						+ "\nfailure with the following exception: " + e);
				return;
			}
			loggingContext.metricStarted();
			deleteTransaction.commitTransaction();
			loggingContext.metricEnded();
			PolicyLogger.metrics("XACMLPapServlet doACPut 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");
			OnapPDPGroup 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");
				setResponseError(response,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");
				loggingContext.transactionEnded();
				PolicyLogger.audit("Transaction Failed - See Error.log");
				setResponseError(response,HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
				return;
			} else if (request.getParameter("pdpId") != null) {
				// ARGS:        group=<groupId> pdpId=<pdpId>                  <= delete PDP 
				String pdpId = request.getParameter("pdpId");
				OnapPDP pdp = papEngine.getPDP(pdpId);
				try{
					removePdpOrGroupTransaction.removePdpFromGroup(pdp.getId(),"XACMLPapServlet.doACDelete");
				} catch(Exception e){
					throw new PAPException(e);
				}
				try{
	                papEngine.removePDP((OnapPDP) pdp);
				}catch(PAPException e){
                    LOGGER.error(e);
                }
				// adjust the status of the group, which may have changed when we removed this PDP
				((StdPDPGroup)group).resetStatus();
				response.setStatus(HttpServletResponse.SC_NO_CONTENT);
				loggingContext.metricStarted();
				notifyAC();
				loggingContext.metricEnded();
				PolicyLogger.metrics("XACMLPapServlet doACPut notifyAC");
				// update the PDP and tell it that it has NO Policies (which prevents it from serving PEP Requests)
				pdpChanged(pdp, loggingContext);
				loggingContext.metricStarted();
				removePdpOrGroupTransaction.commitTransaction();
				loggingContext.metricEnded();
				PolicyLogger.metrics("XACMLPapServlet doACPut 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");
				setResponseError(response,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");
				OnapPDPGroup moveToGroup = null;
				if (moveToGroupId != null) {
				    try{
				        moveToGroup = papEngine.getGroup(moveToGroupId);
				    }catch(PAPException e){
	                    LOGGER.error(e);
	                }
				}
				// get list of PDPs in the group being deleted so we can notify them that they got changed
				Set<OnapPDP> movedPDPs = new HashSet<>();
				movedPDPs.addAll(group.getOnapPdps());
				// 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");
					throw new PAPException(e.getMessage());
				}
				try{
				    papEngine.removeGroup(group, moveToGroup);
				}catch(PAPException e){
                    LOGGER.error(e);
                }
				response.setStatus(HttpServletResponse.SC_NO_CONTENT);
				loggingContext.metricStarted();
				notifyAC();
				loggingContext.metricEnded();
				PolicyLogger.metrics("XACMLPapServlet doACPut notifyAC");
				// notify any PDPs in the removed set that their config may have changed
				for (OnapPDP pdp : movedPDPs) {
					pdpChanged(pdp, loggingContext);
				}
				loggingContext.metricStarted();
				removePdpOrGroupTransaction.commitTransaction();
				loggingContext.metricEnded();
				PolicyLogger.metrics("XACMLPapServlet doACPut 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");
			setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
			return;
		}
	}
	
	/**
	 * 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<OnapPDP> pdps = new HashSet<>();
		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) {
			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<>();
			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 (OnapPDPGroup g : papEngine.getOnapPDPGroups()) {
								for (OnapPDP p : g.getOnapPdps()) {
									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 (OnapPDP 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
							if(pdpURL != null){
								connection = (HttpURLConnection)pdpURL.openConnection();
								// Setup our method and headers
								connection.setRequestMethod("GET");
								connection.setConnectTimeout(heartbeatTimeout);
								// 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
							if(connection != null)
								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();
				Thread.currentThread().interrupt();
			}
		}
	}

	/*
	 * 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(OnapPDP pdp, PDPStatus.Status newStatus) throws PAPException {
		setPDPSummaryStatus(pdp, newStatus.toString());
	}

	private void setPDPSummaryStatus(OnapPDP 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((OnapPDP) 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<OnapPDPGroup> groups;
		try {
			groups = papEngine.getOnapPDPGroups();
		} catch (PAPException e) {
			PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " getPDPGroups failed");
			throw new IllegalAccessError(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get Groups: " + e);
		}
		for (OnapPDPGroup group : groups) {
			groupChanged(group);
		}
	}
	
	public void changed(ONAPLoggingContext loggingContext) {
		// all PDPs in all groups need to be updated/sync'd
		Set<OnapPDPGroup> groups;
		try {
			groups = papEngine.getOnapPDPGroups();
		} catch (PAPException e) {
			PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " getPDPGroups failed");
			throw new IllegalAccessError(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get Groups: " + e);
		}
		for (OnapPDPGroup group : groups) {
			groupChanged(group, loggingContext);
		}
	}
	
	@Override
	public void groupChanged(OnapPDPGroup group) {
		// all PDPs within one group need to be updated/sync'd
		for (OnapPDP pdp : group.getOnapPdps()) {
			pdpChanged(pdp);
		}
	}

	public void groupChanged(OnapPDPGroup group, ONAPLoggingContext loggingContext) {
		// all PDPs within one group need to be updated/sync'd
		for (OnapPDP pdp : group.getOnapPdps()) {
			pdpChanged(pdp, loggingContext);
		}
	}

	@Override
	 public void pdpChanged(OnapPDP 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.
		Thread t = new Thread(new UpdatePDPThread(pdp));
		if(CheckPDP.validateID(pdp.getId())){
			t.start();
		}
	}
	
	 public void pdpChanged(OnapPDP pdp, ONAPLoggingContext loggingContext) {
		// 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.
		Thread t = new Thread(new UpdatePDPThread(pdp, loggingContext));
		if(CheckPDP.validateID(pdp.getId())){
			t.start();
		}
	}

	private class UpdatePDPThread implements Runnable {
		private OnapPDP pdp;
		private String requestId;
		private ONAPLoggingContext loggingContext;

		public UpdatePDPThread(OnapPDP pdp) {
			this.pdp = pdp;
		}

		public UpdatePDPThread(OnapPDP pdp, ONAPLoggingContext loggingContext) {
			this.pdp = pdp;
			if (!(loggingContext == null)) {
				if (!(loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")) {
					this.requestId = loggingContext.getRequestID();
				}
			}
			this.loggingContext = loggingContext;
		}

		public void run() {
			// send the current configuration to one PDP
			HttpURLConnection connection = null;
			// get a new logging context for the thread
			try {
				if (this.loggingContext.equals(null)) {
				     loggingContext = new ONAPLoggingContext(baseLoggingContext);
				} 
			} 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;
     		}
			try {
				loggingContext.setServiceName("PAP:PDP.putConfig");
				// If a requestId was provided, use it, otherwise generate one; post to loggingContext to be used later when calling PDP
				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());
				}
				loggingContext.transactionStarted();
				// 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");
				// Authentication
				String encoding = CheckPDP.getEncoding(pdp.getId());
				if(encoding !=null){
					connection.setRequestProperty("Authorization", "Basic " + encoding);
				}
				connection.setRequestProperty("Content-Type", "text/x-java-properties");
				connection.setRequestProperty("X-ECOMP-RequestID", loggingContext.getRequestID());
				connection.setInstanceFollowRedirects(true);
				connection.setDoOutput(true);
				try (OutputStream os = connection.getOutputStream()) {
					OnapPDPGroup group = papEngine.getPDPGroup((OnapPDP) 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
				loggingContext.metricStarted();
				connection.connect();
				loggingContext.metricEnded();
				PolicyLogger.metrics("XACMLPapServlet UpdatePDPThread 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) {
				LOGGER.debug(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) {
					LOGGER.debug(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
				if(connection != null){
					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<>();
			// 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) {
					PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Unable to sync config AC '" + acURL + "'");
					disconnectedACs.add(acURL);
				} finally {
					// cleanup the connection
					if(connection != null)
						connection.disconnect();
				}
			}
			// remove any ACs that are no longer connected
			if (disconnectedACs.size() > 0) {
				adminConsoleURLStringList.removeAll(disconnectedACs);
			}
		}
	}

	private void testService(ONAPLoggingContext loggingContext, HttpServletResponse response) throws IOException{
		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 | AdministrativeStateException | StandbyStatusException e){
			String submsg;
			if (e instanceof ForwardProgressException) {
				submsg = " is not making forward progress.";
			} else if (e instanceof AdministrativeStateException) {
				submsg = " Administrative State is LOCKED.";
			} else {
				submsg = " Standby Status is NOT PROVIDING SERVICE.";
			}

			String message = "GET:/pap/test called and PAP " + papResourceName + submsg
					+ " Exception Message: " + e.getMessage();
			LOGGER.info(message, e);
			PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
			loggingContext.transactionEnded();
			PolicyLogger.audit("Transaction Failed - See Error.log");
			setResponseError(response,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, e);
			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-ONAP-SubsystemFailure", ssFailureList);
			setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
			return;
		}
	}

	/*
	 * Authorizing the PEP Requests. 
	 */
	private boolean authorizeRequest(HttpServletRequest request) { 
		String clientCredentials = request.getHeader(ENVIRONMENT_HEADER);
		// Check if the Client is Authorized. 
		if(clientCredentials!=null && clientCredentials.equalsIgnoreCase(environment)){
			return true;
		}else{
			return false;
		}
	}

	private static void loadWebapps() throws PAPException{
		if(actionHome == null || configHome == 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 PAPException("Invalid Webapps Path Location property : " + XACMLRestProperties.PROP_PAP_WEBAPPS);
			}
			Path webappsPathConfig = Paths.get(webappsPath.toString()+File.separator+"Config");
			Path webappsPathAction = Paths.get(webappsPath.toString()+File.separator+"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 action directory: "
							+ webappsPathAction.toAbsolutePath().toString(), e);
				}
			}
			actionHome = webappsPathAction.toString();
			configHome = webappsPathConfig.toString();
		}
	}

	public static String getConfigHome(){
		try {
			loadWebapps();
		} catch (PAPException e) {
			LOGGER.debug(e);
			return null;
		}
		return configHome;
	}
	
	private static void setConfigHome(){
	    configHome = getConfigHome();
	}

	public static String getActionHome(){
		try {
			loadWebapps();
		} catch (PAPException e) {
			LOGGER.debug(e);
			return null;
		}
		return actionHome;
	}
	
	private static void setActionHome(){
	    actionHome = getActionHome();
	}

	public static EntityManagerFactory getEmf() {
		return emf;
	}
	
	public IntegrityAudit getIa() {
		return ia;
	}
	
	public static String getPDPFile(){
		return XACMLPapServlet.pdpFile;
	}
	
	public static String getPersistenceUnit(){
		return PERSISTENCE_UNIT;
	}
	
	public static PAPPolicyEngine getPAPEngine(){
		return papEngine;
	}
	
	public static PolicyDBDaoTransaction getDbDaoTransaction(){
		return policyDBDao.getNewTransaction();
	}
	public static String getPapDbDriver() {
		return papDbDriver;
	}

	public static void setPapDbDriver(String papDbDriver) {
		XACMLPapServlet.papDbDriver = papDbDriver;
	}

	public static String getPapDbUrl() {
		return papDbUrl;
	}

	public static void setPapDbUrl(String papDbUrl) {
		XACMLPapServlet.papDbUrl = papDbUrl;
	}

	public static String getPapDbUser() {
		return papDbUser;
	}

	public static void setPapDbUser(String papDbUser) {
		XACMLPapServlet.papDbUser = papDbUser;
	}

	public static String getPapDbPassword() {
		return papDbPassword;
	}

	public static void setPapDbPassword(String papDbPassword) {
		XACMLPapServlet.papDbPassword = papDbPassword;
	}

	public static String getMsOnapName() {
		return msOnapName;
	}

	public static void setMsOnapName(String msOnapName) {
		XACMLPapServlet.msOnapName = msOnapName;
	}

	public static String getMsPolicyName() {
		return msPolicyName;
	}

	public static void setMsPolicyName(String msPolicyName) {
		XACMLPapServlet.msPolicyName = msPolicyName;
	}
}