-/*\r
- * ============LICENSE_START=======================================================\r
- * feature-controller-logging\r
- * ================================================================================\r
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.\r
- * ================================================================================\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ============LICENSE_END=========================================================\r
- */\r
-\r
-package org.onap.policy.drools.controller.logging;\r
-\r
-import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;\r
-import org.onap.policy.common.endpoints.event.comm.TopicSink;\r
-import org.onap.policy.drools.controller.DroolsController;\r
-import org.onap.policy.drools.features.DroolsControllerFeatureApi;\r
-import org.onap.policy.drools.features.PolicyControllerFeatureApi;\r
-import org.onap.policy.drools.features.PolicyEngineFeatureApi;\r
-import org.onap.policy.drools.protocol.configuration.ControllerConfiguration;\r
-import org.onap.policy.drools.protocol.configuration.PdpdConfiguration;\r
-import org.onap.policy.drools.system.PolicyController;\r
-import org.onap.policy.drools.system.PolicyControllerConstants;\r
-import org.onap.policy.drools.system.PolicyEngine;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-\r
-/**\r
- * This class hooks the network logging implementation into DroolsPDP. It will disable the\r
- * default network logger where all topic traffic is logged and segregates the topic\r
- * traffic by controller for each supported control loop use case.\r
- */\r
-\r
-/*\r
- * PolicyControllerFeatureAPI - the 'beforeStart' hook is used to shut off the default\r
- * network logger and the 'beforeOffer' hook is used to log incoming topic messages\r
- *\r
- * DroolsControllerFeatureAPI - the 'afterDeliver' hook is where the outgoing topic\r
- * messages are logged\r
- *\r
- */\r
-public class ControllerLoggingFeature\r
- implements PolicyEngineFeatureApi, DroolsControllerFeatureApi, PolicyControllerFeatureApi {\r
-\r
- @Override\r
- public int getSequenceNumber() {\r
- return 1000;\r
- }\r
-\r
- /**\r
- * The 'beforeOffer' hook will intercept an incoming topic message and append it to\r
- * the log file that is configured for the controller logger.\r
- */\r
- @Override\r
- public boolean beforeOffer(PolicyController controller, CommInfrastructure protocol, String topic, String event) {\r
- Logger controllerLogger = LoggerFactory.getLogger(controller.getName());\r
- controllerLogger.info("[IN|{}|{}]{}{}", protocol, topic, System.lineSeparator(), event);\r
- return false;\r
- }\r
-\r
- /**\r
- * The 'afterDeliver' hook will intercept an outgoing topic message and append it to\r
- * the log file that is configured for the controller logger.\r
- */\r
- @Override\r
- public boolean afterDeliver(DroolsController controller, TopicSink sink, Object fact, String json,\r
- boolean success) {\r
- if (success) {\r
- Logger controllerLogger = LoggerFactory\r
- .getLogger(PolicyControllerConstants.getFactory().get(controller).getName());\r
- controllerLogger.info("[OUT|{}|{}]{}{}", sink.getTopicCommInfrastructure(), sink.getTopic(),\r
- System.lineSeparator(), json);\r
- }\r
- return false;\r
- }\r
-\r
- /**\r
- * The 'afterOnTopicEvent' hook will determine which controllers were updated and log\r
- * the event to the appropriate controller logs.\r
- */\r
- @Override\r
- public boolean afterOnTopicEvent(PolicyEngine engine, PdpdConfiguration configuration, CommInfrastructure commType,\r
- String topic, String event) {\r
- for (ControllerConfiguration controller : configuration.getControllers()) {\r
- Logger controllerLogger = LoggerFactory.getLogger(controller.getName());\r
- controllerLogger.info("[IN|{}|{}]{}{}", commType, topic, System.lineSeparator(), event);\r
- }\r
- return false;\r
- }\r
-}\r
+/*
+ * ============LICENSE_START=======================================================
+ * feature-controller-logging
+ * ================================================================================
+ * Copyright (C) 2019 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.drools.controller.logging;
+
+import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
+import org.onap.policy.common.endpoints.event.comm.TopicSink;
+import org.onap.policy.drools.controller.DroolsController;
+import org.onap.policy.drools.features.DroolsControllerFeatureApi;
+import org.onap.policy.drools.features.PolicyControllerFeatureApi;
+import org.onap.policy.drools.features.PolicyEngineFeatureApi;
+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.PolicyEngine;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This class hooks the network logging implementation into DroolsPDP. It will disable the
+ * default network logger where all topic traffic is logged and segregates the topic
+ * traffic by controller for each supported control loop use case.
+ */
+
+/*
+ * PolicyControllerFeatureAPI - the 'beforeStart' hook is used to shut off the default
+ * network logger and the 'beforeOffer' hook is used to log incoming topic messages
+ *
+ * DroolsControllerFeatureAPI - the 'afterDeliver' hook is where the outgoing topic
+ * messages are logged
+ *
+ */
+public class ControllerLoggingFeature
+ implements PolicyEngineFeatureApi, DroolsControllerFeatureApi, PolicyControllerFeatureApi {
+
+ @Override
+ public int getSequenceNumber() {
+ return 1000;
+ }
+
+ /**
+ * The 'beforeOffer' hook will intercept an incoming topic message and append it to
+ * the log file that is configured for the controller logger.
+ */
+ @Override
+ public boolean beforeOffer(PolicyController controller, CommInfrastructure protocol, String topic, String event) {
+ Logger controllerLogger = LoggerFactory.getLogger(controller.getName());
+ controllerLogger.info("[IN|{}|{}]{}{}", protocol, topic, System.lineSeparator(), event);
+ return false;
+ }
+
+ /**
+ * The 'afterDeliver' hook will intercept an outgoing topic message and append it to
+ * the log file that is configured for the controller logger.
+ */
+ @Override
+ public boolean afterDeliver(DroolsController controller, TopicSink sink, Object fact, String json,
+ boolean success) {
+ if (success) {
+ Logger controllerLogger = LoggerFactory
+ .getLogger(PolicyControllerConstants.getFactory().get(controller).getName());
+ controllerLogger.info("[OUT|{}|{}]{}{}", sink.getTopicCommInfrastructure(), sink.getTopic(),
+ System.lineSeparator(), json);
+ }
+ return false;
+ }
+
+ /**
+ * The 'afterOnTopicEvent' hook will determine which controllers were updated and log
+ * the event to the appropriate controller logs.
+ */
+ @Override
+ public boolean afterOnTopicEvent(PolicyEngine engine, PdpdConfiguration configuration, CommInfrastructure commType,
+ String topic, String event) {
+ for (ControllerConfiguration controller : configuration.getControllers()) {
+ Logger controllerLogger = LoggerFactory.getLogger(controller.getName());
+ controllerLogger.info("[IN|{}|{}]{}{}", commType, topic, System.lineSeparator(), event);
+ }
+ return false;
+ }
+}
-/*\r
- * ============LICENSE_START=======================================================\r
- * feature-controller-logging\r
- * ================================================================================\r
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.\r
- * ================================================================================\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ============LICENSE_END=========================================================\r
- */\r
-\r
-package org.onap.policy.drools.controller.logging;\r
-\r
-import static org.junit.Assert.assertEquals;\r
-\r
-import ch.qos.logback.classic.spi.LoggingEvent;\r
-import ch.qos.logback.core.AppenderBase;\r
-import com.google.gson.Gson;\r
-import com.google.gson.GsonBuilder;\r
-import java.io.IOException;\r
-import java.nio.file.Paths;\r
-import java.util.ArrayList;\r
-import java.util.Arrays;\r
-import java.util.List;\r
-import java.util.Properties;\r
-import org.junit.After;\r
-import org.junit.BeforeClass;\r
-import org.junit.Test;\r
-import org.onap.policy.common.endpoints.event.comm.Topic;\r
-import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;\r
-import org.onap.policy.common.endpoints.event.comm.bus.NoopTopicSink;\r
-import org.onap.policy.drools.controller.DroolsController;\r
-import org.onap.policy.drools.controller.DroolsControllerConstants;\r
-import org.onap.policy.drools.properties.DroolsPropertyConstants;\r
-import org.onap.policy.drools.protocol.configuration.ControllerConfiguration;\r
-import org.onap.policy.drools.protocol.configuration.PdpdConfiguration;\r
-import org.onap.policy.drools.system.PolicyController;\r
-import org.onap.policy.drools.system.PolicyEngineConstants;\r
-import org.onap.policy.drools.util.KieUtils;\r
-\r
-/**\r
- * Controller Logger Tests.\r
- */\r
-public class ControllerLoggingTest {\r
-\r
- /**\r
- * These properties are for installing a test artifact that the drools controller can\r
- * fetch while testing.\r
- */\r
- private static final String JUNIT_KMODULE_DRL_PATH = "src/test/resources/test.drl";\r
- private static final String JUNIT_KMODULE_POM_PATH = "src/test/resources/test.pom";\r
- private static final String JUNIT_KMODULE_PATH = "src/test/resources/kmodule.xml";\r
- private static final String JUNIT_KJAR_DRL_PATH = "src/main/resources/org/onap/policy/drools/test/test.drl";\r
-\r
- /**\r
- * These properties are used for the Policy Controller to point to the test artifact.\r
- */\r
- private static final String TEST_CONTROLLER_NAME = "test-controller";\r
- private static final String TEST_GROUP_ID = "org.onap.policy.drools.test";\r
- private static final String TEST_ARTIFACT_ID = "test";\r
- private static final String TEST_VERSION = "1.0.0";\r
-\r
- /**\r
- * A test topic used for delivery and network logging.\r
- */\r
- private static final String TEST_TOPIC = "test-topic";\r
- private static final String TEST_SERVER = "http://test.com";\r
-\r
- /**\r
- * These are used for sending PDPD configuration notifications to a policy controller.\r
- */\r
- private static Properties controllerProps = null;\r
- private static String message = null;\r
- private static PdpdConfiguration pdpdNotification = null;\r
- private static PolicyController policyController = null;\r
-\r
- /**\r
- * This is a list of events that are appended to the controller-test logger.\r
- */\r
- private static List<LoggingEvent> events = new ArrayList<>();\r
-\r
- /**\r
- * A custom appender used to intercept events and add them to a list of events that\r
- * the junits can use to determine logging was successful.\r
- */\r
- public static class NetworkAppender extends AppenderBase<LoggingEvent> {\r
-\r
- @Override\r
- protected void append(LoggingEvent event) {\r
- events.add(event);\r
- }\r
-\r
- }\r
-\r
- /**\r
- * Runs before all the test cases to install the drools artifact, create a policy\r
- * controller, and create a PDPD configuration notification.\r
- */\r
- @BeforeClass\r
- public static void setUp() throws IOException {\r
- KieUtils.installArtifact(Paths.get(JUNIT_KMODULE_PATH).toFile(), Paths.get(JUNIT_KMODULE_POM_PATH).toFile(),\r
- JUNIT_KJAR_DRL_PATH, Paths.get(JUNIT_KMODULE_DRL_PATH).toFile());\r
-\r
- controllerProps = new Properties();\r
- controllerProps.put(DroolsPropertyConstants.PROPERTY_CONTROLLER_NAME, TEST_CONTROLLER_NAME);\r
- controllerProps.put(DroolsPropertyConstants.RULES_GROUPID, TEST_GROUP_ID);\r
- controllerProps.put(DroolsPropertyConstants.RULES_ARTIFACTID, TEST_ARTIFACT_ID);\r
- controllerProps.put(DroolsPropertyConstants.RULES_VERSION, TEST_VERSION);\r
-\r
- policyController = PolicyEngineConstants.getManager().createPolicyController(TEST_CONTROLLER_NAME,\r
- controllerProps);\r
-\r
- message = "{\"requestID\":\"38adde30-cc22-11e8-a8d5-f2801f1b9fd1\",\"entity\":\"controller\",\"controllers\":"\r
- + "[{\"name\":\"test-controller\",\"drools\":{\"groupId\":\"org.onap.policy.drools.test\","\r
- + "\"artifactId\":\"test\",\"version\":\"0.0.1\"},\"operation\":\"update\"}]}";\r
-\r
- Gson decoder = new GsonBuilder().disableHtmlEscaping().create();\r
- pdpdNotification = decoder.fromJson(message, PdpdConfiguration.class);\r
- }\r
-\r
- /**\r
- * Runs after every test case to clean up the events added to the event list during\r
- * unit test.\r
- */\r
- @After\r
- public void cleanUpLogs() {\r
- events.clear();\r
- }\r
-\r
- /**\r
- * Obtains the sequence number of the controller logging feature. This should return\r
- * 1000.\r
- */\r
- @Test\r
- public void getSequenceNumberTest() {\r
- ControllerLoggingFeature nlf = new ControllerLoggingFeature();\r
- assertEquals(1000, nlf.getSequenceNumber());\r
- }\r
-\r
- /**\r
- * Asserts that the controller-test logger appends the incoming message to the event\r
- * list.\r
- */\r
- @Test\r
- public void beforeOffer() {\r
- ControllerLoggingFeature nlf = new ControllerLoggingFeature();\r
-\r
- nlf.beforeOffer(policyController, Topic.CommInfrastructure.UEB, TEST_TOPIC, "{\"test\":\"test\"}");\r
-\r
- assertEquals(1, events.size());\r
- }\r
-\r
- /**\r
- * Asserts that the controller-test logger appends the outgoing message to the event\r
- * list.\r
- */\r
- @Test\r
- public void afterDeliverSuccess() {\r
-\r
- final ControllerLoggingFeature nlf = new ControllerLoggingFeature();\r
-\r
- DroolsController droolsController =\r
- DroolsControllerConstants.getFactory().get(TEST_GROUP_ID, TEST_ARTIFACT_ID, TEST_VERSION);\r
-\r
- NoopTopicSink sinkTopic = new NoopTopicSink(Arrays.asList(TEST_SERVER), TEST_TOPIC);\r
-\r
- nlf.afterDeliver(droolsController, sinkTopic, null, "{\"test\":\"test\"}", true);\r
-\r
- assertEquals(1, events.size());\r
-\r
- }\r
-\r
- /**\r
- * Asserts that the controller-test logger does not append the outgoing message to the\r
- * event list if there was a failure.\r
- */\r
- @Test\r
- public void afterDeliverFailure() {\r
-\r
- final ControllerLoggingFeature nlf = new ControllerLoggingFeature();\r
-\r
- DroolsController droolsController =\r
- DroolsControllerConstants.getFactory().get(TEST_GROUP_ID, TEST_ARTIFACT_ID, TEST_VERSION);\r
-\r
- NoopTopicSink sinkTopic = new NoopTopicSink(Arrays.asList(TEST_SERVER), TEST_TOPIC);\r
-\r
- nlf.afterDeliver(droolsController, sinkTopic, null, "{\"test\":\"test\"}", false);\r
-\r
- assertEquals(0, events.size());\r
- }\r
-\r
- /**\r
- * Asserts that the controller logging feature can log the messages to the proper\r
- * controller based on the message containing the controller name.\r
- */\r
- @Test\r
- public void afterOnTopicEventSuccess() {\r
- final ControllerLoggingFeature nlf = new ControllerLoggingFeature();\r
-\r
- nlf.afterOnTopicEvent(PolicyEngineConstants.getManager(), pdpdNotification, CommInfrastructure.UEB, TEST_TOPIC,\r
- message);\r
-\r
- assertEquals(1, events.size());\r
- }\r
-\r
- /**\r
- * Asserts that the controller logging feature can skip logging messages that don't\r
- * contain the controller names in it.\r
- */\r
- @Test\r
- public void afterOnTopicEventFailure() {\r
- final ControllerLoggingFeature nlf = new ControllerLoggingFeature();\r
-\r
- PdpdConfiguration notification = new PdpdConfiguration();\r
- ControllerConfiguration config = new ControllerConfiguration();\r
- config.setName("test-controller-2");\r
- notification.setControllers(Arrays.asList(config));\r
-\r
- nlf.afterOnTopicEvent(PolicyEngineConstants.getManager(), notification, CommInfrastructure.UEB, TEST_TOPIC,\r
- message);\r
-\r
- assertEquals(0, events.size());\r
- }\r
-}\r
+/*
+ * ============LICENSE_START=======================================================
+ * feature-controller-logging
+ * ================================================================================
+ * Copyright (C) 2019 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.drools.controller.logging;
+
+import static org.junit.Assert.assertEquals;
+
+import ch.qos.logback.classic.spi.LoggingEvent;
+import ch.qos.logback.core.AppenderBase;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import java.io.IOException;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Properties;
+import org.junit.After;
+import org.junit.BeforeClass;
+import org.junit.Test;
+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.bus.NoopTopicSink;
+import org.onap.policy.drools.controller.DroolsController;
+import org.onap.policy.drools.controller.DroolsControllerConstants;
+import org.onap.policy.drools.properties.DroolsPropertyConstants;
+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.PolicyEngineConstants;
+import org.onap.policy.drools.util.KieUtils;
+
+/**
+ * Controller Logger Tests.
+ */
+public class ControllerLoggingTest {
+
+ /**
+ * These properties are for installing a test artifact that the drools controller can
+ * fetch while testing.
+ */
+ private static final String JUNIT_KMODULE_DRL_PATH = "src/test/resources/test.drl";
+ private static final String JUNIT_KMODULE_POM_PATH = "src/test/resources/test.pom";
+ private static final String JUNIT_KMODULE_PATH = "src/test/resources/kmodule.xml";
+ private static final String JUNIT_KJAR_DRL_PATH = "src/main/resources/org/onap/policy/drools/test/test.drl";
+
+ /**
+ * These properties are used for the Policy Controller to point to the test artifact.
+ */
+ private static final String TEST_CONTROLLER_NAME = "test-controller";
+ private static final String TEST_GROUP_ID = "org.onap.policy.drools.test";
+ private static final String TEST_ARTIFACT_ID = "test";
+ private static final String TEST_VERSION = "1.0.0";
+
+ /**
+ * A test topic used for delivery and network logging.
+ */
+ private static final String TEST_TOPIC = "test-topic";
+ private static final String TEST_SERVER = "http://test.com";
+
+ /**
+ * These are used for sending PDPD configuration notifications to a policy controller.
+ */
+ private static Properties controllerProps = null;
+ private static String message = null;
+ private static PdpdConfiguration pdpdNotification = null;
+ private static PolicyController policyController = null;
+
+ /**
+ * This is a list of events that are appended to the controller-test logger.
+ */
+ private static List<LoggingEvent> events = new ArrayList<>();
+
+ /**
+ * A custom appender used to intercept events and add them to a list of events that
+ * the junits can use to determine logging was successful.
+ */
+ public static class NetworkAppender extends AppenderBase<LoggingEvent> {
+
+ @Override
+ protected void append(LoggingEvent event) {
+ events.add(event);
+ }
+
+ }
+
+ /**
+ * Runs before all the test cases to install the drools artifact, create a policy
+ * controller, and create a PDPD configuration notification.
+ */
+ @BeforeClass
+ public static void setUp() throws IOException {
+ KieUtils.installArtifact(Paths.get(JUNIT_KMODULE_PATH).toFile(), Paths.get(JUNIT_KMODULE_POM_PATH).toFile(),
+ JUNIT_KJAR_DRL_PATH, Paths.get(JUNIT_KMODULE_DRL_PATH).toFile());
+
+ controllerProps = new Properties();
+ controllerProps.put(DroolsPropertyConstants.PROPERTY_CONTROLLER_NAME, TEST_CONTROLLER_NAME);
+ controllerProps.put(DroolsPropertyConstants.RULES_GROUPID, TEST_GROUP_ID);
+ controllerProps.put(DroolsPropertyConstants.RULES_ARTIFACTID, TEST_ARTIFACT_ID);
+ controllerProps.put(DroolsPropertyConstants.RULES_VERSION, TEST_VERSION);
+
+ policyController = PolicyEngineConstants.getManager().createPolicyController(TEST_CONTROLLER_NAME,
+ controllerProps);
+
+ message = "{\"requestID\":\"38adde30-cc22-11e8-a8d5-f2801f1b9fd1\",\"entity\":\"controller\",\"controllers\":"
+ + "[{\"name\":\"test-controller\",\"drools\":{\"groupId\":\"org.onap.policy.drools.test\","
+ + "\"artifactId\":\"test\",\"version\":\"0.0.1\"},\"operation\":\"update\"}]}";
+
+ Gson decoder = new GsonBuilder().disableHtmlEscaping().create();
+ pdpdNotification = decoder.fromJson(message, PdpdConfiguration.class);
+ }
+
+ /**
+ * Runs after every test case to clean up the events added to the event list during
+ * unit test.
+ */
+ @After
+ public void cleanUpLogs() {
+ events.clear();
+ }
+
+ /**
+ * Obtains the sequence number of the controller logging feature. This should return
+ * 1000.
+ */
+ @Test
+ public void getSequenceNumberTest() {
+ ControllerLoggingFeature nlf = new ControllerLoggingFeature();
+ assertEquals(1000, nlf.getSequenceNumber());
+ }
+
+ /**
+ * Asserts that the controller-test logger appends the incoming message to the event
+ * list.
+ */
+ @Test
+ public void beforeOffer() {
+ ControllerLoggingFeature nlf = new ControllerLoggingFeature();
+
+ nlf.beforeOffer(policyController, Topic.CommInfrastructure.UEB, TEST_TOPIC, "{\"test\":\"test\"}");
+
+ assertEquals(1, events.size());
+ }
+
+ /**
+ * Asserts that the controller-test logger appends the outgoing message to the event
+ * list.
+ */
+ @Test
+ public void afterDeliverSuccess() {
+
+ final ControllerLoggingFeature nlf = new ControllerLoggingFeature();
+
+ DroolsController droolsController =
+ DroolsControllerConstants.getFactory().get(TEST_GROUP_ID, TEST_ARTIFACT_ID, TEST_VERSION);
+
+ NoopTopicSink sinkTopic = new NoopTopicSink(Arrays.asList(TEST_SERVER), TEST_TOPIC);
+
+ nlf.afterDeliver(droolsController, sinkTopic, null, "{\"test\":\"test\"}", true);
+
+ assertEquals(1, events.size());
+
+ }
+
+ /**
+ * Asserts that the controller-test logger does not append the outgoing message to the
+ * event list if there was a failure.
+ */
+ @Test
+ public void afterDeliverFailure() {
+
+ final ControllerLoggingFeature nlf = new ControllerLoggingFeature();
+
+ DroolsController droolsController =
+ DroolsControllerConstants.getFactory().get(TEST_GROUP_ID, TEST_ARTIFACT_ID, TEST_VERSION);
+
+ NoopTopicSink sinkTopic = new NoopTopicSink(Arrays.asList(TEST_SERVER), TEST_TOPIC);
+
+ nlf.afterDeliver(droolsController, sinkTopic, null, "{\"test\":\"test\"}", false);
+
+ assertEquals(0, events.size());
+ }
+
+ /**
+ * Asserts that the controller logging feature can log the messages to the proper
+ * controller based on the message containing the controller name.
+ */
+ @Test
+ public void afterOnTopicEventSuccess() {
+ final ControllerLoggingFeature nlf = new ControllerLoggingFeature();
+
+ nlf.afterOnTopicEvent(PolicyEngineConstants.getManager(), pdpdNotification, CommInfrastructure.UEB, TEST_TOPIC,
+ message);
+
+ assertEquals(1, events.size());
+ }
+
+ /**
+ * Asserts that the controller logging feature can skip logging messages that don't
+ * contain the controller names in it.
+ */
+ @Test
+ public void afterOnTopicEventFailure() {
+ final ControllerLoggingFeature nlf = new ControllerLoggingFeature();
+
+ PdpdConfiguration notification = new PdpdConfiguration();
+ ControllerConfiguration config = new ControllerConfiguration();
+ config.setName("test-controller-2");
+ notification.setControllers(Arrays.asList(config));
+
+ nlf.afterOnTopicEvent(PolicyEngineConstants.getManager(), notification, CommInfrastructure.UEB, TEST_TOPIC,
+ message);
+
+ assertEquals(0, events.size());
+ }
+}
-/*\r
- * ============LICENSE_START=======================================================\r
- * feature-mdc-filters\r
- * ================================================================================\r
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.\r
- * ================================================================================\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ============LICENSE_END=========================================================\r
- */\r
-\r
-package org.onap.policy.drools.mdc.filters;\r
-\r
-import java.util.HashMap;\r
-import java.util.List;\r
-import java.util.Map;\r
-import java.util.Properties;\r
-import org.onap.policy.common.endpoints.event.comm.Topic;\r
-import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;\r
-import org.onap.policy.common.endpoints.features.NetLoggerFeatureApi;\r
-import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType;\r
-import org.onap.policy.drools.features.PolicyControllerFeatureApi;\r
-import org.onap.policy.drools.persistence.SystemPersistenceConstants;\r
-import org.onap.policy.drools.system.PolicyController;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.slf4j.MDC;\r
-\r
-public class MdcFilterFeature implements NetLoggerFeatureApi, PolicyControllerFeatureApi {\r
-\r
- /**\r
- * Logger.\r
- */\r
- private static final Logger logger = LoggerFactory.getLogger(MdcFilterFeature.class);\r
-\r
- /**\r
- * Feature properties.\r
- */\r
- public static final String FEATURE_NAME = "feature-mdc-filters";\r
- public static final String SOURCE = "source";\r
- public static final String SINK = "sink";\r
- public static final String MDC_FILTERS = ".mdcFilters";\r
-\r
- /**\r
- * Mapping of 'protocol:type:topic' key to a 'MdcTopicFilter' object.\r
- */\r
- private Map<String, MdcTopicFilter> topicFilters = new HashMap<>();\r
-\r
- /**\r
- * Feature properties map obtained from the feature properties file.\r
- */\r
- private Properties featureProps = null;\r
-\r
- /**\r
- * Constructor.\r
- */\r
- public MdcFilterFeature() {\r
- super();\r
- featureProps = getFeatureProps();\r
- }\r
-\r
- /**\r
- * Gets the feature properties.\r
- *\r
- * @return the properties for this feature.\r
- */\r
- protected Properties getFeatureProps() {\r
- return SystemPersistenceConstants.getManager().getProperties(FEATURE_NAME);\r
- }\r
-\r
- /**\r
- * Sequence number to be used for order of feature implementer execution.\r
- */\r
- @Override\r
- public int getSequenceNumber() {\r
- return 1;\r
- }\r
-\r
- /**\r
- * Loops through all source and sink topics to find which topics have mdc filters and\r
- * inserts an MdcTopicFilter in to the topicFilters map.\r
- */\r
- @Override\r
- public boolean afterCreate(PolicyController controller) {\r
- createSourceTopicFilters(controller);\r
- createSinkTopicFilters(controller);\r
- return false;\r
- }\r
-\r
- /**\r
- * Extracts the fields in a JSON string that are to be logged in an abbreviated\r
- * message. The event delivery infrastructure details are put in the MDC as well using\r
- * the keys networkEventType (IN/OUT), networkProtocol (UEB/DMAAP/NOOP/REST), and\r
- * networkTopic.\r
- */\r
- @Override\r
- public boolean beforeLog(Logger eventLogger, EventType type, CommInfrastructure protocol, String topic,\r
- String message) {\r
-\r
- String filterKey = null;\r
- if (type == EventType.IN) {\r
- filterKey = getTopicKey(protocol.name().toLowerCase(), SOURCE, topic);\r
- } else {\r
- filterKey = getTopicKey(protocol.name().toLowerCase(), SINK, topic);\r
- }\r
-\r
- MDC.put("networkEventType", type.name());\r
- MDC.put("networkProtocol", protocol.name());\r
- MDC.put("networkTopic", topic);\r
-\r
- MdcTopicFilter filter = topicFilters.get(filterKey);\r
- if (filter != null) {\r
- for (Map.Entry<String, List<String>> entry : filter.find(message).entrySet()) {\r
- String mdcKey = entry.getKey();\r
- List<String> results = entry.getValue();\r
- if (results.isEmpty()) {\r
- logger.debug("No results found for key {}", mdcKey);\r
- } else if (results.size() > 1) {\r
- logger.debug("Multple results found for key {}, returning list as a string", mdcKey);\r
- MDC.put(mdcKey, results.toString());\r
- } else {\r
- MDC.put(mdcKey, results.get(0));\r
- }\r
- }\r
- } else {\r
- logger.debug("No mdc topic filters exist for key {}", filterKey);\r
- }\r
-\r
- return false;\r
- }\r
-\r
- /**\r
- * Clears the MDC mapping after a message is logged.\r
- */\r
- @Override\r
- public boolean afterLog(Logger eventLogger, EventType type, CommInfrastructure protocol, String topic,\r
- String message) {\r
- MDC.clear();\r
- return false;\r
- }\r
-\r
- /**\r
- * Creates a key using the protocol, type, and topic name.\r
- *\r
- * @param protocol defined as ueb, dmaap, noop\r
- * @param type defined as source or sink\r
- * @param topic name of the topic\r
- * @return a key that is the concatenation of the protocol, type, and topic name\r
- */\r
- private String getTopicKey(String protocol, String type, String topic) {\r
- return protocol + ":" + type + ":" + topic;\r
- }\r
-\r
- /**\r
- * Creates MdcTopicFilters for a source/sink topic based on the type.\r
- *\r
- * @param topic the topic name\r
- * @param type 'source' or 'sink'\r
- */\r
- private void createTopicFilter(Topic topic, String type) {\r
- String protocol = topic.getTopicCommInfrastructure().name().toLowerCase();\r
- String topicName = topic.getTopic();\r
-\r
- String propertyKey = protocol + "." + type + ".topics." + topicName + MDC_FILTERS;\r
- String propertyValue = featureProps.getProperty(propertyKey);\r
- if (propertyValue != null) {\r
- String topicKey = getTopicKey(protocol, type, topicName);\r
- if (!topicFilters.containsKey(topicKey)) {\r
- logger.debug("MdcTopicFilter created for {} {} topic {}", protocol, type, topicName);\r
- topicFilters.put(topicKey, new MdcTopicFilter(propertyValue));\r
- } else {\r
- logger.debug("An MdcTopicFilter already exists for key {}", topicKey);\r
- }\r
- } else {\r
- logger.debug("No MDC filters defined for {} {} topic {}", protocol, type, topicName);\r
- }\r
- }\r
-\r
- /**\r
- * Creates MdcTopicFilters for the controller's source topics.\r
- */\r
- private void createSourceTopicFilters(PolicyController controller) {\r
- controller.getTopicSources().forEach(sourceTopic -> createTopicFilter(sourceTopic, SOURCE));\r
- }\r
-\r
- /**\r
- * Creates MdcTopicFilters for the controller's sink topics.\r
- */\r
- private void createSinkTopicFilters(PolicyController controller) {\r
- controller.getTopicSinks().forEach(sinkTopic -> createTopicFilter(sinkTopic, SINK));\r
- }\r
-}\r
+/*
+ * ============LICENSE_START=======================================================
+ * feature-mdc-filters
+ * ================================================================================
+ * Copyright (C) 2019 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.drools.mdc.filters;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+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.features.NetLoggerFeatureApi;
+import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType;
+import org.onap.policy.drools.features.PolicyControllerFeatureApi;
+import org.onap.policy.drools.persistence.SystemPersistenceConstants;
+import org.onap.policy.drools.system.PolicyController;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.slf4j.MDC;
+
+public class MdcFilterFeature implements NetLoggerFeatureApi, PolicyControllerFeatureApi {
+
+ /**
+ * Logger.
+ */
+ private static final Logger logger = LoggerFactory.getLogger(MdcFilterFeature.class);
+
+ /**
+ * Feature properties.
+ */
+ public static final String FEATURE_NAME = "feature-mdc-filters";
+ public static final String SOURCE = "source";
+ public static final String SINK = "sink";
+ public static final String MDC_FILTERS = ".mdcFilters";
+
+ /**
+ * Mapping of 'protocol:type:topic' key to a 'MdcTopicFilter' object.
+ */
+ private Map<String, MdcTopicFilter> topicFilters = new HashMap<>();
+
+ /**
+ * Feature properties map obtained from the feature properties file.
+ */
+ private Properties featureProps = null;
+
+ /**
+ * Constructor.
+ */
+ public MdcFilterFeature() {
+ super();
+ featureProps = getFeatureProps();
+ }
+
+ /**
+ * Gets the feature properties.
+ *
+ * @return the properties for this feature.
+ */
+ protected Properties getFeatureProps() {
+ return SystemPersistenceConstants.getManager().getProperties(FEATURE_NAME);
+ }
+
+ /**
+ * Sequence number to be used for order of feature implementer execution.
+ */
+ @Override
+ public int getSequenceNumber() {
+ return 1;
+ }
+
+ /**
+ * Loops through all source and sink topics to find which topics have mdc filters and
+ * inserts an MdcTopicFilter in to the topicFilters map.
+ */
+ @Override
+ public boolean afterCreate(PolicyController controller) {
+ createSourceTopicFilters(controller);
+ createSinkTopicFilters(controller);
+ return false;
+ }
+
+ /**
+ * Extracts the fields in a JSON string that are to be logged in an abbreviated
+ * message. The event delivery infrastructure details are put in the MDC as well using
+ * the keys networkEventType (IN/OUT), networkProtocol (UEB/DMAAP/NOOP/REST), and
+ * networkTopic.
+ */
+ @Override
+ public boolean beforeLog(Logger eventLogger, EventType type, CommInfrastructure protocol, String topic,
+ String message) {
+
+ String filterKey = null;
+ if (type == EventType.IN) {
+ filterKey = getTopicKey(protocol.name().toLowerCase(), SOURCE, topic);
+ } else {
+ filterKey = getTopicKey(protocol.name().toLowerCase(), SINK, topic);
+ }
+
+ MDC.put("networkEventType", type.name());
+ MDC.put("networkProtocol", protocol.name());
+ MDC.put("networkTopic", topic);
+
+ MdcTopicFilter filter = topicFilters.get(filterKey);
+ if (filter != null) {
+ for (Map.Entry<String, List<String>> entry : filter.find(message).entrySet()) {
+ String mdcKey = entry.getKey();
+ List<String> results = entry.getValue();
+ if (results.isEmpty()) {
+ logger.debug("No results found for key {}", mdcKey);
+ } else if (results.size() > 1) {
+ logger.debug("Multple results found for key {}, returning list as a string", mdcKey);
+ MDC.put(mdcKey, results.toString());
+ } else {
+ MDC.put(mdcKey, results.get(0));
+ }
+ }
+ } else {
+ logger.debug("No mdc topic filters exist for key {}", filterKey);
+ }
+
+ return false;
+ }
+
+ /**
+ * Clears the MDC mapping after a message is logged.
+ */
+ @Override
+ public boolean afterLog(Logger eventLogger, EventType type, CommInfrastructure protocol, String topic,
+ String message) {
+ MDC.clear();
+ return false;
+ }
+
+ /**
+ * Creates a key using the protocol, type, and topic name.
+ *
+ * @param protocol defined as ueb, dmaap, noop
+ * @param type defined as source or sink
+ * @param topic name of the topic
+ * @return a key that is the concatenation of the protocol, type, and topic name
+ */
+ private String getTopicKey(String protocol, String type, String topic) {
+ return protocol + ":" + type + ":" + topic;
+ }
+
+ /**
+ * Creates MdcTopicFilters for a source/sink topic based on the type.
+ *
+ * @param topic the topic name
+ * @param type 'source' or 'sink'
+ */
+ private void createTopicFilter(Topic topic, String type) {
+ String protocol = topic.getTopicCommInfrastructure().name().toLowerCase();
+ String topicName = topic.getTopic();
+
+ String propertyKey = protocol + "." + type + ".topics." + topicName + MDC_FILTERS;
+ String propertyValue = featureProps.getProperty(propertyKey);
+ if (propertyValue != null) {
+ String topicKey = getTopicKey(protocol, type, topicName);
+ if (!topicFilters.containsKey(topicKey)) {
+ logger.debug("MdcTopicFilter created for {} {} topic {}", protocol, type, topicName);
+ topicFilters.put(topicKey, new MdcTopicFilter(propertyValue));
+ } else {
+ logger.debug("An MdcTopicFilter already exists for key {}", topicKey);
+ }
+ } else {
+ logger.debug("No MDC filters defined for {} {} topic {}", protocol, type, topicName);
+ }
+ }
+
+ /**
+ * Creates MdcTopicFilters for the controller's source topics.
+ */
+ private void createSourceTopicFilters(PolicyController controller) {
+ controller.getTopicSources().forEach(sourceTopic -> createTopicFilter(sourceTopic, SOURCE));
+ }
+
+ /**
+ * Creates MdcTopicFilters for the controller's sink topics.
+ */
+ private void createSinkTopicFilters(PolicyController controller) {
+ controller.getTopicSinks().forEach(sinkTopic -> createTopicFilter(sinkTopic, SINK));
+ }
+}
-/*\r
- * ============LICENSE_START=======================================================\r
- * feature-mdc-filters\r
- * ================================================================================\r
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.\r
- * ================================================================================\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ============LICENSE_END=========================================================\r
- */\r
-\r
-package org.onap.policy.drools.mdc.filters;\r
-\r
-import com.att.aft.dme2.internal.apache.commons.lang3.StringUtils;\r
-import java.util.ArrayList;\r
-import java.util.Arrays;\r
-import java.util.HashMap;\r
-import java.util.List;\r
-import java.util.Map;\r
-import lombok.Getter;\r
-import org.onap.policy.drools.protocol.coders.JsonProtocolFilter;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-\r
-public class MdcTopicFilter {\r
-\r
- private static final Logger logger = LoggerFactory.getLogger(MdcTopicFilter.class);\r
-\r
- public static final String MDC_KEY_ERROR = "mdcKey must be provided";\r
- public static final String JSON_PATH_ERROR = "json path(s) must be provided";\r
-\r
- private Map<String, FilterRule> rules = new HashMap<>();\r
-\r
- @Getter\r
- public static class FilterRule {\r
- private String mdcKey;\r
- private List<String> paths;\r
-\r
- public FilterRule(String mdcKey, String path) {\r
- this.mdcKey = mdcKey;\r
- this.paths = Arrays.asList(path);\r
- }\r
-\r
- /**\r
- * Constructor.\r
- *\r
- * @param mdcKey the key to the filter rule\r
- * @param paths the list of potential paths to the key\r
- */\r
- public FilterRule(String mdcKey, List<String> paths) {\r
- this.mdcKey = mdcKey;\r
- this.paths = paths;\r
- }\r
-\r
- protected void setMdcKey(String mdcKey) {\r
- if (StringUtils.isBlank(mdcKey)) {\r
- throw new IllegalArgumentException(MDC_KEY_ERROR);\r
- }\r
- this.mdcKey = mdcKey;\r
- }\r
-\r
- protected void setPaths(List<String> paths) {\r
- if (nullOrEmpty(paths)) {\r
- throw new IllegalArgumentException(JSON_PATH_ERROR);\r
- }\r
- this.paths = paths;\r
- }\r
-\r
- protected void addPaths(List<String> paths) {\r
- if (nullOrEmpty(paths)) {\r
- throw new IllegalArgumentException(JSON_PATH_ERROR);\r
- }\r
- this.paths.addAll(paths);\r
- }\r
-\r
- protected void addPath(String path) {\r
- if (StringUtils.isBlank(path)) {\r
- throw new IllegalArgumentException(JSON_PATH_ERROR);\r
- }\r
- this.paths.add(path);\r
- }\r
- }\r
-\r
- protected MdcTopicFilter(String rawFilters) {\r
- for (String filter : rawFilters.split("\\s*,\\s*")) {\r
- FilterRule rule = createFilterRule(filter);\r
- rules.put(rule.mdcKey, rule);\r
- }\r
- }\r
-\r
- private FilterRule createFilterRule(String filter) {\r
- String[] filterKeyPaths = filter.split("\\s*=\\s*");\r
- if (filterKeyPaths.length != 2) {\r
- throw new IllegalArgumentException("could not parse filter rule");\r
- }\r
-\r
- String filterKey = filterKeyPaths[0];\r
- String paths = filterKeyPaths[1];\r
- List<String> filterPaths = new ArrayList<>(Arrays.asList(paths.split("(?<!\\|)\\|(?!\\|)")));\r
- return new FilterRule(filterKey, filterPaths);\r
- }\r
-\r
- /**\r
- * Gets all the filter rules for the topic.\r
- *\r
- * @return an array list of the rules for the topic\r
- */\r
- protected List<FilterRule> getFilterRule() {\r
- return new ArrayList<>(rules.values());\r
- }\r
-\r
- /**\r
- * Gets the filter rule for the specified key.\r
- *\r
- * @param mdcKey the key to the filter rule\r
- * @return the filter rule associated with the key\r
- */\r
- protected FilterRule getFilterRule(String mdcKey) {\r
- if (StringUtils.isBlank(mdcKey)) {\r
- throw new IllegalArgumentException(MDC_KEY_ERROR);\r
- }\r
- return rules.get(mdcKey);\r
- }\r
-\r
- /**\r
- * Adds a filter rule for the specified key and path.\r
- *\r
- * @param mdcKey the key to the filter rule\r
- * @param path the json path to the key\r
- * @return the filter rule that was added for the topic\r
- */\r
- protected FilterRule addFilterRule(String mdcKey, String path) {\r
- if (StringUtils.isBlank(path)) {\r
- throw new IllegalArgumentException(JSON_PATH_ERROR);\r
- }\r
- return addFilterRule(mdcKey, Arrays.asList(path));\r
- }\r
-\r
- /**\r
- * Adds a filter rule for the specified key and paths.\r
- *\r
- * @param mdcKey the key to the filter rule\r
- * @param paths the list of potential paths to the key\r
- * @return the filter rule that was added for the topic\r
- */\r
- protected FilterRule addFilterRule(String mdcKey, List<String> paths) {\r
- if (StringUtils.isBlank(mdcKey)) {\r
- throw new IllegalArgumentException(MDC_KEY_ERROR);\r
- }\r
-\r
- if (nullOrEmpty(paths)) {\r
- throw new IllegalArgumentException(JSON_PATH_ERROR);\r
- }\r
-\r
- if (rules.containsKey(mdcKey)) {\r
- throw new IllegalArgumentException("a filter rule already exists for key: " + mdcKey);\r
- }\r
-\r
- FilterRule rule = new FilterRule(mdcKey, paths);\r
- rules.put(mdcKey, rule);\r
- return rule;\r
- }\r
-\r
- private static boolean nullOrEmpty(List<String> paths) {\r
- return paths == null || paths.isEmpty();\r
- }\r
-\r
- /**\r
- * Modifies an existing filter rule by adding the specified path.\r
- *\r
- * @param mdcKey the key to the filter rule\r
- * @param path the path to the key\r
- * @return the filter rule that was modified\r
- */\r
- protected FilterRule modifyFilterRule(String mdcKey, String path) {\r
- if (StringUtils.isBlank(path)) {\r
- throw new IllegalArgumentException(JSON_PATH_ERROR);\r
- }\r
- return modifyFilterRule(mdcKey, Arrays.asList(path));\r
- }\r
-\r
- /**\r
- * Modifies an existing filter rule by adding the specified paths.\r
- *\r
- * @param mdcKey the key to the filter rule\r
- * @param paths the list of potential paths to the key\r
- * @return the filter rule that was modified\r
- */\r
- protected FilterRule modifyFilterRule(String mdcKey, List<String> paths) {\r
- if (StringUtils.isBlank(mdcKey)) {\r
- throw new IllegalArgumentException(MDC_KEY_ERROR);\r
- }\r
-\r
- if (nullOrEmpty(paths)) {\r
- throw new IllegalArgumentException(JSON_PATH_ERROR);\r
- }\r
-\r
- if (!rules.containsKey(mdcKey)) {\r
- throw new IllegalArgumentException("a filter rule doesn't exist for key: " + mdcKey);\r
- }\r
-\r
- FilterRule rule = rules.get(mdcKey);\r
- rule.addPaths(paths);\r
- return rule;\r
- }\r
-\r
- /**\r
- * Modifies an existing filter rule's key and replaces the paths with the specified\r
- * paths.\r
- *\r
- * @param oldMdcKey the old key to the filter rule\r
- * @param newMdcKey the new key to the filter rule\r
- * @param paths the list of potential paths to the key\r
- * @return the filter rule that was modified\r
- */\r
- protected FilterRule modifyFilterRule(String oldMdcKey, String newMdcKey, List<String> paths) {\r
- if (StringUtils.isBlank(oldMdcKey)) {\r
- throw new IllegalArgumentException("current mdcKey must be provided");\r
- }\r
-\r
- if (StringUtils.isBlank(newMdcKey)) {\r
- throw new IllegalArgumentException("new mdcKey must be provided");\r
- }\r
-\r
- if (oldMdcKey.equals(newMdcKey)) {\r
- throw new IllegalArgumentException("the old and new mdcKey are equivalent");\r
- }\r
- if (nullOrEmpty(paths)) {\r
- throw new IllegalArgumentException(JSON_PATH_ERROR);\r
- }\r
-\r
- if (rules.containsKey(newMdcKey)) {\r
- throw new IllegalArgumentException("a filter rule already exists for key: " + newMdcKey);\r
- }\r
-\r
- FilterRule rule = rules.remove(oldMdcKey);\r
- if (rule == null) {\r
- throw new IllegalArgumentException("a filter rule doesn't exist for key: " + oldMdcKey);\r
- }\r
-\r
- rule.setMdcKey(newMdcKey);\r
- rule.setPaths(paths);\r
- rules.put(newMdcKey, rule);\r
- return rule;\r
- }\r
-\r
- /**\r
- * Deletes all filter rules for the topic filter.\r
- */\r
- protected void deleteFilterRule() {\r
- rules.clear();\r
- }\r
-\r
- /**\r
- * Deletes an existing filter rule.\r
- *\r
- * @param mdcKey the key to the filter rule\r
- * @return the filter rule that was deleted\r
- */\r
- protected FilterRule deleteFilterRule(String mdcKey) {\r
- if (StringUtils.isBlank(mdcKey)) {\r
- throw new IllegalArgumentException(MDC_KEY_ERROR);\r
- }\r
- return rules.remove(mdcKey);\r
- }\r
-\r
- /**\r
- * Finds all fields for each topic filter rule. The results are stored in a map that\r
- * is indexed by the MDC key. Each MDC key has a list of results as multiple\r
- * occurrences of a key can be found in a JSON document.\r
- *\r
- * @param json the json string to be parsed\r
- * @return a map of mdc keys and list of results for each key\r
- */\r
- protected Map<String, List<String>> find(String json) {\r
- Map<String, List<String>> results = new HashMap<>();\r
- for (FilterRule rule : rules.values()) {\r
- List<String> matches = new ArrayList<>();\r
- for (String path : rule.getPaths()) {\r
-\r
- try {\r
- matches = JsonProtocolFilter.filter(json, path);\r
- } catch (Exception e) {\r
- logger.debug("Could not filter on path {} because of {}", path, e.getMessage(), e);\r
- }\r
-\r
- if (!matches.isEmpty()) {\r
- break;\r
- } else {\r
- logger.error("Could not find path {} in json {}", path, json);\r
- }\r
-\r
- }\r
- results.put(rule.getMdcKey(), matches);\r
- }\r
- return results;\r
- }\r
-\r
- /**\r
- * Finds all occurrences of a field in a JSON document based on the filter rule paths.\r
- *\r
- * @param json the json string to be parsed\r
- * @return a list of matches from the JSON document\r
- */\r
- protected List<String> find(String json, String mdcKey) {\r
- List<String> matches = new ArrayList<>();\r
- for (String path : rules.get(mdcKey).getPaths()) {\r
-\r
- try {\r
- matches = JsonProtocolFilter.filter(json, path);\r
- } catch (Exception e) {\r
- logger.debug("Could not filter on path {} because of {}", path, e.getMessage(), e);\r
- }\r
-\r
- if (!matches.isEmpty()) {\r
- break;\r
- }\r
-\r
- }\r
-\r
- if (matches.isEmpty()) {\r
- logger.error("Could not find any matches for key {} in json {}", mdcKey, json);\r
- }\r
-\r
- return matches;\r
- }\r
-}\r
+/*
+ * ============LICENSE_START=======================================================
+ * feature-mdc-filters
+ * ================================================================================
+ * Copyright (C) 2019 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.drools.mdc.filters;
+
+import com.att.aft.dme2.internal.apache.commons.lang3.StringUtils;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import lombok.Getter;
+import org.onap.policy.drools.protocol.coders.JsonProtocolFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class MdcTopicFilter {
+
+ private static final Logger logger = LoggerFactory.getLogger(MdcTopicFilter.class);
+
+ public static final String MDC_KEY_ERROR = "mdcKey must be provided";
+ public static final String JSON_PATH_ERROR = "json path(s) must be provided";
+
+ private Map<String, FilterRule> rules = new HashMap<>();
+
+ @Getter
+ public static class FilterRule {
+ private String mdcKey;
+ private List<String> paths;
+
+ public FilterRule(String mdcKey, String path) {
+ this.mdcKey = mdcKey;
+ this.paths = Arrays.asList(path);
+ }
+
+ /**
+ * Constructor.
+ *
+ * @param mdcKey the key to the filter rule
+ * @param paths the list of potential paths to the key
+ */
+ public FilterRule(String mdcKey, List<String> paths) {
+ this.mdcKey = mdcKey;
+ this.paths = paths;
+ }
+
+ protected void setMdcKey(String mdcKey) {
+ if (StringUtils.isBlank(mdcKey)) {
+ throw new IllegalArgumentException(MDC_KEY_ERROR);
+ }
+ this.mdcKey = mdcKey;
+ }
+
+ protected void setPaths(List<String> paths) {
+ if (nullOrEmpty(paths)) {
+ throw new IllegalArgumentException(JSON_PATH_ERROR);
+ }
+ this.paths = paths;
+ }
+
+ protected void addPaths(List<String> paths) {
+ if (nullOrEmpty(paths)) {
+ throw new IllegalArgumentException(JSON_PATH_ERROR);
+ }
+ this.paths.addAll(paths);
+ }
+
+ protected void addPath(String path) {
+ if (StringUtils.isBlank(path)) {
+ throw new IllegalArgumentException(JSON_PATH_ERROR);
+ }
+ this.paths.add(path);
+ }
+ }
+
+ protected MdcTopicFilter(String rawFilters) {
+ for (String filter : rawFilters.split("\\s*,\\s*")) {
+ FilterRule rule = createFilterRule(filter);
+ rules.put(rule.mdcKey, rule);
+ }
+ }
+
+ private FilterRule createFilterRule(String filter) {
+ String[] filterKeyPaths = filter.split("\\s*=\\s*");
+ if (filterKeyPaths.length != 2) {
+ throw new IllegalArgumentException("could not parse filter rule");
+ }
+
+ String filterKey = filterKeyPaths[0];
+ String paths = filterKeyPaths[1];
+ List<String> filterPaths = new ArrayList<>(Arrays.asList(paths.split("(?<!\\|)\\|(?!\\|)")));
+ return new FilterRule(filterKey, filterPaths);
+ }
+
+ /**
+ * Gets all the filter rules for the topic.
+ *
+ * @return an array list of the rules for the topic
+ */
+ protected List<FilterRule> getFilterRule() {
+ return new ArrayList<>(rules.values());
+ }
+
+ /**
+ * Gets the filter rule for the specified key.
+ *
+ * @param mdcKey the key to the filter rule
+ * @return the filter rule associated with the key
+ */
+ protected FilterRule getFilterRule(String mdcKey) {
+ if (StringUtils.isBlank(mdcKey)) {
+ throw new IllegalArgumentException(MDC_KEY_ERROR);
+ }
+ return rules.get(mdcKey);
+ }
+
+ /**
+ * Adds a filter rule for the specified key and path.
+ *
+ * @param mdcKey the key to the filter rule
+ * @param path the json path to the key
+ * @return the filter rule that was added for the topic
+ */
+ protected FilterRule addFilterRule(String mdcKey, String path) {
+ if (StringUtils.isBlank(path)) {
+ throw new IllegalArgumentException(JSON_PATH_ERROR);
+ }
+ return addFilterRule(mdcKey, Arrays.asList(path));
+ }
+
+ /**
+ * Adds a filter rule for the specified key and paths.
+ *
+ * @param mdcKey the key to the filter rule
+ * @param paths the list of potential paths to the key
+ * @return the filter rule that was added for the topic
+ */
+ protected FilterRule addFilterRule(String mdcKey, List<String> paths) {
+ if (StringUtils.isBlank(mdcKey)) {
+ throw new IllegalArgumentException(MDC_KEY_ERROR);
+ }
+
+ if (nullOrEmpty(paths)) {
+ throw new IllegalArgumentException(JSON_PATH_ERROR);
+ }
+
+ if (rules.containsKey(mdcKey)) {
+ throw new IllegalArgumentException("a filter rule already exists for key: " + mdcKey);
+ }
+
+ FilterRule rule = new FilterRule(mdcKey, paths);
+ rules.put(mdcKey, rule);
+ return rule;
+ }
+
+ private static boolean nullOrEmpty(List<String> paths) {
+ return paths == null || paths.isEmpty();
+ }
+
+ /**
+ * Modifies an existing filter rule by adding the specified path.
+ *
+ * @param mdcKey the key to the filter rule
+ * @param path the path to the key
+ * @return the filter rule that was modified
+ */
+ protected FilterRule modifyFilterRule(String mdcKey, String path) {
+ if (StringUtils.isBlank(path)) {
+ throw new IllegalArgumentException(JSON_PATH_ERROR);
+ }
+ return modifyFilterRule(mdcKey, Arrays.asList(path));
+ }
+
+ /**
+ * Modifies an existing filter rule by adding the specified paths.
+ *
+ * @param mdcKey the key to the filter rule
+ * @param paths the list of potential paths to the key
+ * @return the filter rule that was modified
+ */
+ protected FilterRule modifyFilterRule(String mdcKey, List<String> paths) {
+ if (StringUtils.isBlank(mdcKey)) {
+ throw new IllegalArgumentException(MDC_KEY_ERROR);
+ }
+
+ if (nullOrEmpty(paths)) {
+ throw new IllegalArgumentException(JSON_PATH_ERROR);
+ }
+
+ if (!rules.containsKey(mdcKey)) {
+ throw new IllegalArgumentException("a filter rule doesn't exist for key: " + mdcKey);
+ }
+
+ FilterRule rule = rules.get(mdcKey);
+ rule.addPaths(paths);
+ return rule;
+ }
+
+ /**
+ * Modifies an existing filter rule's key and replaces the paths with the specified
+ * paths.
+ *
+ * @param oldMdcKey the old key to the filter rule
+ * @param newMdcKey the new key to the filter rule
+ * @param paths the list of potential paths to the key
+ * @return the filter rule that was modified
+ */
+ protected FilterRule modifyFilterRule(String oldMdcKey, String newMdcKey, List<String> paths) {
+ if (StringUtils.isBlank(oldMdcKey)) {
+ throw new IllegalArgumentException("current mdcKey must be provided");
+ }
+
+ if (StringUtils.isBlank(newMdcKey)) {
+ throw new IllegalArgumentException("new mdcKey must be provided");
+ }
+
+ if (oldMdcKey.equals(newMdcKey)) {
+ throw new IllegalArgumentException("the old and new mdcKey are equivalent");
+ }
+ if (nullOrEmpty(paths)) {
+ throw new IllegalArgumentException(JSON_PATH_ERROR);
+ }
+
+ if (rules.containsKey(newMdcKey)) {
+ throw new IllegalArgumentException("a filter rule already exists for key: " + newMdcKey);
+ }
+
+ FilterRule rule = rules.remove(oldMdcKey);
+ if (rule == null) {
+ throw new IllegalArgumentException("a filter rule doesn't exist for key: " + oldMdcKey);
+ }
+
+ rule.setMdcKey(newMdcKey);
+ rule.setPaths(paths);
+ rules.put(newMdcKey, rule);
+ return rule;
+ }
+
+ /**
+ * Deletes all filter rules for the topic filter.
+ */
+ protected void deleteFilterRule() {
+ rules.clear();
+ }
+
+ /**
+ * Deletes an existing filter rule.
+ *
+ * @param mdcKey the key to the filter rule
+ * @return the filter rule that was deleted
+ */
+ protected FilterRule deleteFilterRule(String mdcKey) {
+ if (StringUtils.isBlank(mdcKey)) {
+ throw new IllegalArgumentException(MDC_KEY_ERROR);
+ }
+ return rules.remove(mdcKey);
+ }
+
+ /**
+ * Finds all fields for each topic filter rule. The results are stored in a map that
+ * is indexed by the MDC key. Each MDC key has a list of results as multiple
+ * occurrences of a key can be found in a JSON document.
+ *
+ * @param json the json string to be parsed
+ * @return a map of mdc keys and list of results for each key
+ */
+ protected Map<String, List<String>> find(String json) {
+ Map<String, List<String>> results = new HashMap<>();
+ for (FilterRule rule : rules.values()) {
+ List<String> matches = new ArrayList<>();
+ for (String path : rule.getPaths()) {
+
+ try {
+ matches = JsonProtocolFilter.filter(json, path);
+ } catch (Exception e) {
+ logger.debug("Could not filter on path {} because of {}", path, e.getMessage(), e);
+ }
+
+ if (!matches.isEmpty()) {
+ break;
+ } else {
+ logger.error("Could not find path {} in json {}", path, json);
+ }
+
+ }
+ results.put(rule.getMdcKey(), matches);
+ }
+ return results;
+ }
+
+ /**
+ * Finds all occurrences of a field in a JSON document based on the filter rule paths.
+ *
+ * @param json the json string to be parsed
+ * @return a list of matches from the JSON document
+ */
+ protected List<String> find(String json, String mdcKey) {
+ List<String> matches = new ArrayList<>();
+ for (String path : rules.get(mdcKey).getPaths()) {
+
+ try {
+ matches = JsonProtocolFilter.filter(json, path);
+ } catch (Exception e) {
+ logger.debug("Could not filter on path {} because of {}", path, e.getMessage(), e);
+ }
+
+ if (!matches.isEmpty()) {
+ break;
+ }
+
+ }
+
+ if (matches.isEmpty()) {
+ logger.error("Could not find any matches for key {} in json {}", mdcKey, json);
+ }
+
+ return matches;
+ }
+}
-/*\r
- * ============LICENSE_START=======================================================\r
- * feature-mdc-filters\r
- * ================================================================================\r
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.\r
- * ================================================================================\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ============LICENSE_END=========================================================\r
- */\r
-\r
-package org.onap.policy.drools.mdc.filters;\r
-\r
-import static org.junit.Assert.assertEquals;\r
-import static org.junit.Assert.assertNotNull;\r
-import static org.junit.Assert.assertNull;\r
-import static org.mockito.Mockito.doReturn;\r
-import static org.mockito.Mockito.mock;\r
-\r
-import java.io.IOException;\r
-import java.nio.file.Files;\r
-import java.nio.file.Paths;\r
-import java.util.List;\r
-import java.util.Properties;\r
-import org.junit.Before;\r
-import org.junit.Test;\r
-import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;\r
-import org.onap.policy.common.endpoints.event.comm.TopicEndpointManager;\r
-import org.onap.policy.common.endpoints.event.comm.TopicSink;\r
-import org.onap.policy.common.endpoints.event.comm.TopicSource;\r
-import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType;\r
-import org.onap.policy.drools.system.PolicyController;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-import org.slf4j.MDC;\r
-\r
-public class MdcFilterFeatureTest {\r
-\r
- /**\r
- * Logger.\r
- */\r
- private static final Logger logger = LoggerFactory.getLogger(MdcFilterFeatureTest.class);\r
-\r
- /**\r
- * Test topic names for mdc topic filters.\r
- */\r
- private static final String TEST_TOPIC_A = "org.onap.policy.test-topic-a";\r
- private static final String TEST_TOPIC_B = "org.onap.policy.test-topic-b";\r
-\r
- /**\r
- * The mock PolicyController to be used for the junits.\r
- */\r
- private PolicyController controller;\r
-\r
- /**\r
- * The mock properties to be used for the junits.\r
- */\r
- private Properties props;\r
-\r
- /**\r
- * An instance of the MdcFilterFeature.\r
- */\r
- private MdcFilterFeature mdcFilterFeature;\r
-\r
- /**\r
- * Sample json string to be logged.\r
- */\r
- private String message;\r
-\r
- /**\r
- * Setup.\r
- * @throws IOException thrown if onset.json file could not be read\r
- */\r
- @Before\r
- public void setUp() throws IOException {\r
- message = new String(Files.readAllBytes(Paths.get("src/test/resources/onset.json")));\r
-\r
- props = mockFeatureProperties();\r
- controller = mock(PolicyController.class);\r
-\r
- props.setProperty("dmaap.source.topics", TEST_TOPIC_A);\r
- props.setProperty("dmaap.source.topics." + TEST_TOPIC_A + ".servers", "http://testing123.com/");\r
- props.setProperty("noop.sink.topics", TEST_TOPIC_B);\r
-\r
- List<TopicSource> topicSources = TopicEndpointManager.getManager().addTopicSources(props);\r
- doReturn(topicSources).when(controller).getTopicSources();\r
-\r
- List<TopicSink> topicSinks = TopicEndpointManager.getManager().addTopicSinks(props);\r
- doReturn(topicSinks).when(controller).getTopicSinks();\r
-\r
- mdcFilterFeature = new MdcFilterFeatureImpl();\r
- mdcFilterFeature.afterCreate(controller);\r
- }\r
-\r
- /**\r
- * Tests extracting fields from a JSON message and place them in the MDC and\r
- * then clearing the MDC.\r
- */\r
- @Test\r
- public void mdcLogTest() {\r
- mdcFilterFeature.beforeLog(logger, EventType.IN,\r
- CommInfrastructure.DMAAP, TEST_TOPIC_A, message);\r
-\r
- assertEquals("8c1b8bd8-06f7-493f-8ed7-daaa4cc481bc", MDC.get("requestID"));\r
- assertEquals("CL-TEST", MDC.get("closedLoopControlName"));\r
-\r
- assertNotNull(MDC.getCopyOfContextMap());\r
-\r
- mdcFilterFeature.afterLog(logger, EventType.IN,\r
- CommInfrastructure.DMAAP, TEST_TOPIC_A, message);\r
-\r
- assertNull(MDC.getCopyOfContextMap());\r
- }\r
-\r
- /**\r
- * Tests that the feature does not search for fields in a JSON message\r
- * if there is not an MdcTopicFilter object for the generated key.\r
- */\r
- @Test\r
- public void noTopicFilterTest() {\r
- mdcFilterFeature.beforeLog(logger, EventType.OUT,\r
- CommInfrastructure.NOOP, "no-topic", message);\r
-\r
- assertEquals("OUT", MDC.get("networkEventType"));\r
- assertEquals("NOOP", MDC.get("networkProtocol"));\r
- assertEquals("no-topic", MDC.get("networkTopic"));\r
- assertNull(MDC.get("requestID"));\r
- }\r
-\r
- /**\r
- * Creates a simple properties map containing an mdc filter for a test\r
- * topic.\r
- *\r
- * @return a properties map with mdc filter properties.\r
- */\r
- private Properties mockFeatureProperties() {\r
- Properties props = new Properties();\r
-\r
- String key = "dmaap.source.topics." + TEST_TOPIC_A + ".mdcFilters";\r
- String value = "requestID=$.requestID,closedLoopControlName=$.closedLoopControlName";\r
- props.setProperty(key, value);\r
-\r
- return props;\r
- }\r
-\r
- /**\r
- * Subclass of MdcFilterFeature for junit usage.\r
- */\r
- private class MdcFilterFeatureImpl extends MdcFilterFeature {\r
-\r
- public MdcFilterFeatureImpl() {\r
- super();\r
- }\r
-\r
- @Override\r
- protected Properties getFeatureProps() {\r
- return props;\r
- }\r
- }\r
-}\r
+/*
+ * ============LICENSE_START=======================================================
+ * feature-mdc-filters
+ * ================================================================================
+ * Copyright (C) 2019 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.drools.mdc.filters;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.List;
+import java.util.Properties;
+import org.junit.Before;
+import org.junit.Test;
+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.utils.NetLoggerUtil.EventType;
+import org.onap.policy.drools.system.PolicyController;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.slf4j.MDC;
+
+public class MdcFilterFeatureTest {
+
+ /**
+ * Logger.
+ */
+ private static final Logger logger = LoggerFactory.getLogger(MdcFilterFeatureTest.class);
+
+ /**
+ * Test topic names for mdc topic filters.
+ */
+ private static final String TEST_TOPIC_A = "org.onap.policy.test-topic-a";
+ private static final String TEST_TOPIC_B = "org.onap.policy.test-topic-b";
+
+ /**
+ * The mock PolicyController to be used for the junits.
+ */
+ private PolicyController controller;
+
+ /**
+ * The mock properties to be used for the junits.
+ */
+ private Properties props;
+
+ /**
+ * An instance of the MdcFilterFeature.
+ */
+ private MdcFilterFeature mdcFilterFeature;
+
+ /**
+ * Sample json string to be logged.
+ */
+ private String message;
+
+ /**
+ * Setup.
+ * @throws IOException thrown if onset.json file could not be read
+ */
+ @Before
+ public void setUp() throws IOException {
+ message = new String(Files.readAllBytes(Paths.get("src/test/resources/onset.json")));
+
+ props = mockFeatureProperties();
+ controller = mock(PolicyController.class);
+
+ props.setProperty("dmaap.source.topics", TEST_TOPIC_A);
+ props.setProperty("dmaap.source.topics." + TEST_TOPIC_A + ".servers", "http://testing123.com/");
+ props.setProperty("noop.sink.topics", TEST_TOPIC_B);
+
+ List<TopicSource> topicSources = TopicEndpointManager.getManager().addTopicSources(props);
+ doReturn(topicSources).when(controller).getTopicSources();
+
+ List<TopicSink> topicSinks = TopicEndpointManager.getManager().addTopicSinks(props);
+ doReturn(topicSinks).when(controller).getTopicSinks();
+
+ mdcFilterFeature = new MdcFilterFeatureImpl();
+ mdcFilterFeature.afterCreate(controller);
+ }
+
+ /**
+ * Tests extracting fields from a JSON message and place them in the MDC and
+ * then clearing the MDC.
+ */
+ @Test
+ public void mdcLogTest() {
+ mdcFilterFeature.beforeLog(logger, EventType.IN,
+ CommInfrastructure.DMAAP, TEST_TOPIC_A, message);
+
+ assertEquals("8c1b8bd8-06f7-493f-8ed7-daaa4cc481bc", MDC.get("requestID"));
+ assertEquals("CL-TEST", MDC.get("closedLoopControlName"));
+
+ assertNotNull(MDC.getCopyOfContextMap());
+
+ mdcFilterFeature.afterLog(logger, EventType.IN,
+ CommInfrastructure.DMAAP, TEST_TOPIC_A, message);
+
+ assertNull(MDC.getCopyOfContextMap());
+ }
+
+ /**
+ * Tests that the feature does not search for fields in a JSON message
+ * if there is not an MdcTopicFilter object for the generated key.
+ */
+ @Test
+ public void noTopicFilterTest() {
+ mdcFilterFeature.beforeLog(logger, EventType.OUT,
+ CommInfrastructure.NOOP, "no-topic", message);
+
+ assertEquals("OUT", MDC.get("networkEventType"));
+ assertEquals("NOOP", MDC.get("networkProtocol"));
+ assertEquals("no-topic", MDC.get("networkTopic"));
+ assertNull(MDC.get("requestID"));
+ }
+
+ /**
+ * Creates a simple properties map containing an mdc filter for a test
+ * topic.
+ *
+ * @return a properties map with mdc filter properties.
+ */
+ private Properties mockFeatureProperties() {
+ Properties props = new Properties();
+
+ String key = "dmaap.source.topics." + TEST_TOPIC_A + ".mdcFilters";
+ String value = "requestID=$.requestID,closedLoopControlName=$.closedLoopControlName";
+ props.setProperty(key, value);
+
+ return props;
+ }
+
+ /**
+ * Subclass of MdcFilterFeature for junit usage.
+ */
+ private class MdcFilterFeatureImpl extends MdcFilterFeature {
+
+ public MdcFilterFeatureImpl() {
+ super();
+ }
+
+ @Override
+ protected Properties getFeatureProps() {
+ return props;
+ }
+ }
+}
-/*\r
- * ============LICENSE_START=======================================================\r
- * feature-mdc-filters\r
- * ================================================================================\r
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.\r
- * ================================================================================\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ============LICENSE_END=========================================================\r
- */\r
-\r
-package org.onap.policy.drools.mdc.filters;\r
-\r
-import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;\r
-import static org.junit.Assert.assertEquals;\r
-import static org.junit.Assert.assertNotNull;\r
-import static org.junit.Assert.assertTrue;\r
-\r
-import java.util.ArrayList;\r
-import java.util.Arrays;\r
-import java.util.Collections;\r
-import java.util.List;\r
-import java.util.Map;\r
-import org.junit.Test;\r
-import org.onap.policy.drools.mdc.filters.MdcTopicFilter.FilterRule;\r
-\r
-public class MdcTopicFilterTest {\r
-\r
- /**\r
- * Test the simple case of having one filter rule for a key.\r
- */\r
- @Test\r
- public void singleFilterOnePathTest() {\r
- String topicFilterProp = "requestID=$.requestID";\r
- MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);\r
-\r
- FilterRule rule = topicFilter.getFilterRule("requestID");\r
- assertEquals("requestID", rule.getMdcKey());\r
- assertEquals("[$.requestID]", rule.getPaths().toString());\r
- }\r
-\r
- /**\r
- * Tests having one filter rule with a set of potential paths to the key.\r
- */\r
- @Test\r
- public void singleFilterMultiPathTest() {\r
- String topicFilterProp = "requestID=$.requestID|$.request-id";\r
- MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);\r
-\r
- FilterRule rule = topicFilter.getFilterRule("requestID");\r
- assertEquals("requestID", rule.getMdcKey());\r
- assertEquals(2, rule.getPaths().size());\r
- assertEquals("[$.requestID, $.request-id]", rule.getPaths().toString());\r
- }\r
-\r
- /**\r
- * Tests having two filter rules that each have one key/path pair.\r
- */\r
- @Test\r
- public void multiFilterSinglePathTest() {\r
- String topicFilterProp = "requestID=$.requestID,closedLoopControlName=$.closedLoopControlName";\r
- MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);\r
-\r
- FilterRule rule = topicFilter.getFilterRule("requestID");\r
- assertEquals("requestID", rule.getMdcKey());\r
- assertEquals(1, rule.getPaths().size());\r
- assertEquals("[$.requestID]", rule.getPaths().toString());\r
-\r
- FilterRule rule2 = topicFilter.getFilterRule("closedLoopControlName");\r
- assertEquals("closedLoopControlName", rule2.getMdcKey());\r
- assertEquals(1, rule2.getPaths().size());\r
- assertEquals("[$.closedLoopControlName]", rule2.getPaths().toString());\r
- }\r
-\r
- /**\r
- * Tests having two filter rules that each have two key/path pairs.\r
- */\r
- @Test\r
- public void multiFilterMultiPathTest() {\r
- String topicFilterProp = "requestID=$.requestID|$.body.request-id,"\r
- + "closedLoopControlName=$.closedLoopControlName"\r
- + "|$.body.closedLoopControlName";\r
- MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);\r
-\r
- FilterRule rule = topicFilter.getFilterRule("requestID");\r
- assertEquals("requestID", rule.getMdcKey());\r
- assertEquals(2, rule.getPaths().size());\r
- assertEquals("[$.requestID, $.body.request-id]", rule.getPaths().toString());\r
-\r
- FilterRule rule2 = topicFilter.getFilterRule("closedLoopControlName");\r
- assertEquals("closedLoopControlName", rule2.getMdcKey());\r
- assertEquals(2, rule2.getPaths().size());\r
- assertEquals("[$.closedLoopControlName, $.body.closedLoopControlName]", rule2.getPaths().toString());\r
- }\r
-\r
- /**\r
- * Tests that the regex split logic for '|' in the feature code doesn't\r
- * break parsing when "||" is used as a predicate in a JsonPath query.\r
- */\r
- @Test\r
- public void addOrPredicateFilterTest() {\r
- String topicFilterProp = "requestID=$.requestID||$.body.requestID";\r
- MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);\r
- assertEquals(1, topicFilter.getFilterRule().size());\r
- assertEquals("requestID", topicFilter.getFilterRule("requestID").getMdcKey());\r
- assertEquals(Arrays.asList("$.requestID||$.body.requestID"), topicFilter\r
- .getFilterRule("requestID").getPaths());\r
- }\r
-\r
- /**\r
- * Tests getting all filter rules for a given topic.\r
- */\r
- @Test\r
- public void getAllFilterRulesTest() {\r
- String topicFilterProp = "requestID=$.requestID,subRequestID=$.subRequestID,"\r
- + "closedLoopControlName=$.closedLoopControlName";\r
- MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);\r
- assertEquals(3, topicFilter.getFilterRule().size());\r
- }\r
-\r
- /**\r
- * Tests getting a filter rule by its key.\r
- */\r
- @Test\r
- public void getFilterRuleTest() {\r
- String topicFilterProp = "requestID=$.requestID,subRequestID=$.subRequestID,"\r
- + "closedLoopControlName=$.closedLoopControlName";\r
- MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);\r
-\r
- FilterRule rule = topicFilter.getFilterRule("requestID");\r
- assertNotNull(rule);\r
- }\r
-\r
- /**\r
- * Tests throwing an exception for passing in a null key.\r
- */\r
- @Test(expected = IllegalArgumentException.class)\r
- public void getFilterRuleNullKeyTest() {\r
- String topicFilterProp = "requestID=$.requestID,subRequestID=$.subRequestID";\r
- MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);\r
- topicFilter.getFilterRule(null);\r
- }\r
-\r
- /**\r
- * Tests throwing an exception for passing in an empty key.\r
- */\r
- @Test(expected = IllegalArgumentException.class)\r
- public void getFilterRuleEmptyKeyTest() {\r
- String topicFilterProp = "requestID=$.requestID,subRequestID=$.subRequestID";\r
- MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);\r
- topicFilter.getFilterRule("");\r
- }\r
-\r
- /**\r
- * Tests adding a filter rule with a single path.\r
- */\r
- @Test\r
- public void addFilterRuleSinglePathTest() {\r
- String topicFilterProp = "requestID=$.requestID";\r
- MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);\r
-\r
- String key = "subRequestID";\r
- String path = "$.subRequestID";\r
- FilterRule rule = topicFilter.addFilterRule(key, path);\r
- assertEquals(topicFilter.getFilterRule(key), rule);\r
- }\r
-\r
- /**\r
- * Tests adding a filter rule with multiple paths.\r
- */\r
- @Test\r
- public void addFilterRuleMultiPathTest() {\r
- String topicFilterProp = "requestID=$.requestID";\r
- MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);\r
-\r
- String key = "subRequestID";\r
- List<String> paths = Arrays.asList("$.subRequestID", "$.sub-request-id");\r
- FilterRule rule = topicFilter.addFilterRule(key, paths);\r
- assertEquals(topicFilter.getFilterRule(key), rule);\r
- }\r
-\r
- /**\r
- * Tests throwing an exception for passing a null key and a\r
- * single path.\r
- */\r
- @Test(expected = IllegalArgumentException.class)\r
- public void addFilterRuleNullKeyStringPathTest() {\r
- String topicFilterProp = "requestID=$.requestID";\r
- MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);\r
- topicFilter.addFilterRule(null, "$.subRequestID");\r
- }\r
-\r
- /**\r
- * Tests throwing an exception for passing a null key and a list\r
- * of paths.\r
- */\r
- @Test(expected = IllegalArgumentException.class)\r
- public void addFilterRuleNullKeyPathListTest() {\r
- String topicFilterProp = "requestID=$.requestID";\r
- MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);\r
- topicFilter.addFilterRule(null, Arrays.asList("$.subRequestID"));\r
- }\r
-\r
- /**\r
- * Tests throwing an exception for passing an empty key and\r
- * a single path.\r
- */\r
- @Test(expected = IllegalArgumentException.class)\r
- public void addFilterRuleEmptyKeyStringPathTest() {\r
- String topicFilterProp = "requestID=$.requestID";\r
- MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);\r
- topicFilter.addFilterRule("", "$.subRequestID");\r
- }\r
-\r
- /**\r
- * Tests throwing an exception for passing an empty key and\r
- * a list of paths.\r
- */\r
- @Test(expected = IllegalArgumentException.class)\r
- public void addFilterRuleEmptyKeyPathListTest() {\r
- String topicFilterProp = "requestID=$.requestID";\r
- MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);\r
- topicFilter.addFilterRule("", Arrays.asList("$.subRequestID"));\r
- }\r
-\r
- /**\r
- * Tests throwing an exception for passing an empty path string.\r
- */\r
- @Test(expected = IllegalArgumentException.class)\r
- public void addFilterRuleEmptyPathTest() {\r
- String topicFilterProp = "requestID=$.requestID";\r
- MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);\r
- topicFilter.addFilterRule("subRequestID", "");\r
- }\r
-\r
- /**\r
- * Tests throwing an exception for passing an empty paths list.\r
- */\r
- @Test(expected = IllegalArgumentException.class)\r
- public void addFilterRuleEmptyPathsTest() {\r
- String topicFilterProp = "requestID=$.requestID";\r
- MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);\r
- topicFilter.addFilterRule("subRequestID", Arrays.asList());\r
- }\r
-\r
- /**\r
- * Tests throwing an exception for trying to add a filter with a key that\r
- * already exists with a single filter.\r
- */\r
- @Test(expected = IllegalArgumentException.class)\r
- public void addExistingFilterRuleStringTest() {\r
- String topicFilterProp = "requestID=$.requestID";\r
- MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);\r
- topicFilter.addFilterRule("requestID", "$.test");\r
- }\r
-\r
- /**\r
- * Tests throwing an exception for trying to add a filter with a key that\r
- * already exists with a list of filters.\r
- */\r
- @Test(expected = IllegalArgumentException.class)\r
- public void addExistingFilterRuleListTest() {\r
- String topicFilterProp = "requestID=$.requestID";\r
- MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);\r
- topicFilter.addFilterRule("requestID", Arrays.asList("$.test"));\r
- }\r
-\r
- @Test\r
- public void createFilterRuleExceptionTest() {\r
- assertThatIllegalArgumentException().isThrownBy(() -> new MdcTopicFilter("invalid filter"))\r
- .withMessage("could not parse filter rule");\r
- }\r
-\r
- /**\r
- * Tests modifying a filter rule to add a new path.\r
- */\r
- @Test\r
- public void modifyFilterRuleSinglePathTest() {\r
- String topicFilterProp = "requestID=$.requestID";\r
- MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);\r
-\r
- FilterRule rule = topicFilter.modifyFilterRule("requestID", "$.request-id");\r
- assertEquals(topicFilter.getFilterRule("requestID"), rule);\r
- assertEquals(Arrays.asList("$.requestID", "$.request-id"), rule.getPaths());\r
- }\r
-\r
- /**\r
- * Tests modifying a filter rule to add a list of new paths.\r
- */\r
- @Test\r
- public void modifyFilterRuleMultiPathTest() {\r
- String topicFilterProp = "requestID=$.requestID";\r
- MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);\r
-\r
- FilterRule rule = topicFilter.modifyFilterRule("requestID",\r
- Arrays.asList("$.request-id", "$.requestId"));\r
- assertEquals(topicFilter.getFilterRule("requestID"), rule);\r
- assertEquals(\r
- Arrays.asList("$.requestID", "$.request-id", "$.requestId"),\r
- rule.getPaths());\r
- }\r
-\r
- @Test\r
- public void modifyFilterRuleMultiPathExceptionTest() {\r
- MdcTopicFilter filter = new MdcTopicFilter("abc=$a.value");\r
- assertThatIllegalArgumentException()\r
- .isThrownBy(() -> filter.modifyFilterRule("def", "abc", Arrays.asList("$.b", "$.c")))\r
- .withMessage("a filter rule already exists for key: abc");\r
- }\r
-\r
- /**\r
- * Tests modifying a filter rule key.\r
- */\r
- @Test\r
- public void modifyFilterRuleKeyTest() {\r
- String topicFilterProp = "requestID=$.requestID";\r
- MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);\r
-\r
- FilterRule rule = topicFilter.modifyFilterRule("requestID",\r
- "request-id", Arrays.asList("$.request-id"));\r
- assertEquals(topicFilter.getFilterRule("request-id"), rule);\r
- assertEquals("[$.request-id]", rule.getPaths().toString());\r
- }\r
-\r
- /**\r
- * Tests throwing an exception when passing a null key and\r
- * a single path.\r
- */\r
- @Test(expected = IllegalArgumentException.class)\r
- public void modifyFilterRuleNullKeyStringPathTest() {\r
- String topicFilterProp = "requestID=$.requestID";\r
- MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);\r
- topicFilter.modifyFilterRule(null, "$.request-id");\r
- }\r
-\r
- /**\r
- * Tests throwing an exception when passing a null key and\r
- * a list of multiple paths.\r
- */\r
- @Test(expected = IllegalArgumentException.class)\r
- public void modifyFilterRuleNullKeyPathListTest() {\r
- String topicFilterProp = "requestID=$.requestID";\r
- MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);\r
- topicFilter.modifyFilterRule(null, Arrays.asList("$.request-id"));\r
- }\r
-\r
- /**\r
- * Tests throwing an exception when passing an empty key and\r
- * a single path.\r
- */\r
- @Test(expected = IllegalArgumentException.class)\r
- public void modifyFilterRuleEmptyKeyStringPathTest() {\r
- String topicFilterProp = "requestID=$.requestID";\r
- MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);\r
- topicFilter.modifyFilterRule("", "$.request-id");\r
- }\r
-\r
- /**\r
- * Tests throwing an exception when passing an empty key and\r
- * a list of multiple paths.\r
- */\r
- @Test(expected = IllegalArgumentException.class)\r
- public void modifyFilterRuleEmptyKeyPathListTest() {\r
- String topicFilterProp = "requestID=$.requestID";\r
- MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);\r
- topicFilter.modifyFilterRule("", Arrays.asList("$.request-id"));\r
- }\r
-\r
- /**\r
- * Tests throwing an exception when passing an empty string path.\r
- */\r
- @Test(expected = IllegalArgumentException.class)\r
- public void modifyFilterRuleEmptyPathStringTest() {\r
- String topicFilterProp = "requestID=$.requestID";\r
- MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);\r
- topicFilter.modifyFilterRule("requestID", "");\r
- }\r
-\r
- /**\r
- * Tests throwing an exception when passing an empty list of paths.\r
- */\r
- @Test(expected = IllegalArgumentException.class)\r
- public void modifyFilterRuleEmptyPathListTest() {\r
- String topicFilterProp = "requestID=$.requestID";\r
- MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);\r
- topicFilter.modifyFilterRule("requestID", Arrays.asList());\r
- }\r
-\r
- /**\r
- * Tests throwing an exception when passing a key that is\r
- * not in the filter rules map and a string path.\r
- */\r
- @Test(expected = IllegalArgumentException.class)\r
- public void modifyFilterRuleMissingKeyStringPathTest() {\r
- String topicFilterProp = "requestID=$.requestID";\r
- MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);\r
- topicFilter.modifyFilterRule("request-id", "$.request-id");\r
- }\r
-\r
- /**\r
- * Tests throwing an exception when passing a key that is\r
- * not in the filter rules map and a list of paths.\r
- */\r
- @Test(expected = IllegalArgumentException.class)\r
- public void modifyFilterRuleMissingKeyPathListTest() {\r
- String topicFilterProp = "requestID=$.requestID";\r
- MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);\r
- topicFilter.modifyFilterRule("request-id", Arrays.asList("$.request-id"));\r
- }\r
-\r
-\r
- /**\r
- * Tests throwing an exception when passing a null oldKey.\r
- */\r
- @Test(expected = IllegalArgumentException.class)\r
- public void modifyFilterRuleNullOldKeyTest() {\r
- String topicFilterProp = "requestID=$.requestID";\r
- MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);\r
- topicFilter.modifyFilterRule(null, "request-id", Arrays.asList("$.request-id"));\r
- }\r
-\r
- /**\r
- * Tests throwing an exception when passing an empty oldKey.\r
- */\r
- @Test(expected = IllegalArgumentException.class)\r
- public void modifyFilterRuleEmptyOldKeyTest() {\r
- String topicFilterProp = "requestID=$.requestID";\r
- MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);\r
- topicFilter.modifyFilterRule("", "request-id", Arrays.asList("$.request-id"));\r
- }\r
-\r
- /**\r
- * Tests throwing an exception when passing a null newKey.\r
- */\r
- @Test(expected = IllegalArgumentException.class)\r
- public void modifyFilterRuleNullNewKeyTest() {\r
- String topicFilterProp = "requestID=$.requestID";\r
- MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);\r
- topicFilter.modifyFilterRule("requestID", null, Arrays.asList("$.request-id"));\r
- }\r
-\r
- /**\r
- * Tests throwing an exception when passing an empty newKey.\r
- */\r
- @Test(expected = IllegalArgumentException.class)\r
- public void modifyFilterRuleEmptyNewKeyTest() {\r
- String topicFilterProp = "requestID=$.requestID";\r
- MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);\r
- topicFilter.modifyFilterRule("requestID", "", Arrays.asList("$.request-id"));\r
- }\r
-\r
- /**\r
- * Tests throwing an exception when the old and new key are the same.\r
- */\r
- @Test(expected = IllegalArgumentException.class)\r
- public void modifyFilterRuleSameKeyTest() {\r
- String topicFilterProp = "requestID=$.requestID";\r
- MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);\r
- topicFilter.modifyFilterRule("requestID", "requestID",\r
- Arrays.asList("$.request-id"));\r
- }\r
-\r
- /**\r
- * Tests throwing an exception when passing an empty paths list.\r
- */\r
- @Test(expected = IllegalArgumentException.class)\r
- public void modifyFilterRuleEmptyPathsTest() {\r
- String topicFilterProp = "requestID=$.requestID";\r
- MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);\r
- topicFilter.modifyFilterRule("requestID", "request-id", Arrays.asList());\r
- }\r
-\r
- /**\r
- * Tests throwing an exception when the old key doesn't exist\r
- * in the rules map.\r
- */\r
- @Test(expected = IllegalArgumentException.class)\r
- public void modifyFilterRuleNonExistingOldKeyTest() {\r
- String topicFilterProp = "requestID=$.requestID";\r
- MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);\r
- topicFilter.modifyFilterRule("request-id", "id", Arrays.asList("$.request-id"));\r
- }\r
-\r
- /**\r
- * Tests deleting all filter rules in the rules map.\r
- */\r
- @Test\r
- public void deleteAllFilterRulesTest() {\r
- String topicFilterProp = "requestID=$.requestID,subRequestID=$.subRequestID,"\r
- + "closedLoopControlName=$.closedLoopControlName";\r
- MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);\r
-\r
- assertEquals(3, topicFilter.getFilterRule().size());\r
- topicFilter.deleteFilterRule();\r
- assertEquals(0, topicFilter.getFilterRule().size());\r
- }\r
-\r
- /**\r
- * Tests deleting a single filter rule by its key from the rules map.\r
- */\r
- @Test\r
- public void deleteFilterRuleTest() {\r
- String topicFilterProp = "requestID=$.requestID,subRequestID=$.subRequestID,"\r
- + "closedLoopControlName=$.closedLoopControlName";\r
- MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);\r
-\r
- assertEquals(3, topicFilter.getFilterRule().size());\r
- topicFilter.deleteFilterRule("closedLoopControlName");\r
- assertEquals(2, topicFilter.getFilterRule().size());\r
- }\r
-\r
- /**\r
- * Tests throwing an exception if the key is null.\r
- */\r
- @Test(expected = IllegalArgumentException.class)\r
- public void deleteFilterRuleNullKeyTest() {\r
- String topicFilterProp = "requestID=$.requestID,subRequestID=$.subRequestID,"\r
- + "closedLoopControlName=$.closedLoopControlName";\r
- MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);\r
- topicFilter.deleteFilterRule(null);\r
- }\r
-\r
- /**\r
- * Tests throwing an exception if the key is empty.\r
- */\r
- @Test(expected = IllegalArgumentException.class)\r
- public void deleteFilterRuleEmptyKeyTest() {\r
- String topicFilterProp = "requestID=$.requestID,subRequestID=$.subRequestID,"\r
- + "closedLoopControlName=$.closedLoopControlName";\r
- MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);\r
- topicFilter.deleteFilterRule("");\r
- }\r
-\r
- /**\r
- * Tests finding all results for each filter rule corresponding to a topic.\r
- */\r
- @Test\r
- public void findAllTest() {\r
- String message = "{\"requestID\":\"38adde30-cc22-11e8-a8d5-f2801f1b9fd1\",\"entity\":\"controller\","\r
- + "\"controllers\":[{\"name\":\"test-controller\","\r
- + "\"drools\":{\"groupId\":\"org.onap.policy.drools.test\","\r
- + "\"artifactId\":\"test\",\"version\":\"0.0.1\"},\"operation\":\"update\"}]}";\r
-\r
- String topicFilterProp = "requestID=$.requestID,controllerName=$.controllers[0].name,"\r
- + "operation=$.controllers[0].operation";\r
- MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);\r
-\r
- Map<String, List<String>> results = topicFilter.find(message);\r
- assertEquals("38adde30-cc22-11e8-a8d5-f2801f1b9fd1",\r
- results.get("requestID").get(0));\r
- assertEquals("test-controller", results.get("controllerName").get(0));\r
- assertEquals("update", results.get("operation").get(0));\r
- }\r
-\r
- @Test\r
- public void findAllNotFoundTest() {\r
- String message = "{\"requestID\":\"38adde30-cc22-11e8-a8d5-f2801f1b9fd1\",\"entity\":\"controller\","\r
- + "\"controllers\":[{\"name\":\"test-controller\","\r
- + "\"drools\":{\"groupId\":\"org.onap.policy.drools.test\","\r
- + "\"artifactId\":\"test\",\"version\":\"0.0.1\"},\"operation\":\"update\"}]}";\r
-\r
- String topicFilterProp = "requestID=$.requestID[3]";\r
- MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);\r
-\r
- assertTrue(topicFilter.find(message).get("requestID").isEmpty());\r
- }\r
-\r
- /**\r
- * Tests finding field matches for a filter rule corresponding to a topic.\r
- */\r
- @Test\r
- public void findTest() {\r
- String message = "{\"requestID\":\"38adde30-cc22-11e8-a8d5-f2801f1b9fd1\",\"entity\":\"controller\","\r
- + "\"controllers\":[{\"name\":\"test-controller\","\r
- + "\"drools\":{\"groupId\":\"org.onap.policy.drools.test\","\r
- + "\"artifactId\":\"test\",\"version\":\"0.0.1\"},\"operation\":\"update\"}]}";\r
-\r
- String topicFilterProp = "requestID=$.requestID,controllerName=$.controllers[0].name,"\r
- + "operation=$.controllers[0].operation";\r
- MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);\r
-\r
- List<String> results = topicFilter.find(message, "requestID");\r
- assertEquals("38adde30-cc22-11e8-a8d5-f2801f1b9fd1", results.get(0));\r
- }\r
-\r
- @Test\r
- public void findNotFoundTest() {\r
- String message = "{\"requestID\":\"38adde30-cc22-11e8-a8d5-f2801f1b9fd1\",\"entity\":\"controller\","\r
- + "\"controllers\":[{\"name\":\"test-controller\","\r
- + "\"drools\":{\"groupId\":\"org.onap.policy.drools.test\","\r
- + "\"artifactId\":\"test\",\"version\":\"0.0.1\"},\"operation\":\"update\"}]}";\r
-\r
- String topicFilterProp = "requestID=$.requestID[3]";\r
- MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);\r
-\r
- assertTrue(topicFilter.find(message, "requestID").isEmpty());\r
- }\r
-\r
- @Test\r
- public void testFilterRuleStringString() {\r
- FilterRule rule = new FilterRule("hello", "world");\r
-\r
- assertEquals("hello", rule.getMdcKey());\r
- assertEquals("[world]", rule.getPaths().toString());\r
- }\r
-\r
- @Test\r
- public void testFilterRuleMdcKey() {\r
- FilterRule rule = new FilterRule("abc", "def");\r
-\r
- // check error cases first\r
- assertThatIllegalArgumentException().isThrownBy(() -> rule.setMdcKey(null))\r
- .withMessage(MdcTopicFilter.MDC_KEY_ERROR);\r
- assertThatIllegalArgumentException().isThrownBy(() -> rule.setMdcKey(""))\r
- .withMessage(MdcTopicFilter.MDC_KEY_ERROR);\r
-\r
- // success cases\r
- rule.setMdcKey("my-mdc-key");\r
- assertEquals("my-mdc-key", rule.getMdcKey());\r
- }\r
-\r
- @Test\r
- public void testFilterRulePaths() {\r
- FilterRule rule = new FilterRule("abc", "def");\r
-\r
- // check error cases first\r
- assertThatIllegalArgumentException().isThrownBy(() -> rule.setPaths(null))\r
- .withMessage(MdcTopicFilter.JSON_PATH_ERROR);\r
- assertThatIllegalArgumentException().isThrownBy(() -> rule.setPaths(Collections.emptyList()))\r
- .withMessage(MdcTopicFilter.JSON_PATH_ERROR);\r
-\r
- assertThatIllegalArgumentException().isThrownBy(() -> rule.addPaths(null))\r
- .withMessage(MdcTopicFilter.JSON_PATH_ERROR);\r
- assertThatIllegalArgumentException().isThrownBy(() -> rule.addPaths(Collections.emptyList()))\r
- .withMessage(MdcTopicFilter.JSON_PATH_ERROR);\r
-\r
- assertThatIllegalArgumentException().isThrownBy(() -> rule.addPath(null))\r
- .withMessage(MdcTopicFilter.JSON_PATH_ERROR);\r
- assertThatIllegalArgumentException().isThrownBy(() -> rule.addPath(""))\r
- .withMessage(MdcTopicFilter.JSON_PATH_ERROR);\r
-\r
- // success cases\r
- rule.setPaths(new ArrayList<>(Arrays.asList("pathA", "pathB")));\r
- assertEquals("[pathA, pathB]", rule.getPaths().toString());\r
-\r
- rule.addPath("pathC");\r
- assertEquals("[pathA, pathB, pathC]", rule.getPaths().toString());\r
-\r
- rule.addPaths(Arrays.asList("pathD", "pathE"));\r
- assertEquals("[pathA, pathB, pathC, pathD, pathE]", rule.getPaths().toString());\r
- }\r
-}\r
+/*
+ * ============LICENSE_START=======================================================
+ * feature-mdc-filters
+ * ================================================================================
+ * Copyright (C) 2019 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.drools.mdc.filters;
+
+import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import org.junit.Test;
+import org.onap.policy.drools.mdc.filters.MdcTopicFilter.FilterRule;
+
+public class MdcTopicFilterTest {
+
+ /**
+ * Test the simple case of having one filter rule for a key.
+ */
+ @Test
+ public void singleFilterOnePathTest() {
+ String topicFilterProp = "requestID=$.requestID";
+ MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
+
+ FilterRule rule = topicFilter.getFilterRule("requestID");
+ assertEquals("requestID", rule.getMdcKey());
+ assertEquals("[$.requestID]", rule.getPaths().toString());
+ }
+
+ /**
+ * Tests having one filter rule with a set of potential paths to the key.
+ */
+ @Test
+ public void singleFilterMultiPathTest() {
+ String topicFilterProp = "requestID=$.requestID|$.request-id";
+ MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
+
+ FilterRule rule = topicFilter.getFilterRule("requestID");
+ assertEquals("requestID", rule.getMdcKey());
+ assertEquals(2, rule.getPaths().size());
+ assertEquals("[$.requestID, $.request-id]", rule.getPaths().toString());
+ }
+
+ /**
+ * Tests having two filter rules that each have one key/path pair.
+ */
+ @Test
+ public void multiFilterSinglePathTest() {
+ String topicFilterProp = "requestID=$.requestID,closedLoopControlName=$.closedLoopControlName";
+ MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
+
+ FilterRule rule = topicFilter.getFilterRule("requestID");
+ assertEquals("requestID", rule.getMdcKey());
+ assertEquals(1, rule.getPaths().size());
+ assertEquals("[$.requestID]", rule.getPaths().toString());
+
+ FilterRule rule2 = topicFilter.getFilterRule("closedLoopControlName");
+ assertEquals("closedLoopControlName", rule2.getMdcKey());
+ assertEquals(1, rule2.getPaths().size());
+ assertEquals("[$.closedLoopControlName]", rule2.getPaths().toString());
+ }
+
+ /**
+ * Tests having two filter rules that each have two key/path pairs.
+ */
+ @Test
+ public void multiFilterMultiPathTest() {
+ String topicFilterProp = "requestID=$.requestID|$.body.request-id,"
+ + "closedLoopControlName=$.closedLoopControlName"
+ + "|$.body.closedLoopControlName";
+ MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
+
+ FilterRule rule = topicFilter.getFilterRule("requestID");
+ assertEquals("requestID", rule.getMdcKey());
+ assertEquals(2, rule.getPaths().size());
+ assertEquals("[$.requestID, $.body.request-id]", rule.getPaths().toString());
+
+ FilterRule rule2 = topicFilter.getFilterRule("closedLoopControlName");
+ assertEquals("closedLoopControlName", rule2.getMdcKey());
+ assertEquals(2, rule2.getPaths().size());
+ assertEquals("[$.closedLoopControlName, $.body.closedLoopControlName]", rule2.getPaths().toString());
+ }
+
+ /**
+ * Tests that the regex split logic for '|' in the feature code doesn't
+ * break parsing when "||" is used as a predicate in a JsonPath query.
+ */
+ @Test
+ public void addOrPredicateFilterTest() {
+ String topicFilterProp = "requestID=$.requestID||$.body.requestID";
+ MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
+ assertEquals(1, topicFilter.getFilterRule().size());
+ assertEquals("requestID", topicFilter.getFilterRule("requestID").getMdcKey());
+ assertEquals(Arrays.asList("$.requestID||$.body.requestID"), topicFilter
+ .getFilterRule("requestID").getPaths());
+ }
+
+ /**
+ * Tests getting all filter rules for a given topic.
+ */
+ @Test
+ public void getAllFilterRulesTest() {
+ String topicFilterProp = "requestID=$.requestID,subRequestID=$.subRequestID,"
+ + "closedLoopControlName=$.closedLoopControlName";
+ MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
+ assertEquals(3, topicFilter.getFilterRule().size());
+ }
+
+ /**
+ * Tests getting a filter rule by its key.
+ */
+ @Test
+ public void getFilterRuleTest() {
+ String topicFilterProp = "requestID=$.requestID,subRequestID=$.subRequestID,"
+ + "closedLoopControlName=$.closedLoopControlName";
+ MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
+
+ FilterRule rule = topicFilter.getFilterRule("requestID");
+ assertNotNull(rule);
+ }
+
+ /**
+ * Tests throwing an exception for passing in a null key.
+ */
+ @Test(expected = IllegalArgumentException.class)
+ public void getFilterRuleNullKeyTest() {
+ String topicFilterProp = "requestID=$.requestID,subRequestID=$.subRequestID";
+ MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
+ topicFilter.getFilterRule(null);
+ }
+
+ /**
+ * Tests throwing an exception for passing in an empty key.
+ */
+ @Test(expected = IllegalArgumentException.class)
+ public void getFilterRuleEmptyKeyTest() {
+ String topicFilterProp = "requestID=$.requestID,subRequestID=$.subRequestID";
+ MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
+ topicFilter.getFilterRule("");
+ }
+
+ /**
+ * Tests adding a filter rule with a single path.
+ */
+ @Test
+ public void addFilterRuleSinglePathTest() {
+ String topicFilterProp = "requestID=$.requestID";
+ MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
+
+ String key = "subRequestID";
+ String path = "$.subRequestID";
+ FilterRule rule = topicFilter.addFilterRule(key, path);
+ assertEquals(topicFilter.getFilterRule(key), rule);
+ }
+
+ /**
+ * Tests adding a filter rule with multiple paths.
+ */
+ @Test
+ public void addFilterRuleMultiPathTest() {
+ String topicFilterProp = "requestID=$.requestID";
+ MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
+
+ String key = "subRequestID";
+ List<String> paths = Arrays.asList("$.subRequestID", "$.sub-request-id");
+ FilterRule rule = topicFilter.addFilterRule(key, paths);
+ assertEquals(topicFilter.getFilterRule(key), rule);
+ }
+
+ /**
+ * Tests throwing an exception for passing a null key and a
+ * single path.
+ */
+ @Test(expected = IllegalArgumentException.class)
+ public void addFilterRuleNullKeyStringPathTest() {
+ String topicFilterProp = "requestID=$.requestID";
+ MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
+ topicFilter.addFilterRule(null, "$.subRequestID");
+ }
+
+ /**
+ * Tests throwing an exception for passing a null key and a list
+ * of paths.
+ */
+ @Test(expected = IllegalArgumentException.class)
+ public void addFilterRuleNullKeyPathListTest() {
+ String topicFilterProp = "requestID=$.requestID";
+ MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
+ topicFilter.addFilterRule(null, Arrays.asList("$.subRequestID"));
+ }
+
+ /**
+ * Tests throwing an exception for passing an empty key and
+ * a single path.
+ */
+ @Test(expected = IllegalArgumentException.class)
+ public void addFilterRuleEmptyKeyStringPathTest() {
+ String topicFilterProp = "requestID=$.requestID";
+ MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
+ topicFilter.addFilterRule("", "$.subRequestID");
+ }
+
+ /**
+ * Tests throwing an exception for passing an empty key and
+ * a list of paths.
+ */
+ @Test(expected = IllegalArgumentException.class)
+ public void addFilterRuleEmptyKeyPathListTest() {
+ String topicFilterProp = "requestID=$.requestID";
+ MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
+ topicFilter.addFilterRule("", Arrays.asList("$.subRequestID"));
+ }
+
+ /**
+ * Tests throwing an exception for passing an empty path string.
+ */
+ @Test(expected = IllegalArgumentException.class)
+ public void addFilterRuleEmptyPathTest() {
+ String topicFilterProp = "requestID=$.requestID";
+ MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
+ topicFilter.addFilterRule("subRequestID", "");
+ }
+
+ /**
+ * Tests throwing an exception for passing an empty paths list.
+ */
+ @Test(expected = IllegalArgumentException.class)
+ public void addFilterRuleEmptyPathsTest() {
+ String topicFilterProp = "requestID=$.requestID";
+ MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
+ topicFilter.addFilterRule("subRequestID", Arrays.asList());
+ }
+
+ /**
+ * Tests throwing an exception for trying to add a filter with a key that
+ * already exists with a single filter.
+ */
+ @Test(expected = IllegalArgumentException.class)
+ public void addExistingFilterRuleStringTest() {
+ String topicFilterProp = "requestID=$.requestID";
+ MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
+ topicFilter.addFilterRule("requestID", "$.test");
+ }
+
+ /**
+ * Tests throwing an exception for trying to add a filter with a key that
+ * already exists with a list of filters.
+ */
+ @Test(expected = IllegalArgumentException.class)
+ public void addExistingFilterRuleListTest() {
+ String topicFilterProp = "requestID=$.requestID";
+ MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
+ topicFilter.addFilterRule("requestID", Arrays.asList("$.test"));
+ }
+
+ @Test
+ public void createFilterRuleExceptionTest() {
+ assertThatIllegalArgumentException().isThrownBy(() -> new MdcTopicFilter("invalid filter"))
+ .withMessage("could not parse filter rule");
+ }
+
+ /**
+ * Tests modifying a filter rule to add a new path.
+ */
+ @Test
+ public void modifyFilterRuleSinglePathTest() {
+ String topicFilterProp = "requestID=$.requestID";
+ MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
+
+ FilterRule rule = topicFilter.modifyFilterRule("requestID", "$.request-id");
+ assertEquals(topicFilter.getFilterRule("requestID"), rule);
+ assertEquals(Arrays.asList("$.requestID", "$.request-id"), rule.getPaths());
+ }
+
+ /**
+ * Tests modifying a filter rule to add a list of new paths.
+ */
+ @Test
+ public void modifyFilterRuleMultiPathTest() {
+ String topicFilterProp = "requestID=$.requestID";
+ MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
+
+ FilterRule rule = topicFilter.modifyFilterRule("requestID",
+ Arrays.asList("$.request-id", "$.requestId"));
+ assertEquals(topicFilter.getFilterRule("requestID"), rule);
+ assertEquals(
+ Arrays.asList("$.requestID", "$.request-id", "$.requestId"),
+ rule.getPaths());
+ }
+
+ @Test
+ public void modifyFilterRuleMultiPathExceptionTest() {
+ MdcTopicFilter filter = new MdcTopicFilter("abc=$a.value");
+ assertThatIllegalArgumentException()
+ .isThrownBy(() -> filter.modifyFilterRule("def", "abc", Arrays.asList("$.b", "$.c")))
+ .withMessage("a filter rule already exists for key: abc");
+ }
+
+ /**
+ * Tests modifying a filter rule key.
+ */
+ @Test
+ public void modifyFilterRuleKeyTest() {
+ String topicFilterProp = "requestID=$.requestID";
+ MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
+
+ FilterRule rule = topicFilter.modifyFilterRule("requestID",
+ "request-id", Arrays.asList("$.request-id"));
+ assertEquals(topicFilter.getFilterRule("request-id"), rule);
+ assertEquals("[$.request-id]", rule.getPaths().toString());
+ }
+
+ /**
+ * Tests throwing an exception when passing a null key and
+ * a single path.
+ */
+ @Test(expected = IllegalArgumentException.class)
+ public void modifyFilterRuleNullKeyStringPathTest() {
+ String topicFilterProp = "requestID=$.requestID";
+ MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
+ topicFilter.modifyFilterRule(null, "$.request-id");
+ }
+
+ /**
+ * Tests throwing an exception when passing a null key and
+ * a list of multiple paths.
+ */
+ @Test(expected = IllegalArgumentException.class)
+ public void modifyFilterRuleNullKeyPathListTest() {
+ String topicFilterProp = "requestID=$.requestID";
+ MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
+ topicFilter.modifyFilterRule(null, Arrays.asList("$.request-id"));
+ }
+
+ /**
+ * Tests throwing an exception when passing an empty key and
+ * a single path.
+ */
+ @Test(expected = IllegalArgumentException.class)
+ public void modifyFilterRuleEmptyKeyStringPathTest() {
+ String topicFilterProp = "requestID=$.requestID";
+ MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
+ topicFilter.modifyFilterRule("", "$.request-id");
+ }
+
+ /**
+ * Tests throwing an exception when passing an empty key and
+ * a list of multiple paths.
+ */
+ @Test(expected = IllegalArgumentException.class)
+ public void modifyFilterRuleEmptyKeyPathListTest() {
+ String topicFilterProp = "requestID=$.requestID";
+ MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
+ topicFilter.modifyFilterRule("", Arrays.asList("$.request-id"));
+ }
+
+ /**
+ * Tests throwing an exception when passing an empty string path.
+ */
+ @Test(expected = IllegalArgumentException.class)
+ public void modifyFilterRuleEmptyPathStringTest() {
+ String topicFilterProp = "requestID=$.requestID";
+ MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
+ topicFilter.modifyFilterRule("requestID", "");
+ }
+
+ /**
+ * Tests throwing an exception when passing an empty list of paths.
+ */
+ @Test(expected = IllegalArgumentException.class)
+ public void modifyFilterRuleEmptyPathListTest() {
+ String topicFilterProp = "requestID=$.requestID";
+ MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
+ topicFilter.modifyFilterRule("requestID", Arrays.asList());
+ }
+
+ /**
+ * Tests throwing an exception when passing a key that is
+ * not in the filter rules map and a string path.
+ */
+ @Test(expected = IllegalArgumentException.class)
+ public void modifyFilterRuleMissingKeyStringPathTest() {
+ String topicFilterProp = "requestID=$.requestID";
+ MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
+ topicFilter.modifyFilterRule("request-id", "$.request-id");
+ }
+
+ /**
+ * Tests throwing an exception when passing a key that is
+ * not in the filter rules map and a list of paths.
+ */
+ @Test(expected = IllegalArgumentException.class)
+ public void modifyFilterRuleMissingKeyPathListTest() {
+ String topicFilterProp = "requestID=$.requestID";
+ MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
+ topicFilter.modifyFilterRule("request-id", Arrays.asList("$.request-id"));
+ }
+
+
+ /**
+ * Tests throwing an exception when passing a null oldKey.
+ */
+ @Test(expected = IllegalArgumentException.class)
+ public void modifyFilterRuleNullOldKeyTest() {
+ String topicFilterProp = "requestID=$.requestID";
+ MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
+ topicFilter.modifyFilterRule(null, "request-id", Arrays.asList("$.request-id"));
+ }
+
+ /**
+ * Tests throwing an exception when passing an empty oldKey.
+ */
+ @Test(expected = IllegalArgumentException.class)
+ public void modifyFilterRuleEmptyOldKeyTest() {
+ String topicFilterProp = "requestID=$.requestID";
+ MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
+ topicFilter.modifyFilterRule("", "request-id", Arrays.asList("$.request-id"));
+ }
+
+ /**
+ * Tests throwing an exception when passing a null newKey.
+ */
+ @Test(expected = IllegalArgumentException.class)
+ public void modifyFilterRuleNullNewKeyTest() {
+ String topicFilterProp = "requestID=$.requestID";
+ MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
+ topicFilter.modifyFilterRule("requestID", null, Arrays.asList("$.request-id"));
+ }
+
+ /**
+ * Tests throwing an exception when passing an empty newKey.
+ */
+ @Test(expected = IllegalArgumentException.class)
+ public void modifyFilterRuleEmptyNewKeyTest() {
+ String topicFilterProp = "requestID=$.requestID";
+ MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
+ topicFilter.modifyFilterRule("requestID", "", Arrays.asList("$.request-id"));
+ }
+
+ /**
+ * Tests throwing an exception when the old and new key are the same.
+ */
+ @Test(expected = IllegalArgumentException.class)
+ public void modifyFilterRuleSameKeyTest() {
+ String topicFilterProp = "requestID=$.requestID";
+ MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
+ topicFilter.modifyFilterRule("requestID", "requestID",
+ Arrays.asList("$.request-id"));
+ }
+
+ /**
+ * Tests throwing an exception when passing an empty paths list.
+ */
+ @Test(expected = IllegalArgumentException.class)
+ public void modifyFilterRuleEmptyPathsTest() {
+ String topicFilterProp = "requestID=$.requestID";
+ MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
+ topicFilter.modifyFilterRule("requestID", "request-id", Arrays.asList());
+ }
+
+ /**
+ * Tests throwing an exception when the old key doesn't exist
+ * in the rules map.
+ */
+ @Test(expected = IllegalArgumentException.class)
+ public void modifyFilterRuleNonExistingOldKeyTest() {
+ String topicFilterProp = "requestID=$.requestID";
+ MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
+ topicFilter.modifyFilterRule("request-id", "id", Arrays.asList("$.request-id"));
+ }
+
+ /**
+ * Tests deleting all filter rules in the rules map.
+ */
+ @Test
+ public void deleteAllFilterRulesTest() {
+ String topicFilterProp = "requestID=$.requestID,subRequestID=$.subRequestID,"
+ + "closedLoopControlName=$.closedLoopControlName";
+ MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
+
+ assertEquals(3, topicFilter.getFilterRule().size());
+ topicFilter.deleteFilterRule();
+ assertEquals(0, topicFilter.getFilterRule().size());
+ }
+
+ /**
+ * Tests deleting a single filter rule by its key from the rules map.
+ */
+ @Test
+ public void deleteFilterRuleTest() {
+ String topicFilterProp = "requestID=$.requestID,subRequestID=$.subRequestID,"
+ + "closedLoopControlName=$.closedLoopControlName";
+ MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
+
+ assertEquals(3, topicFilter.getFilterRule().size());
+ topicFilter.deleteFilterRule("closedLoopControlName");
+ assertEquals(2, topicFilter.getFilterRule().size());
+ }
+
+ /**
+ * Tests throwing an exception if the key is null.
+ */
+ @Test(expected = IllegalArgumentException.class)
+ public void deleteFilterRuleNullKeyTest() {
+ String topicFilterProp = "requestID=$.requestID,subRequestID=$.subRequestID,"
+ + "closedLoopControlName=$.closedLoopControlName";
+ MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
+ topicFilter.deleteFilterRule(null);
+ }
+
+ /**
+ * Tests throwing an exception if the key is empty.
+ */
+ @Test(expected = IllegalArgumentException.class)
+ public void deleteFilterRuleEmptyKeyTest() {
+ String topicFilterProp = "requestID=$.requestID,subRequestID=$.subRequestID,"
+ + "closedLoopControlName=$.closedLoopControlName";
+ MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
+ topicFilter.deleteFilterRule("");
+ }
+
+ /**
+ * Tests finding all results for each filter rule corresponding to a topic.
+ */
+ @Test
+ public void findAllTest() {
+ String message = "{\"requestID\":\"38adde30-cc22-11e8-a8d5-f2801f1b9fd1\",\"entity\":\"controller\","
+ + "\"controllers\":[{\"name\":\"test-controller\","
+ + "\"drools\":{\"groupId\":\"org.onap.policy.drools.test\","
+ + "\"artifactId\":\"test\",\"version\":\"0.0.1\"},\"operation\":\"update\"}]}";
+
+ String topicFilterProp = "requestID=$.requestID,controllerName=$.controllers[0].name,"
+ + "operation=$.controllers[0].operation";
+ MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
+
+ Map<String, List<String>> results = topicFilter.find(message);
+ assertEquals("38adde30-cc22-11e8-a8d5-f2801f1b9fd1",
+ results.get("requestID").get(0));
+ assertEquals("test-controller", results.get("controllerName").get(0));
+ assertEquals("update", results.get("operation").get(0));
+ }
+
+ @Test
+ public void findAllNotFoundTest() {
+ String message = "{\"requestID\":\"38adde30-cc22-11e8-a8d5-f2801f1b9fd1\",\"entity\":\"controller\","
+ + "\"controllers\":[{\"name\":\"test-controller\","
+ + "\"drools\":{\"groupId\":\"org.onap.policy.drools.test\","
+ + "\"artifactId\":\"test\",\"version\":\"0.0.1\"},\"operation\":\"update\"}]}";
+
+ String topicFilterProp = "requestID=$.requestID[3]";
+ MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
+
+ assertTrue(topicFilter.find(message).get("requestID").isEmpty());
+ }
+
+ /**
+ * Tests finding field matches for a filter rule corresponding to a topic.
+ */
+ @Test
+ public void findTest() {
+ String message = "{\"requestID\":\"38adde30-cc22-11e8-a8d5-f2801f1b9fd1\",\"entity\":\"controller\","
+ + "\"controllers\":[{\"name\":\"test-controller\","
+ + "\"drools\":{\"groupId\":\"org.onap.policy.drools.test\","
+ + "\"artifactId\":\"test\",\"version\":\"0.0.1\"},\"operation\":\"update\"}]}";
+
+ String topicFilterProp = "requestID=$.requestID,controllerName=$.controllers[0].name,"
+ + "operation=$.controllers[0].operation";
+ MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
+
+ List<String> results = topicFilter.find(message, "requestID");
+ assertEquals("38adde30-cc22-11e8-a8d5-f2801f1b9fd1", results.get(0));
+ }
+
+ @Test
+ public void findNotFoundTest() {
+ String message = "{\"requestID\":\"38adde30-cc22-11e8-a8d5-f2801f1b9fd1\",\"entity\":\"controller\","
+ + "\"controllers\":[{\"name\":\"test-controller\","
+ + "\"drools\":{\"groupId\":\"org.onap.policy.drools.test\","
+ + "\"artifactId\":\"test\",\"version\":\"0.0.1\"},\"operation\":\"update\"}]}";
+
+ String topicFilterProp = "requestID=$.requestID[3]";
+ MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
+
+ assertTrue(topicFilter.find(message, "requestID").isEmpty());
+ }
+
+ @Test
+ public void testFilterRuleStringString() {
+ FilterRule rule = new FilterRule("hello", "world");
+
+ assertEquals("hello", rule.getMdcKey());
+ assertEquals("[world]", rule.getPaths().toString());
+ }
+
+ @Test
+ public void testFilterRuleMdcKey() {
+ FilterRule rule = new FilterRule("abc", "def");
+
+ // check error cases first
+ assertThatIllegalArgumentException().isThrownBy(() -> rule.setMdcKey(null))
+ .withMessage(MdcTopicFilter.MDC_KEY_ERROR);
+ assertThatIllegalArgumentException().isThrownBy(() -> rule.setMdcKey(""))
+ .withMessage(MdcTopicFilter.MDC_KEY_ERROR);
+
+ // success cases
+ rule.setMdcKey("my-mdc-key");
+ assertEquals("my-mdc-key", rule.getMdcKey());
+ }
+
+ @Test
+ public void testFilterRulePaths() {
+ FilterRule rule = new FilterRule("abc", "def");
+
+ // check error cases first
+ assertThatIllegalArgumentException().isThrownBy(() -> rule.setPaths(null))
+ .withMessage(MdcTopicFilter.JSON_PATH_ERROR);
+ assertThatIllegalArgumentException().isThrownBy(() -> rule.setPaths(Collections.emptyList()))
+ .withMessage(MdcTopicFilter.JSON_PATH_ERROR);
+
+ assertThatIllegalArgumentException().isThrownBy(() -> rule.addPaths(null))
+ .withMessage(MdcTopicFilter.JSON_PATH_ERROR);
+ assertThatIllegalArgumentException().isThrownBy(() -> rule.addPaths(Collections.emptyList()))
+ .withMessage(MdcTopicFilter.JSON_PATH_ERROR);
+
+ assertThatIllegalArgumentException().isThrownBy(() -> rule.addPath(null))
+ .withMessage(MdcTopicFilter.JSON_PATH_ERROR);
+ assertThatIllegalArgumentException().isThrownBy(() -> rule.addPath(""))
+ .withMessage(MdcTopicFilter.JSON_PATH_ERROR);
+
+ // success cases
+ rule.setPaths(new ArrayList<>(Arrays.asList("pathA", "pathB")));
+ assertEquals("[pathA, pathB]", rule.getPaths().toString());
+
+ rule.addPath("pathC");
+ assertEquals("[pathA, pathB, pathC]", rule.getPaths().toString());
+
+ rule.addPaths(Arrays.asList("pathD", "pathE"));
+ assertEquals("[pathA, pathB, pathC, pathD, pathE]", rule.getPaths().toString());
+ }
+}