aboutsummaryrefslogtreecommitdiffstats
path: root/policy-management/src/main/java/org/onap/policy/drools/server/restful/RestManager.java
blob: ecc6c083d457796c47860510c72cd1aa392b9b95 (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
/*
 * ============LICENSE_START=======================================================
 * ONAP
 * ================================================================================
 * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
 * Modifications Copyright (C) 2021, 2023-2024 Nordix Foundation.
 * ================================================================================
 * 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.drools.server.restful;

import ch.qos.logback.classic.LoggerContext;
import com.google.re2j.Pattern;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.DefaultValue;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.Status;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.UUID;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.onap.policy.common.endpoints.event.comm.Topic;
import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
import org.onap.policy.common.endpoints.event.comm.TopicEndpointManager;
import org.onap.policy.common.endpoints.event.comm.TopicSink;
import org.onap.policy.common.endpoints.event.comm.TopicSource;
import org.onap.policy.common.endpoints.http.server.YamlMessageBodyHandler;
import org.onap.policy.common.utils.logging.LoggerUtils;
import org.onap.policy.drools.controller.DroolsController;
import org.onap.policy.drools.properties.DroolsPropertyConstants;
import org.onap.policy.drools.protocol.coders.EventProtocolCoder.CoderFilters;
import org.onap.policy.drools.protocol.coders.EventProtocolCoderConstants;
import org.onap.policy.drools.protocol.coders.JsonProtocolFilter;
import org.onap.policy.drools.protocol.coders.ProtocolCoderToolset;
import org.onap.policy.drools.protocol.configuration.ControllerConfiguration;
import org.onap.policy.drools.protocol.configuration.PdpdConfiguration;
import org.onap.policy.drools.system.PolicyController;
import org.onap.policy.drools.system.PolicyControllerConstants;
import org.onap.policy.drools.system.PolicyEngineConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Telemetry JAX-RS Interface to the PDP-D.
 */

@Path("/policy/pdp")
@Produces({MediaType.APPLICATION_JSON, YamlMessageBodyHandler.APPLICATION_YAML})
@Consumes({MediaType.APPLICATION_JSON, YamlMessageBodyHandler.APPLICATION_YAML})
@ToString
public class RestManager implements SwaggerApi, DefaultApi, FeaturesApi, InputsApi,
        PropertiesApi, EnvironmentApi, SwitchesApi, ControllersApi,
        TopicsApi, ToolsApi {

    private static final String OFFER_FAILED = "{}: cannot offer to topic {} because of {}";
    private static final String CANNOT_PERFORM_OPERATION = "cannot perform operation";
    private static final String NO_FILTERS = " no filters";
    private static final String NOT_FOUND = " not found: ";
    private static final String NOT_FOUND_MSG = " not found";
    private static final String DOES_NOT_EXIST_MSG = " does not exist";
    private static final String NOT_ACCEPTABLE_MSG = " not acceptable";
    private static final String FETCH_POLICY_FAILED = "{}: cannot get policy-controller because of {}";
    private static final String FETCH_POLICY_BY_NAME_FAILED = "{}: cannot get policy-controller {} because of {}";
    private static final String FETCH_POLICY_BY_TOPIC_FAILED =
        "{}: cannot get policy-controller {} topic {} because of {}";
    private static final String FETCH_DROOLS_FAILED = "{}: cannot get drools-controller {} because of {}";
    private static final String FETCH_DROOLS_BY_ENTITY_FAILED =
        "{}: cannot get: drools-controller {}, session {}, query {}, entity {} because of {}";
    private static final String FETCH_DROOLS_BY_PARAMS_FAILED =
        "{}: cannot get: drools-controller {}, session {}, query {}, entity {}, params {} because of {}";
    private static final String FETCH_DROOLS_BY_FACTTYPE_FAILED =
        "{}: cannot get: drools-controller {}, session {}, factType {}, because of {}";
    private static final String FETCH_DECODERS_BY_POLICY_FAILED =
        "{}: cannot get decoders for policy-controller {} because of {}";
    private static final String FETCH_DECODERS_BY_TOPIC_FAILED =
        "{}: cannot get decoders for policy-controller {} topic {} because of {}";
    private static final String FETCH_DECODER_BY_TYPE_FAILED =
        "{}: cannot get decoder filters for policy-controller {} topic {} type {} because of {}";
    private static final String FETCH_DECODER_BY_FILTER_FAILED =
        "{}: cannot get decoder filters for policy-controller {} topic {} type {} filters {} because of {}";
    private static final String FETCH_ENCODER_BY_FILTER_FAILED =
        "{}: cannot get encoder filters for policy-controller {} because of {}";

    private static final String SWAGGER = "/swagger/swagger.json";

    /**
     * Logger.
     */
    private static final Logger logger = LoggerFactory.getLogger(RestManager.class);

    /**
     * Feed Ports into Resources.
     */
    private static final List<String> INPUTS = Collections.singletonList("configuration");

    /**
     * Resource Toggles.
     */
    private static final List<String> SWITCHES = Arrays.asList("activation", "lock");

    /**
     * GET.
     *
     * @return response object
     */
    @Override
    @GET
    @Path("engine/swagger")
    public Response swagger() {

        try (InputStream inputStream = getClass().getResourceAsStream(SWAGGER);
            BufferedReader reader = new BufferedReader(
                new InputStreamReader(Objects.requireNonNull(inputStream)))) {
            String contents = reader.lines()
                    .collect(Collectors.joining(System.lineSeparator()));
            return Response.status(Response.Status.OK)
                        .entity(contents)
                        .build();
        } catch (IOException e) {
            logger.error("Cannot read swagger.json {} because of {}", e.getMessage(), e);
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
                    .build();
        }

    }

    /**
     * GET.
     *
     * @return response object
     */
    @Override
    @GET
    @Path("engine")
    public Response engine() {
        return Response.status(Response.Status.OK).entity(PolicyEngineConstants.getManager()).build();
    }

    /**
     * DELETE.
     *
     * @return response object
     */
    @Override
    @DELETE
    @Path("engine")
    public Response engineShutdown() {
        try {
            PolicyEngineConstants.getManager().shutdown();
        } catch (final IllegalStateException e) {
            logger.error("{}: cannot shutdown {} because of {}", this, PolicyEngineConstants.getManager(),
                e.getMessage(), e);
            return Response.status(Response.Status.BAD_REQUEST).entity(PolicyEngineConstants.getManager()).build();
        }

        return Response.status(Response.Status.OK).entity(PolicyEngineConstants.getManager()).build();
    }

    /**
     * GET.
     *
     * @return response object
     */
    @Override
    @GET
    @Path("engine/features")
    public Response engineFeatures() {
        return Response.status(Response.Status.OK).entity(PolicyEngineConstants.getManager().getFeatures()).build();
    }

    @Override
    @GET
    @Path("engine/features/inventory")
    public Response engineFeaturesInventory() {
        return Response.status(Response.Status.OK).entity(PolicyEngineConstants.getManager().getFeatureProviders())
            .build();
    }

    /**
     * GET.
     *
     * @return response object
     */
    @Override
    @GET
    @Path("engine/features/{featureName}")
    public Response engineFeature(@PathParam("featureName") String featureName) {
        try {
            return Response.status(Response.Status.OK)
                .entity(PolicyEngineConstants.getManager().getFeatureProvider(featureName)).build();
        } catch (final IllegalArgumentException iae) {
            logger.debug("feature unavailable: {}", featureName, iae);
            return Response.status(Response.Status.NOT_FOUND).entity(new Error(iae.getMessage())).build();
        }
    }

    /**
     * GET.
     *
     * @return response object
     */
    @Override
    @GET
    @Path("engine/inputs")
    public Response engineInputs() {
        return Response.status(Response.Status.OK).entity(INPUTS).build();
    }

    /**
     * POST.
     *
     * @return response object
     */
    @Override
    @POST
    @Path("engine/inputs/configuration")
    public Response engineUpdate(PdpdConfiguration configuration) {
        final PolicyController controller = null;
        boolean success;
        try {
            success = PolicyEngineConstants.getManager().configure(configuration);
        } catch (final Exception e) {
            success = false;
            logger.info("{}: cannot configure {} because of {}", this, PolicyEngineConstants.getManager(),
                e.getMessage(), e);
        }

        if (!success) {
            return Response.status(Response.Status.NOT_ACCEPTABLE).entity(new Error(CANNOT_PERFORM_OPERATION))
                .build();
        } else {
            return Response.status(Response.Status.OK).entity(controller).build();
        }
    }

    /**
     * GET.
     *
     * @return response object
     */
    @Override
    @GET
    @Path("engine/properties")
    public Response engineProperties() {
        return Response.status(Response.Status.OK).entity(PolicyEngineConstants.getManager().getProperties()).build();
    }

    /**
     * GET.
     *
     * @return response object
     */
    @Override
    @GET
    @Path("engine/environment")
    public Response engineEnvironment() {
        return Response.status(Response.Status.OK).entity(PolicyEngineConstants.getManager().getEnvironment()).build();
    }

    /**
     * GET.
     *
     * @return response object
     */
    @Override
    @GET
    @Path("engine/environment/{envProperty}")
    @Consumes(MediaType.TEXT_PLAIN)
    public Response engineEnvironmentProperty(@PathParam("envProperty") String envProperty) {
        return Response.status(Response.Status.OK)
            .entity(PolicyEngineConstants.getManager().getEnvironmentProperty(envProperty)).build();
    }

    /**
     * PUT.
     *
     * @return response object
     */
    @Override
    @PUT
    @Path("engine/environment/{envProperty}")
    @Consumes(MediaType.TEXT_PLAIN)
    @Produces(MediaType.TEXT_PLAIN)
    public Response engineEnvironmentAdd(@PathParam("envProperty") String envProperty, String envValue) {
        final String previousValue = PolicyEngineConstants.getManager().setEnvironmentProperty(envProperty, envValue);
        return Response.status(Response.Status.OK).entity(previousValue).build();
    }

    /**
     * GET.
     *
     * @return response object
     */
    @Override
    @GET
    @Path("engine/switches")
    public Response engineSwitches() {
        return Response.status(Response.Status.OK).entity(SWITCHES).build();
    }

    /**
     * PUT.
     *
     * @return response object
     */
    @Override
    @PUT
    @Path("engine/switches/activation")
    public Response engineActivation() {
        var success = true;
        try {
            PolicyEngineConstants.getManager().activate();
        } catch (final Exception e) {
            success = false;
            logger.info("{}: cannot activate {} because of {}", this, PolicyEngineConstants.getManager(),
                e.getMessage(), e);
        }

        if (!success) {
            return Response.status(Response.Status.NOT_ACCEPTABLE).entity(new Error(CANNOT_PERFORM_OPERATION))
                .build();
        } else {
            return Response.status(Response.Status.OK).entity(PolicyEngineConstants.getManager()).build();
        }
    }

    /**
     * DELETE.
     *
     * @return response object
     */
    @Override
    @DELETE
    @Path("engine/switches/activation")
    public Response engineDeactivation() {
        var success = true;
        try {
            PolicyEngineConstants.getManager().deactivate();
        } catch (final Exception e) {
            success = false;
            logger.info("{}: cannot deactivate {} because of {}", this, PolicyEngineConstants.getManager(),
                e.getMessage(), e);
        }

        if (!success) {
            return Response.status(Response.Status.NOT_ACCEPTABLE).entity(new Error(CANNOT_PERFORM_OPERATION))
                .build();
        } else {
            return Response.status(Response.Status.OK).entity(PolicyEngineConstants.getManager()).build();
        }
    }

    /**
     * PUT.
     *
     * @return response object
     */
    @Override
    @PUT
    @Path("engine/switches/lock")
    public Response engineLock() {
        final boolean success = PolicyEngineConstants.getManager().lock();
        if (success) {
            return Response.status(Status.OK).entity(PolicyEngineConstants.getManager()).build();
        } else {
            return Response.status(Status.NOT_ACCEPTABLE).entity(new Error(CANNOT_PERFORM_OPERATION)).build();
        }
    }

    /**
     * DELETE.
     *
     * @return response object
     */
    @Override
    @DELETE
    @Path("engine/switches/lock")
    public Response engineUnlock() {
        final boolean success = PolicyEngineConstants.getManager().unlock();
        if (success) {
            return Response.status(Status.OK).entity(PolicyEngineConstants.getManager()).build();
        } else {
            return Response.status(Status.NOT_ACCEPTABLE).entity(new Error(CANNOT_PERFORM_OPERATION)).build();
        }
    }

    /**
     * GET.
     *
     * @return response object
     */
    @Override
    @GET
    @Path("engine/controllers")
    public Response controllers() {
        return Response.status(Response.Status.OK).entity(PolicyEngineConstants.getManager().getPolicyControllerIds())
            .build();
    }

    /**
     * GET.
     *
     * @return response object
     */
    @Override
    @GET
    @Path("engine/controllers/inventory")
    public Response controllerInventory() {
        return Response.status(Response.Status.OK).entity(PolicyEngineConstants.getManager().getPolicyControllers())
            .build();
    }

    /**
     * POST.
     *
     * @return response object
     */
    @Override
    @POST
    @Path("engine/controllers")
    public Response controllerAdd(Properties config) {
        if (config == null) {
            return Response.status(Response.Status.BAD_REQUEST).entity(new Error("A configuration must be provided"))
                .build();
        }

        final String controllerName = config.getProperty(DroolsPropertyConstants.PROPERTY_CONTROLLER_NAME);
        if (controllerName == null || controllerName.isEmpty()) {
            return Response.status(Response.Status.BAD_REQUEST)
                .entity(new Error(
                    "Configuration must have an entry for " + DroolsPropertyConstants.PROPERTY_CONTROLLER_NAME))
                .build();
        }

        PolicyController controller;
        try {
            controller = PolicyControllerConstants.getFactory().get(controllerName);
            if (controller != null) {
                return Response.status(Response.Status.NOT_MODIFIED).entity(controller).build();
            }
        } catch (final IllegalArgumentException e) {
            logger.trace("OK ", e);
            // This is OK
        } catch (final IllegalStateException e) {
            logger.info(FETCH_POLICY_FAILED, this, e.getMessage(), e);
            return Response.status(Response.Status.NOT_ACCEPTABLE).entity(new Error(controllerName + NOT_FOUND_MSG))
                .build();
        }

        try {
            controller = PolicyEngineConstants.getManager().createPolicyController(
                config.getProperty(DroolsPropertyConstants.PROPERTY_CONTROLLER_NAME), config);
        } catch (IllegalArgumentException | IllegalStateException e) {
            logger.warn("{}: cannot create policy-controller because of {}", this, e.getMessage(), e);
            return Response.status(Response.Status.BAD_REQUEST).entity(new Error(e.getMessage())).build();
        }

        try {
            final boolean success = controller.start();
            if (!success) {
                logger.info("{}: cannot start {}", this, controller);
                return Response.status(Response.Status.PARTIAL_CONTENT)
                    .entity(new Error(controllerName + " can't be started")).build();
            }
        } catch (final IllegalStateException e) {
            logger.info("{}: cannot start {} because of {}", this, controller, e.getMessage(), e);
            return Response.status(Response.Status.PARTIAL_CONTENT).entity(controller).build();
        }

        return Response.status(Response.Status.CREATED).entity(controller).build();
    }

    /**
     * GET.
     *
     * @return response object
     */
    @Override
    @GET
    @Path("engine/controllers/features")
    public Response controllerFeatures() {
        return Response.status(Response.Status.OK).entity(PolicyEngineConstants.getManager().getFeatures()).build();
    }

    /**
     * GET.
     *
     * @return response object
     */
    @Override
    @GET
    @Path("engine/controllers/features/inventory")
    public Response controllerFeaturesInventory() {
        return Response.status(Response.Status.OK)
            .entity(PolicyControllerConstants.getFactory().getFeatureProviders()).build();
    }

    /**
     * GET.
     *
     * @return response object
     */
    @Override
    @GET
    @Path("engine/controllers/features/{featureName}")
    public Response controllerFeature(@PathParam("featureName") String featureName) {
        try {
            return Response.status(Response.Status.OK)
                .entity(PolicyControllerConstants.getFactory().getFeatureProvider(featureName))
                .build();
        } catch (final IllegalArgumentException iae) {
            logger.debug("{}: cannot feature {} because of {}", this, featureName, iae.getMessage(), iae);
            return Response.status(Response.Status.NOT_FOUND).entity(new Error(iae.getMessage())).build();
        }
    }

    /**
     * GET.
     *
     * @return response object
     */
    @Override
    @GET
    @Path("engine/controllers/{controller}")
    public Response controller(@PathParam("controller") String controllerName) {

        return catchArgStateGenericEx(
            () -> Response.status(Response.Status.OK)
                .entity(PolicyControllerConstants.getFactory().get(controllerName)).build(),
            e -> {
                logger.debug(FETCH_POLICY_BY_NAME_FAILED, this, controllerName, e.getMessage(), e);
                return (controllerName);
            });
    }

    /**
     * DELETE.
     *
     * @return response object
     */
    @Override
    @DELETE
    @Path("engine/controllers/{controller}")
    public Response controllerDelete(@PathParam("controller") String controllerName) {

        PolicyController controller;
        try {
            controller = PolicyControllerConstants.getFactory().get(controllerName);
            if (controller == null) {
                return Response.status(Response.Status.BAD_REQUEST)
                    .entity(new Error(controllerName + DOES_NOT_EXIST_MSG)).build();
            }
        } catch (final IllegalArgumentException e) {
            logger.debug(FETCH_POLICY_BY_NAME_FAILED, this, controllerName, e.getMessage(), e);
            return Response.status(Response.Status.BAD_REQUEST)
                .entity(new Error(controllerName + NOT_FOUND + e.getMessage())).build();
        } catch (final IllegalStateException e) {
            logger.debug(FETCH_POLICY_BY_NAME_FAILED, this, controllerName, e.getMessage(), e);
            return Response.status(Response.Status.NOT_ACCEPTABLE)
                .entity(new Error(controllerName + NOT_ACCEPTABLE_MSG)).build();
        }

        try {
            PolicyEngineConstants.getManager().removePolicyController(controllerName);
        } catch (IllegalArgumentException | IllegalStateException e) {
            logger.debug("{}: cannot remove policy-controller {} because of {}", this, controllerName, e.getMessage(),
                e);
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(new Error(e.getMessage())).build();
        }

        return Response.status(Response.Status.OK).entity(controller).build();
    }

    /**
     * GET.
     *
     * @return response object
     */
    @Override
    @GET
    @Path("engine/controllers/{controller}/properties")

    public Response controllerProperties(@PathParam("controller") String controllerName) {

        return catchArgStateGenericEx(() -> {
            final PolicyController controller = PolicyControllerConstants.getFactory().get(controllerName);
            return Response.status(Response.Status.OK).entity(controller.getProperties()).build();

        }, e -> {
            logger.debug(FETCH_POLICY_BY_NAME_FAILED, this, controllerName, e.getMessage(), e);
            return (controllerName);
        });
    }

    /**
     * GET.
     *
     * @return response object
     */
    @Override
    @GET
    @Path("engine/controllers/{controller}/inputs")
    public Response controllerInputs(@PathParam("controller") String controllerName) {
        return Response.status(Response.Status.OK).entity(INPUTS).build();
    }

    /**
     * POST.
     *
     * @return response object
     */
    @Override
    @POST
    @Path("engine/controllers/{controller}/inputs/configuration")
    public Response controllerUpdate(ControllerConfiguration controllerConfiguration,
            @PathParam("controller") String controllerName) {

        if (controllerName == null || controllerName.isEmpty() || controllerConfiguration == null
            || !controllerName.equals(controllerConfiguration.getName())) {
            return Response.status(Response.Status.BAD_REQUEST)
                .entity("A valid or matching controller names must be provided").build();
        }

        return catchArgStateGenericEx(() -> {
            var controller =
                PolicyEngineConstants.getManager().updatePolicyController(controllerConfiguration);
            if (controller == null) {
                return Response.status(Response.Status.BAD_REQUEST)
                    .entity(new Error(controllerName + DOES_NOT_EXIST_MSG)).build();
            }

            return Response.status(Response.Status.OK).entity(controller).build();

        }, e -> {
            logger.info("{}: cannot update policy-controller {} because of {}", this, controllerName,
                e.getMessage(), e);
            return (controllerName);
        });
    }

    /**
     * GET.
     *
     * @return response object
     */
    @Override
    @GET
    @Path("engine/controllers/{controller}/switches")
    public Response controllerSwitches(@PathParam("controller") String controllerName) {
        return Response.status(Response.Status.OK).entity(SWITCHES).build();
    }

    /**
     * PUT.
     *
     * @return response object
     */
    @Override
    @PUT
    @Path("engine/controllers/{controller}/switches/lock")
    public Response controllerLock(@PathParam("controller") String controllerName) {
        var policyController = PolicyControllerConstants.getFactory().get(controllerName);
        final boolean success = policyController.lock();
        if (success) {
            return Response.status(Status.OK).entity(policyController).build();
        } else {
            return Response.status(Status.NOT_ACCEPTABLE)
                .entity(new Error("Controller " + controllerName + " cannot be locked")).build();
        }
    }

    /**
     * DELETE.
     *
     * @return response object
     */
    @Override
    @DELETE
    @Path("engine/controllers/{controller}/switches/lock")
    public Response controllerUnlock(@PathParam("controller") String controllerName) {
        var policyController = PolicyControllerConstants.getFactory().get(controllerName);
        final boolean success = policyController.unlock();
        if (success) {
            return Response.status(Status.OK).entity(policyController).build();
        } else {
            return Response.status(Status.NOT_ACCEPTABLE)
                .entity(new Error("Controller " + controllerName + " cannot be unlocked")).build();
        }
    }

    /**
     * GET.
     *
     * @return response object
     */
    @Override
    @GET
    @Path("engine/controllers/{controller}/drools")
    public Response drools(@PathParam("controller") String controllerName) {

        return catchArgStateGenericEx(() -> {
            var drools = this.getDroolsController(controllerName);
            return Response.status(Response.Status.OK).entity(drools).build();

        }, e -> {
            logger.debug(FETCH_DROOLS_FAILED, this, controllerName, e.getMessage(), e);
            return (controllerName);
        });
    }

    /**
     * GET.
     *
     * @return response object
     */
    @Override
    @GET
    @Path("engine/controllers/{controller}/drools/facts")
    public Response droolsFacts2(@PathParam("controller") String controllerName) {

        return catchArgStateGenericEx(() -> {
            final Map<String, Long> sessionCounts = new HashMap<>();
            var drools = this.getDroolsController(controllerName);
            for (final String session : drools.getSessionNames()) {
                sessionCounts.put(session, drools.factCount(session));
            }
            return sessionCounts;

        }, e -> {
            logger.debug(FETCH_POLICY_BY_NAME_FAILED, this, controllerName, e.getMessage(), e);
            return controllerName;
        });
    }

    /**
     * GET.
     *
     * @return response object
     */
    @Override
    @GET
    @Path("engine/controllers/{controller}/drools/facts/{session}")
    public Response droolsFacts1(@PathParam("controller") String controllerName,
        @PathParam("session") String sessionName) {

        return catchArgStateGenericEx(() -> {
            var drools = this.getDroolsController(controllerName);
            return drools.factClassNames(sessionName);

        }, e -> {
            logger.debug(FETCH_DROOLS_FAILED, this, controllerName, e.getMessage(), e);
            return (controllerName + ":" + sessionName);
        });
    }

    /**
     * GET.
     *
     * @return response object
     */
    @Override
    @GET
    @Path("engine/controllers/{controller}/drools/facts/{session}/{factType}")
    public Response droolsFacts(
        @PathParam("controller") String controllerName,
        @PathParam("session") String sessionName,
        @PathParam("factType") String factType,
        @DefaultValue("false") @QueryParam("count") boolean count) {

        return catchArgStateGenericEx(() -> {
            var drools = this.getDroolsController(controllerName);
            final List<Object> facts = drools.facts(sessionName, factType, false);
            return (count ? facts.size() : facts);

        }, e -> {
            logger.debug(FETCH_POLICY_BY_NAME_FAILED, this, controllerName, e.getMessage(), e);
            return (controllerName + ":" + sessionName + ":" + factType);
        });
    }

    /**
     * GET.
     *
     * @return response object
     */
    @Override
    @GET
    @Path("engine/controllers/{controller}/drools/facts/{session}/{query}/{queriedEntity}")
    public Response droolsFacts3(
        @PathParam("controller") String controllerName,
        @PathParam("session") String sessionName,
        @PathParam("query") String queryName,
        @PathParam("queriedEntity") String queriedEntity,
        @DefaultValue("false") @QueryParam("count") boolean count) {

        return catchArgStateGenericEx(() -> {
            var drools = this.getDroolsController(controllerName);
            final List<Object> facts = drools.factQuery(sessionName, queryName, queriedEntity, false);
            return (count ? facts.size() : facts);

        }, e -> {
            logger.debug(FETCH_DROOLS_BY_ENTITY_FAILED, this,
                controllerName, sessionName, queryName, queriedEntity, e.getMessage(), e);
            return (controllerName + ":" + sessionName + ":" + queryName + queriedEntity);
        });
    }

    /**
     * POST.
     *
     * @return response object
     */
    @Override
    @POST
    @Path("engine/controllers/{controller}/drools/facts/{session}/{query}/{queriedEntity}")
    public Response droolsFacts4(
        @PathParam("controller") String controllerName,
        @PathParam("session") String sessionName,
        @PathParam("query") String queryName,
        @PathParam("queriedEntity") String queriedEntity,
        List<Object> queryParameters) {

        return catchArgStateGenericEx(() -> {
            var drools = this.getDroolsController(controllerName);
            if (queryParameters == null || queryParameters.isEmpty()) {
                return drools.factQuery(sessionName, queryName, queriedEntity, false);
            } else {
                return drools.factQuery(sessionName, queryName, queriedEntity, false, queryParameters.toArray());
            }

        }, e -> {
            logger.debug(FETCH_DROOLS_BY_PARAMS_FAILED,
                this, controllerName, sessionName, queryName, queriedEntity, queryParameters, e.getMessage(), e);
            return (controllerName + ":" + sessionName + ":" + queryName + queriedEntity);
        });
    }

    /**
     * DELETE.
     *
     * @return response object
     */
    @Override
    @DELETE
    @Path("engine/controllers/{controller}/drools/facts/{session}/{factType}")
    public Response droolsFactsDelete1(
        @PathParam("controller") String controllerName,
        @PathParam("session") String sessionName,
        @PathParam("factType") String factType) {

        return catchArgStateGenericEx(() -> {
            var drools = this.getDroolsController(controllerName);
            return drools.facts(sessionName, factType, true);

        }, e -> {
            logger.debug(FETCH_DROOLS_BY_FACTTYPE_FAILED, this,
                controllerName, sessionName, factType, e.getMessage(), e);
            return (controllerName + ":" + sessionName + ":" + factType);
        });
    }

    /**
     * DELETE.
     *
     * @return response object
     */
    @Override
    @DELETE
    @Path("engine/controllers/{controller}/drools/facts/{session}/{query}/{queriedEntity}")
    public Response droolsFactsDelete(
        @PathParam("controller") String controllerName,
        @PathParam("session") String sessionName,
        @PathParam("query") String queryName,
        @PathParam("queriedEntity") String queriedEntity) {

        return catchArgStateGenericEx(() -> {
            var drools = this.getDroolsController(controllerName);
            return drools.factQuery(sessionName, queryName, queriedEntity, true);


        }, e -> {
            logger.debug(FETCH_DROOLS_BY_PARAMS_FAILED,
                this, controllerName, sessionName, queryName, queriedEntity, e.getMessage(), e);
            return (controllerName + ":" + sessionName + ":" + queryName + queriedEntity);
        });
    }

    /**
     * POST.
     *
     * @return response object
     */
    @Override
    @POST
    @Path("engine/controllers/tools/coders/decoders/filters/rule")
    public Response rules(String expression) {
        return Response.status(Status.OK).entity(new JsonProtocolFilter(expression)).build();
    }

    /**
     * GET.
     *
     * @return response object
     */
    @Override
    @GET
    @Path("engine/controllers/{controller}/decoders")
    public Response decoders(@PathParam("controller") String controllerName) {

        return catchArgStateGenericEx(() -> {
            var drools = this.getDroolsController(controllerName);
            return EventProtocolCoderConstants.getManager().getDecoders(drools.getGroupId(), drools.getArtifactId());

        }, e -> {
            logger.debug(FETCH_DECODERS_BY_POLICY_FAILED, this, controllerName,
                e.getMessage(), e);
            return (controllerName);
        });
    }

    /**
     * GET.
     *
     * @return response object
     */
    @Override
    @GET
    @Path("engine/controllers/{controller}/decoders/filters")
    public Response decoderFilters(@PathParam("controller") String controllerName) {

        return catchArgStateGenericEx(() -> {
            var drools = this.getDroolsController(controllerName);
            return EventProtocolCoderConstants.getManager()
                .getDecoderFilters(drools.getGroupId(), drools.getArtifactId());

        }, e -> {
            logger.debug(FETCH_DECODERS_BY_POLICY_FAILED, this, controllerName, e.getMessage(), e);
            return (controllerName);
        });
    }

    /**
     * GET.
     *
     * @return response object
     */
    @Override
    @GET
    @Path("engine/controllers/{controller}/decoders/{topic}")
    public Response decoder(
        @PathParam("controller") String controllerName,
        @PathParam("topic") String topic) {

        return catchArgStateGenericEx(() -> {
            var drools = this.getDroolsController(controllerName);
            return EventProtocolCoderConstants.getManager()
                .getDecoders(drools.getGroupId(), drools.getArtifactId(), topic);

        }, e -> {
            logger.debug(FETCH_DECODERS_BY_TOPIC_FAILED, this, controllerName, topic, e.getMessage(), e);
            return (controllerName + ":" + topic);
        });
    }

    /**
     * GET.
     *
     * @return response object
     */
    @Override
    @GET
    @Path("engine/controllers/{controller}/decoders/{topic}/filters")
    public Response decoderFilter2(
        @PathParam("controller") String controllerName,
        @PathParam("topic") String topic) {

        return catchArgStateGenericEx(() -> {
            var drools = this.getDroolsController(controllerName);
            final ProtocolCoderToolset decoder = EventProtocolCoderConstants.getManager()
                .getDecoders(drools.getGroupId(), drools.getArtifactId(), topic);
            if (decoder == null) {
                return Response.status(Response.Status.BAD_REQUEST).entity(new Error(topic + DOES_NOT_EXIST_MSG))
                    .build();
            } else {
                return decoder.getCoders();
            }

        }, e -> {
            logger.debug(FETCH_DECODERS_BY_TOPIC_FAILED, this, controllerName, topic, e.getMessage(), e);
            return (controllerName + ":" + topic);
        });
    }

    /**
     * GET.
     *
     * @return response object
     */
    @Override
    @GET
    @Path("engine/controllers/{controller}/decoders/{topic}/filters/{factType}")
    public Response decoderFilter1(
        @PathParam("controller") String controllerName,
        @PathParam("topic") String topic,
        @PathParam("factType") String factClass) {

        return catchArgStateGenericEx(() -> {
            var drools = this.getDroolsController(controllerName);
            final ProtocolCoderToolset decoder = EventProtocolCoderConstants.getManager()
                .getDecoders(drools.getGroupId(), drools.getArtifactId(), topic);
            final CoderFilters filters = decoder.getCoder(factClass);
            if (filters == null) {
                return Response.status(Response.Status.BAD_REQUEST)
                    .entity(new Error(topic + ":" + factClass + DOES_NOT_EXIST_MSG)).build();
            } else {
                return filters;
            }

        }, e -> {
            logger.debug(FETCH_DECODER_BY_TYPE_FAILED, this,
                controllerName, topic, factClass, e.getMessage(), e);
            return (controllerName + ":" + topic + ":" + factClass);
        });
    }

    /**
     * PUT.
     *
     * @return response object
     */
    @Override
    @PUT
    @Path("engine/controllers/{controller}/decoders/{topic}/filters/{factType}")
    public Response decoderFilter(
            JsonProtocolFilter configFilters,
            @PathParam("controller") String controllerName,
            @PathParam("topic") String topic,
            @PathParam("factType") String factClass) {

        if (configFilters == null) {
            return Response.status(Response.Status.BAD_REQUEST).entity(new Error("Configuration Filters not provided"))
                .build();
        }

        return catchArgStateGenericEx(() -> {
            var drools = this.getDroolsController(controllerName);
            final ProtocolCoderToolset decoder = EventProtocolCoderConstants.getManager()
                .getDecoders(drools.getGroupId(), drools.getArtifactId(), topic);
            final CoderFilters filters = decoder.getCoder(factClass);
            if (filters == null) {
                return Response.status(Response.Status.BAD_REQUEST)
                    .entity(new Error(topic + ":" + factClass + DOES_NOT_EXIST_MSG)).build();
            }
            filters.setFilter(configFilters);
            return filters;

        }, e -> {
            logger.debug(FETCH_DECODER_BY_FILTER_FAILED,
                this, controllerName, topic, factClass, configFilters, e.getMessage(), e);
            return (controllerName + ":" + topic + ":" + factClass);
        });
    }

    /**
     * GET.
     *
     * @return response object
     */
    @Override
    @GET
    @Path("engine/controllers/{controller}/decoders/{topic}/filters/{factType}/rule")
    public Response decoderFilterRules(
        @PathParam("controller") String controllerName,
        @PathParam("topic") String topic,
        @PathParam("factType") String factClass) {

        return catchArgStateGenericEx(() -> {
            var drools = this.getDroolsController(controllerName);
            final ProtocolCoderToolset decoder = EventProtocolCoderConstants.getManager()
                .getDecoders(drools.getGroupId(), drools.getArtifactId(), topic);

            final CoderFilters filters = decoder.getCoder(factClass);
            if (filters == null) {
                return Response.status(Response.Status.BAD_REQUEST)
                    .entity(new Error(controllerName + ":" + topic + ":" + factClass + DOES_NOT_EXIST_MSG)).build();
            }

            final JsonProtocolFilter filter = filters.getFilter();
            if (filter == null) {
                return Response.status(Response.Status.BAD_REQUEST)
                    .entity(new Error(controllerName + ":" + topic + ":" + factClass + NO_FILTERS)).build();
            }

            return filter.getRule();

        }, e -> {
            logger.debug(FETCH_DECODER_BY_TYPE_FAILED, this,
                controllerName, topic, factClass, e.getMessage(), e);
            return (controllerName + ":" + topic + ":" + factClass);
        });
    }

    /**
     * DELETE.
     *
     * @return response object
     */
    @Override
    @DELETE
    @Path("engine/controllers/{controller}/decoders/{topic}/filters/{factType}/rule")
    public Response decoderFilterRuleDelete(
        @PathParam("controller") String controllerName,
        @PathParam("topic") String topic,
        @PathParam("factType") String factClass) {

        return catchArgStateGenericEx(() -> {
            var drools = this.getDroolsController(controllerName);
            final ProtocolCoderToolset decoder = EventProtocolCoderConstants.getManager()
                .getDecoders(drools.getGroupId(), drools.getArtifactId(), topic);

            final CoderFilters filters = decoder.getCoder(factClass);
            if (filters == null) {
                return Response.status(Response.Status.BAD_REQUEST)
                    .entity(new Error(controllerName + ":" + topic + ":" + factClass + DOES_NOT_EXIST_MSG)).build();
            }

            final JsonProtocolFilter filter = filters.getFilter();
            if (filter == null) {
                return Response.status(Response.Status.BAD_REQUEST)
                    .entity(new Error(controllerName + ":" + topic + ":" + factClass + NO_FILTERS)).build();
            }

            filter.setRule(null);
            return filter.getRule();

        }, e -> {
            logger.debug(FETCH_DECODER_BY_TYPE_FAILED,
                this, controllerName, topic, factClass, e.getMessage(), e);
            return (controllerName + ":" + topic + ":" + factClass);
        });
    }

    /**
     * PUT.
     *
     * @return response object
     */
    @Override
    @PUT
    @Path("engine/controllers/{controller}/decoders/{topic}/filters/{factType}/rule")
    public Response decoderFilterRule(
        @PathParam("controller") String controllerName,
        @PathParam("topic") String topic,
        @PathParam("factType") String factClass,
        String rule) {

        return catchArgStateGenericEx(() -> decoderFilterRule2(controllerName, topic, factClass, rule), e -> {
            logger.debug("{}: cannot access decoder filter rules for policy-controller {} "
                + "topic {} type {} because of {}",
                this, controllerName, topic, factClass, e.getMessage(), e);
            return (controllerName + ":" + topic + ":" + factClass);
        });
    }

    private Object decoderFilterRule2(String controllerName, String topic, String factClass, String rule) {
        var drools = this.getDroolsController(controllerName);
        final ProtocolCoderToolset decoder = EventProtocolCoderConstants.getManager()
            .getDecoders(drools.getGroupId(), drools.getArtifactId(), topic);

        final CoderFilters filters = decoder.getCoder(factClass);
        if (filters == null) {
            return Response.status(Response.Status.BAD_REQUEST)
                .entity(new Error(controllerName + ":" + topic + ":" + factClass + DOES_NOT_EXIST_MSG)).build();
        }

        final JsonProtocolFilter filter = filters.getFilter();
        if (filter == null) {
            return Response.status(Response.Status.BAD_REQUEST)
                .entity(new Error(controllerName + ":" + topic + ":" + factClass + NO_FILTERS)).build();
        }

        if (rule == null || rule.isEmpty()) {
            return Response.status(Response.Status.BAD_REQUEST).entity(new Error(controllerName + ":" + topic + ":"
                + factClass + " no filter rule provided")).build();
        }

        filter.setRule(rule);
        return filter.getRule();
    }

    /**
     * POST.
     *
     * @return response object
     */
    @Override
    @POST
    @Path("engine/controllers/{controller}/decoders/{topic}")
    @Consumes(MediaType.TEXT_PLAIN)
    public Response decode(
        @PathParam("controller") String controllerName,
        @PathParam("topic") String topic,
        String json) {

        if (!checkValidNameInput(controllerName)) {
            return Response.status(Response.Status.NOT_ACCEPTABLE)
                .entity(new Error("controllerName contains whitespaces " + NOT_ACCEPTABLE_MSG)).build();
        }

        if (!checkValidNameInput(topic)) {
            return Response.status(Response.Status.NOT_ACCEPTABLE)
                .entity(new Error("topic contains whitespaces " + NOT_ACCEPTABLE_MSG)).build();
        }

        PolicyController policyController;
        try {
            policyController = PolicyControllerConstants.getFactory().get(controllerName);
        } catch (final IllegalArgumentException e) {
            logger.debug(FETCH_DECODERS_BY_TOPIC_FAILED, this,
                controllerName, topic, e.getMessage(), e);
            return Response.status(Response.Status.NOT_FOUND)
                .entity(new Error(controllerName + ":" + topic + ":" + NOT_FOUND_MSG)).build();
        } catch (final IllegalStateException e) {
            logger.debug(FETCH_DECODERS_BY_TOPIC_FAILED, this,
                controllerName, topic, e.getMessage(), e);
            return Response.status(Response.Status.NOT_ACCEPTABLE)
                .entity(new Error(controllerName + ":" + topic + ":" + NOT_ACCEPTABLE_MSG)).build();
        }

        var result = new CodingResult();
        result.setDecoding(false);
        result.setEncoding(false);
        result.setJsonEncoding(null);

        Object event;
        try {
            event = EventProtocolCoderConstants.getManager().decode(policyController.getDrools().getGroupId(),
                policyController.getDrools().getArtifactId(), topic, json);
            result.setDecoding(true);
        } catch (final Exception e) {
            logger.debug(FETCH_POLICY_BY_TOPIC_FAILED, this, controllerName, topic,
                e.getMessage(), e);
            return Response.status(Response.Status.BAD_REQUEST).entity(new Error(e.getMessage())).build();
        }

        try {
            result.setJsonEncoding(EventProtocolCoderConstants.getManager().encode(topic, event));
            result.setEncoding(true);
        } catch (final Exception e) {
            // continue so to propagate decoding results ..
            logger.debug("{}: cannot encode for policy-controller {} topic {} because of {}", this, controllerName,
                topic, e.getMessage(), e);
        }

        return Response.status(Response.Status.OK).entity(result).build();
    }

    /**
     * GET.
     *
     * @return response object
     */
    @Override
    @GET
    @Path("engine/controllers/{controller}/encoders")
    public Response encoderFilters(@PathParam("controller") String controllerName) {

        return catchArgStateGenericEx(() -> {
            final PolicyController controller = PolicyControllerConstants.getFactory().get(controllerName);
            var drools = controller.getDrools();
            return EventProtocolCoderConstants.getManager()
                .getEncoderFilters(drools.getGroupId(), drools.getArtifactId());

        }, e -> {
            logger.debug(FETCH_ENCODER_BY_FILTER_FAILED, this, controllerName,
                e.getMessage(), e);
            return (controllerName);
        });
    }

    @Override
    @GET
    @Path("engine/topics")
    public Response topics() {
        return Response.status(Response.Status.OK).entity(TopicEndpointManager.getManager()).build();
    }

    @Override
    @GET
    @Path("engine/topics/switches")
    public Response topicSwitches() {
        return Response.status(Response.Status.OK).entity(SWITCHES).build();
    }

    /**
     * PUT.
     *
     * @return response object
     */
    @Override
    @PUT
    @Path("engine/topics/switches/lock")
    public Response topicsLock() {
        final boolean success = TopicEndpointManager.getManager().lock();
        if (success) {
            return Response.status(Status.OK).entity(TopicEndpointManager.getManager()).build();
        } else {
            return Response.status(Status.NOT_ACCEPTABLE).entity(new Error(CANNOT_PERFORM_OPERATION)).build();
        }
    }

    /**
     * DELETE.
     *
     * @return response object
     */
    @Override
    @DELETE
    @Path("engine/topics/switches/lock")
    public Response topicsUnlock() {
        final boolean success = TopicEndpointManager.getManager().unlock();
        if (success) {
            return Response.status(Status.OK).entity(TopicEndpointManager.getManager()).build();
        } else {
            return Response.status(Status.NOT_ACCEPTABLE).entity(new Error(CANNOT_PERFORM_OPERATION)).build();
        }
    }

    /**
     * GET.
     *
     * @return response object
     */
    @Override
    @GET
    @Path("engine/topics/sources")
    public Response sources() {
        return Response.status(Response.Status.OK).entity(TopicEndpointManager.getManager().getTopicSources()).build();
    }

    /**
     * GET.
     *
     * @return response object
     */
    @Override
    @GET
    @Path("engine/topics/sinks")
    public Response sinks() {
        return Response.status(Response.Status.OK).entity(TopicEndpointManager.getManager().getTopicSinks()).build();
    }

    /**
     * GET sources of a communication type.
     */
    @Override
    @GET
    @Path("engine/topics/sources/{comm: ueb|kafka|noop}")
    public Response commSources(
        @PathParam("comm") String comm) {
        if (!checkValidNameInput(comm)) {
            return Response
                .status(Response.Status.NOT_ACCEPTABLE)
                .entity(new Error("source communication mechanism contains whitespaces " + NOT_ACCEPTABLE_MSG))
                .build();
        }

        List<TopicSource> sources = new ArrayList<>();
        var status = Status.OK;
        switch (CommInfrastructure.valueOf(comm.toUpperCase())) {
            case UEB:
                sources.addAll(TopicEndpointManager.getManager().getUebTopicSources());
                break;
            case NOOP:
                sources.addAll(TopicEndpointManager.getManager().getNoopTopicSources());
                break;
            case KAFKA:
                sources.addAll(TopicEndpointManager.getManager().getKafkaTopicSources());
                break;
            default:
                status = Status.BAD_REQUEST;
                logger.debug("Invalid communication mechanism");
                break;
        }
        return Response.status(status).entity(sources).build();
    }

    /**
     * GET sinks of a communication type.
     */
    @Override
    @GET
    @Path("engine/topics/sinks/{comm: ueb|kafka|noop}")
    public Response commSinks(
        @PathParam("comm") String comm) {
        if (!checkValidNameInput(comm)) {
            return Response
                .status(Response.Status.NOT_ACCEPTABLE)
                .entity(new Error("sink communication mechanism contains whitespaces " + NOT_ACCEPTABLE_MSG))
                .build();
        }

        List<TopicSink> sinks = new ArrayList<>();
        var status = Status.OK;
        switch (CommInfrastructure.valueOf(comm.toUpperCase())) {
            case UEB:
                sinks.addAll(TopicEndpointManager.getManager().getUebTopicSinks());
                break;
            case NOOP:
                sinks.addAll(TopicEndpointManager.getManager().getNoopTopicSinks());
                break;
            case KAFKA:
                sinks.addAll(TopicEndpointManager.getManager().getKafkaTopicSinks());
                break;
            default:
                status = Status.BAD_REQUEST;
                logger.debug("Invalid communication mechanism");
                break;
        }
        return Response.status(status).entity(sinks).build();
    }

    /**
     * GET a source.
     */
    @Override
    @GET
    @Path("engine/topics/sources/{comm: ueb|kafka|noop}/{topic}")
    public Response sourceTopic(
        @PathParam("comm") String comm,
        @PathParam("topic") String topic) {
        return Response
            .status(Response.Status.OK)
            .entity(TopicEndpointManager.getManager()
                .getTopicSource(CommInfrastructure.valueOf(comm.toUpperCase()), topic))
            .build();
    }

    /**
     * GET a sink.
     */
    @Override
    @GET
    @Path("engine/topics/sinks/{comm: ueb|kafka|noop}/{topic}")
    public Response sinkTopic(
        @PathParam("comm") String comm,
        @PathParam("topic") String topic) {
        return Response
            .status(Response.Status.OK)
            .entity(TopicEndpointManager.getManager()
                .getTopicSink(CommInfrastructure.valueOf(comm.toUpperCase()), topic))
            .build();
    }

    /**
     * GET a source events.
     */
    @Override
    @GET
    @Path("engine/topics/sources/{comm: ueb|kafka|noop}/{topic}/events")
    public Response sourceEvents(
        @PathParam("comm") String comm,
        @PathParam("topic") String topic) {
        return Response.status(Status.OK)
            .entity(Arrays.asList(TopicEndpointManager.getManager()
                .getTopicSource(CommInfrastructure.valueOf(comm.toUpperCase()), topic)
                .getRecentEvents()))
            .build();
    }

    /**
     * GET a sink events.
     */
    @Override
    @GET
    @Path("engine/topics/sinks/{comm: ueb|kafka|noop}/{topic}/events")
    public Response sinkEvents(
        @PathParam("comm") String comm,
        @PathParam("topic") String topic) {
        return Response.status(Status.OK)
            .entity(Arrays.asList(TopicEndpointManager.getManager()
                .getTopicSink(CommInfrastructure.valueOf(comm.toUpperCase()), topic)
                .getRecentEvents()))
            .build();
    }

    /**
     * GET source topic switches.
     */
    @Override
    @GET
    @Path("engine/topics/sources/{comm: ueb|kafka|noop}/{topic}/switches")
    public Response commSourceTopicSwitches(
        @PathParam("comm") String comm,
        @PathParam("topic") String topic) {
        return Response.status(Response.Status.OK).entity(SWITCHES).build();
    }

    /**
     * GET sink topic switches.
     */
    @Override
    @GET
    @Path("engine/topics/sinks/{comm: ueb|kafka|noop}/{topic}/switches")
    public Response commSinkTopicSwitches(
        @PathParam("comm") String comm,
        @PathParam("topic") String topic) {
        return Response.status(Response.Status.OK).entity(SWITCHES).build();
    }

    /**
     * PUTs a lock on a topic.
     */
    @Override
    @PUT
    @Path("engine/topics/sources/{comm: ueb|kafka|noop}/{topic}/switches/lock")
    public Response commSourceTopicLock(
        @PathParam("comm") String comm,
        @PathParam("topic") String topic) {
        var source =
            TopicEndpointManager.getManager().getTopicSource(CommInfrastructure.valueOf(comm.toUpperCase()), topic);
        return getResponse(topic, source.lock(), source);
    }

    /**
     * DELETEs the lock on a topic.
     */
    @Override
    @DELETE
    @Path("engine/topics/sources/{comm: ueb|kafka|noop}/{topic}/switches/lock")
    public Response commSourceTopicUnlock(
        @PathParam("comm") String comm,
        @PathParam("topic") String topic) {
        var source =
            TopicEndpointManager.getManager().getTopicSource(CommInfrastructure.valueOf(comm.toUpperCase()), topic);
        return getResponse(topic, source.unlock(), source);
    }

    /**
     * Starts a topic source.
     */
    @Override
    @PUT
    @Path("engine/topics/sources/{comm: ueb|kafka|noop}/{topic}/switches/activation")
    public Response commSourceTopicActivation(
        @PathParam("comm") String comm,
        @PathParam("topic") String topic) {
        var source =
            TopicEndpointManager.getManager().getTopicSource(CommInfrastructure.valueOf(comm.toUpperCase()), topic);
        return getResponse(topic, source.start(), source);
    }

    /**
     * Stops a topic source.
     */
    @Override
    @DELETE
    @Path("engine/topics/sources/{comm: ueb|kafka|noop}/{topic}/switches/activation")
    public Response commSourceTopicDeactivation(
        @PathParam("comm") String comm,
        @PathParam("topic") String topic) {
        var source =
            TopicEndpointManager.getManager().getTopicSource(CommInfrastructure.valueOf(comm.toUpperCase()), topic);
        return getResponse(topic, source.stop(), source);
    }

    /**
     * PUTs a lock on a topic.
     */
    @Override
    @PUT
    @Path("engine/topics/sinks/{comm: ueb|kafka|noop}/{topic}/switches/lock")
    public Response commSinkTopicLock(
        @PathParam("comm") String comm,
        @PathParam("topic") String topic) {
        var sink =
            TopicEndpointManager.getManager().getTopicSink(CommInfrastructure.valueOf(comm.toUpperCase()), topic);
        return getResponse(topic, sink.lock(), sink);
    }

    /**
     * DELETEs the lock on a topic.
     */
    @Override
    @DELETE
    @Path("engine/topics/sinks/{comm: ueb|kafka|noop}/{topic}/switches/lock")
    public Response commSinkTopicUnlock(
        @PathParam("comm") String comm,
        @PathParam("topic") String topic) {
        var sink =
            TopicEndpointManager.getManager().getTopicSink(CommInfrastructure.valueOf(comm.toUpperCase()), topic);
        return getResponse(topic, sink.unlock(), sink);
    }

    /**
     * Starts a topic sink.
     */
    @Override
    @PUT
    @Path("engine/topics/sinks/{comm: ueb|kafka|noop}/{topic}/switches/activation")
    public Response commSinkTopicActivation(
        @PathParam("comm") String comm,
        @PathParam("topic") String topic) {
        var sink =
            TopicEndpointManager.getManager().getTopicSink(CommInfrastructure.valueOf(comm.toUpperCase()), topic);
        return getResponse(topic, sink.start(), sink);
    }

    /**
     * Stops a topic sink.
     */
    @Override
    @DELETE
    @Path("engine/topics/sinks/{comm: ueb|kafka|noop}/{topic}/switches/activation")
    public Response commSinkTopicDeactivation(
        @PathParam("comm") String comm,
        @PathParam("topic") String topic) {
        var sink =
            TopicEndpointManager.getManager().getTopicSink(CommInfrastructure.valueOf(comm.toUpperCase()), topic);
        return getResponse(topic, sink.stop(), sink);
    }

    private Response getResponse(String topicName, boolean success, Topic topic) {
        if (success) {
            return Response.status(Status.OK).entity(topic).build();
        } else {
            return Response.status(Status.NOT_ACCEPTABLE).entity(makeTopicOperError(topicName)).build();
        }
    }

    private Error makeTopicOperError(String topic) {
        return new Error("cannot perform operation on " + topic);
    }

    /**
     * Offers an event to a topic in a communication infrastructure.
     *
     * @return response object
     */
    @Override
    @PUT
    @Path("engine/topics/sources/{comm: ueb|kafka|noop}/{topic}/events")
    @Consumes(MediaType.TEXT_PLAIN)
    public Response commEventOffer(
        @PathParam("comm") String comm,
        @PathParam("topic") String topic,
        String json) {

        return catchArgStateGenericEx(() -> {
            var source = TopicEndpointManager.getManager()
                .getTopicSource(CommInfrastructure.valueOf(comm.toUpperCase()), topic);
            if (source.offer(json)) {
                return Arrays.asList(source.getRecentEvents());
            } else {
                return Response.status(Status.NOT_ACCEPTABLE).entity(new Error("Failure to inject event over " + topic))
                    .build();
            }

        }, e -> {
            logger.debug(OFFER_FAILED, this, topic, e.getMessage(), e);
            return (topic);
        });
    }

    /**
     * GET.
     *
     * @return response object
     */
    @Override
    @GET
    @Path("engine/tools/uuid")
    @Produces(MediaType.TEXT_PLAIN)
    public Response uuid() {
        return Response.status(Status.OK).entity(UUID.randomUUID().toString()).build();
    }

    /**
     * GET.
     *
     * @return response object
     */
    @Override
    @GET
    @Path("engine/tools/loggers")
    public Response loggers() {
        final List<String> names = new ArrayList<>();
        if (!(LoggerFactory.getILoggerFactory() instanceof LoggerContext context)) {
            logger.warn("The SLF4J logger factory is not configured for logback");
            return Response.status(Status.INTERNAL_SERVER_ERROR).entity(names).build();
        }

        for (final Logger lgr : context.getLoggerList()) {
            names.add(lgr.getName());
        }

        return Response.status(Status.OK).entity(names).build();
    }

    /**
     * GET.
     *
     * @return response object
     */
    @Override
    @GET
    @Path("engine/tools/loggers/{logger}")
    @Produces(MediaType.TEXT_PLAIN)
    public Response loggerName1(@PathParam("logger") String loggerName) {
        if (!(LoggerFactory.getILoggerFactory() instanceof LoggerContext context)) {
            logger.warn("The SLF4J logger factory is not configured for logback");
            return Response.status(Status.INTERNAL_SERVER_ERROR).build();
        }

        var lgr = context.getLogger(loggerName);
        if (lgr == null) {
            return Response.status(Status.NOT_FOUND).build();
        }

        final String loggerLevel = (lgr.getLevel() != null) ? lgr.getLevel().toString() : "";
        return Response.status(Status.OK).entity(loggerLevel).build();
    }

    /**
     * PUT.
     *
     * @return response object
     */
    @Override
    @PUT
    @Path("engine/tools/loggers/{logger}/{level}")
    @Produces(MediaType.TEXT_PLAIN)
    @Consumes(MediaType.TEXT_PLAIN)
    public Response loggerName(@PathParam("logger") String loggerName, @PathParam("level") String loggerLevel) {

        String newLevel;
        try {
            if (!checkValidNameInput(loggerName)) {
                return Response.status(Response.Status.NOT_ACCEPTABLE)
                    .entity(new Error("logger name: " + NOT_ACCEPTABLE_MSG))
                    .build();
            }
            if (!Pattern.matches("^[a-zA-Z]{3,5}$", loggerLevel)) {
                return Response.status(Response.Status.NOT_ACCEPTABLE)
                    .entity(new Error("logger level: " + NOT_ACCEPTABLE_MSG))
                    .build();
            }
            newLevel = LoggerUtils.setLevel(loggerName, loggerLevel);
        } catch (final IllegalArgumentException e) {
            logger.warn("{}: invalid operation for logger {} and level {}", this, loggerName, loggerLevel, e);
            return Response.status(Status.NOT_FOUND).build();
        } catch (final IllegalStateException e) {
            logger.warn("{}: logging framework unavailable for {} / {}", this, loggerName, loggerLevel, e);
            return Response.status(Status.INTERNAL_SERVER_ERROR).build();
        }

        return Response.status(Status.OK).entity(newLevel

        ).build();
    }

    /**
     * gets the underlying drools controller from the named policy controller.
     *
     * @param controllerName the policy controller name
     * @return the underlying drools controller
     * @throws IllegalArgumentException if an invalid controller name has been passed in
     */
    protected DroolsController getDroolsController(String controllerName) {
        final PolicyController controller = PolicyControllerConstants.getFactory().get(controllerName);
        if (controller == null) {
            throw new IllegalArgumentException(controllerName + DOES_NOT_EXIST_MSG);
        }

        var drools = controller.getDrools();
        if (drools == null) {
            throw new IllegalArgumentException(controllerName + " has no drools configuration");
        }

        return drools;
    }

    /**
     * Invokes a function and returns the generated response, catching illegal argument,
     * illegal state, and generic runtime exceptions.
     *
     * @param responder function that will generate a response. If it returns a "Response"
     *        object, then that object is returned as-is. Otherwise, this method will
     *        return an "OK" Response, using the function's return value as the "entity"
     * @param errorMsg function that will generate an error message prefix to be included
     *        in responses generated as a result of catching an exception
     * @return a response
     */
    private Response catchArgStateGenericEx(Supplier<Object> responder, Function<Exception, String> errorMsg) {
        try {
            Object result = responder.get();
            if (result instanceof Response) {
                return (Response) result;
            }

            return Response.status(Response.Status.OK).entity(result).build();

        } catch (final IllegalArgumentException e) {
            return Response.status(Response.Status.NOT_FOUND).entity(new Error(errorMsg.apply(e) + NOT_FOUND_MSG))
                .build();

        } catch (final IllegalStateException e) {
            return Response.status(Response.Status.NOT_ACCEPTABLE)
                .entity(new Error(errorMsg.apply(e) + NOT_ACCEPTABLE_MSG)).build();

        } catch (final RuntimeException e) {
            errorMsg.apply(e);
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(new Error(e.getMessage())).build();
        }
    }

    public static boolean checkValidNameInput(String test) {
        return Pattern.matches("\\S+", test);
    }

    /*
     * Helper classes for aggregation of results
     */

    /**
     * Coding/Encoding Results Aggregation Helper class.
     */
    @Getter
    @Setter
    public static class CodingResult {
        /**
         * serialized output.
         */

        private String jsonEncoding;
        /**
         * encoding result.
         */

        private Boolean encoding;

        /**
         * decoding result.
         */
        private Boolean decoding;
    }

    /**
     * Generic Error Reporting class.
     */
    @AllArgsConstructor
    public static class Error {
        private String msg;

        public String getError() {
            return msg;
        }

        public void setError(String msg) {
            this.msg = msg;
        }
    }
}