Fix new sonars in drools-pdp 00/113400/3
authorJim Hahn <jrh3@att.com>
Wed, 30 Sep 2020 18:32:56 +0000 (14:32 -0400)
committerJim Hahn <jrh3@att.com>
Wed, 30 Sep 2020 20:29:50 +0000 (16:29 -0400)
Addressed the following sonar issues:
- extract common test method
- too many assertions in test method
- don't always return the same value

Issue-ID: POLICY-2616
Change-Id: Iab836cdcd667b35e2db9db7d6ffc7896df33e1c8
Signed-off-by: Jim Hahn <jrh3@att.com>
feature-mdc-filters/src/test/java/org/onap/policy/drools/mdc/filters/MdcTopicFilterTest.java
feature-pooling-dmaap/src/main/java/org/onap/policy/drools/pooling/state/State.java
feature-pooling-dmaap/src/test/java/org/onap/policy/drools/pooling/PoolingManagerImplTest.java
feature-simulators/src/test/java/org/onap/policy/drools/simulators/DMaaPSimulatorTest.java
policy-core/src/main/java/org/onap/policy/drools/core/PolicyContainer.java
policy-management/src/test/java/org/onap/policy/drools/system/internal/AggregatedPolicyControllerTest.java
policy-utils/src/test/java/org/onap/policy/drools/utils/logging/MdcTransactionTest.java

index e1a9b9b..2a3f251 100755 (executable)
@@ -194,9 +194,7 @@ public class MdcTopicFilterTest {
      */
     @Test(expected = IllegalArgumentException.class)
     public void addFilterRuleNullKeyStringPathTest() {
-        String topicFilterProp = "requestID=$.requestID";
-        MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
-        topicFilter.addFilterRule(null, "$.subRequestID");
+        addFilterRuleValidateFailure(null, "$.subRequestID");
     }
 
     /**
@@ -205,9 +203,7 @@ public class MdcTopicFilterTest {
      */
     @Test(expected = IllegalArgumentException.class)
     public void addFilterRuleNullKeyPathListTest() {
-        String topicFilterProp = "requestID=$.requestID";
-        MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
-        topicFilter.addFilterRule(null, Arrays.asList("$.subRequestID"));
+        addFilterRuleValidateFailure(null, Arrays.asList("$.subRequestID"));
     }
 
     /**
@@ -216,9 +212,7 @@ public class MdcTopicFilterTest {
      */
     @Test(expected = IllegalArgumentException.class)
     public void addFilterRuleEmptyKeyStringPathTest() {
-        String topicFilterProp = "requestID=$.requestID";
-        MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
-        topicFilter.addFilterRule("", "$.subRequestID");
+        addFilterRuleValidateFailure("", "$.subRequestID");
     }
 
     /**
@@ -227,9 +221,7 @@ public class MdcTopicFilterTest {
      */
     @Test(expected = IllegalArgumentException.class)
     public void addFilterRuleEmptyKeyPathListTest() {
-        String topicFilterProp = "requestID=$.requestID";
-        MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
-        topicFilter.addFilterRule("", Arrays.asList("$.subRequestID"));
+        addFilterRuleValidateFailure("", Arrays.asList("$.subRequestID"));
     }
 
     /**
@@ -237,9 +229,7 @@ public class MdcTopicFilterTest {
      */
     @Test(expected = IllegalArgumentException.class)
     public void addFilterRuleEmptyPathTest() {
-        String topicFilterProp = "requestID=$.requestID";
-        MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
-        topicFilter.addFilterRule("subRequestID", "");
+        addFilterRuleValidateFailure("subRequestID", "");
     }
 
     /**
@@ -247,9 +237,7 @@ public class MdcTopicFilterTest {
      */
     @Test(expected = IllegalArgumentException.class)
     public void addFilterRuleEmptyPathsTest() {
-        String topicFilterProp = "requestID=$.requestID";
-        MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
-        topicFilter.addFilterRule("subRequestID", Arrays.asList());
+        addFilterRuleValidateFailure("subRequestID", Arrays.asList());
     }
 
     /**
@@ -258,9 +246,7 @@ public class MdcTopicFilterTest {
      */
     @Test(expected = IllegalArgumentException.class)
     public void addExistingFilterRuleStringTest() {
-        String topicFilterProp = "requestID=$.requestID";
-        MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
-        topicFilter.addFilterRule("requestID", "$.test");
+        addFilterRuleValidateFailure("requestID", "$.test");
     }
 
     /**
@@ -269,9 +255,7 @@ public class MdcTopicFilterTest {
      */
     @Test(expected = IllegalArgumentException.class)
     public void addExistingFilterRuleListTest() {
-        String topicFilterProp = "requestID=$.requestID";
-        MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
-        topicFilter.addFilterRule("requestID", Arrays.asList("$.test"));
+        addFilterRuleValidateFailure("requestID", Arrays.asList("$.test"));
     }
 
     @Test
@@ -337,9 +321,7 @@ public class MdcTopicFilterTest {
      */
     @Test(expected = IllegalArgumentException.class)
     public void modifyFilterRuleNullKeyStringPathTest() {
-        String topicFilterProp = "requestID=$.requestID";
-        MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
-        topicFilter.modifyFilterRule(null, "$.request-id");
+        modifyFilterRuleValidateFailure(null, "$.request-id");
     }
 
     /**
@@ -348,9 +330,7 @@ public class MdcTopicFilterTest {
      */
     @Test(expected = IllegalArgumentException.class)
     public void modifyFilterRuleNullKeyPathListTest() {
-        String topicFilterProp = "requestID=$.requestID";
-        MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
-        topicFilter.modifyFilterRule(null, Arrays.asList("$.request-id"));
+        modifyFilterRuleValidateFailure(null, Arrays.asList("$.request-id"));
     }
 
     /**
@@ -359,9 +339,7 @@ public class MdcTopicFilterTest {
      */
     @Test(expected = IllegalArgumentException.class)
     public void modifyFilterRuleEmptyKeyStringPathTest() {
-        String topicFilterProp = "requestID=$.requestID";
-        MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
-        topicFilter.modifyFilterRule("", "$.request-id");
+        modifyFilterRuleValidateFailure("", "$.request-id");
     }
 
     /**
@@ -370,9 +348,7 @@ public class MdcTopicFilterTest {
      */
     @Test(expected = IllegalArgumentException.class)
     public void modifyFilterRuleEmptyKeyPathListTest() {
-        String topicFilterProp = "requestID=$.requestID";
-        MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
-        topicFilter.modifyFilterRule("", Arrays.asList("$.request-id"));
+        modifyFilterRuleValidateFailure("", Arrays.asList("$.request-id"));
     }
 
     /**
@@ -380,9 +356,7 @@ public class MdcTopicFilterTest {
      */
     @Test(expected = IllegalArgumentException.class)
     public void modifyFilterRuleEmptyPathStringTest() {
-        String topicFilterProp = "requestID=$.requestID";
-        MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
-        topicFilter.modifyFilterRule("requestID", "");
+        modifyFilterRuleValidateFailure("requestID", "");
     }
 
     /**
@@ -390,9 +364,7 @@ public class MdcTopicFilterTest {
      */
     @Test(expected = IllegalArgumentException.class)
     public void modifyFilterRuleEmptyPathListTest() {
-        String topicFilterProp = "requestID=$.requestID";
-        MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
-        topicFilter.modifyFilterRule("requestID", Arrays.asList());
+        modifyFilterRuleValidateFailure("requestID", Arrays.asList());
     }
 
     /**
@@ -401,9 +373,7 @@ public class MdcTopicFilterTest {
      */
     @Test(expected = IllegalArgumentException.class)
     public void modifyFilterRuleMissingKeyStringPathTest() {
-        String topicFilterProp = "requestID=$.requestID";
-        MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
-        topicFilter.modifyFilterRule("request-id", "$.request-id");
+        modifyFilterRuleValidateFailure("request-id", "$.request-id");
     }
 
     /**
@@ -412,9 +382,7 @@ public class MdcTopicFilterTest {
      */
     @Test(expected = IllegalArgumentException.class)
     public void modifyFilterRuleMissingKeyPathListTest() {
-        String topicFilterProp = "requestID=$.requestID";
-        MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
-        topicFilter.modifyFilterRule("request-id", Arrays.asList("$.request-id"));
+        modifyFilterRuleValidateFailure("request-id", Arrays.asList("$.request-id"));
     }
 
 
@@ -423,9 +391,7 @@ public class MdcTopicFilterTest {
      */
     @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"));
+        modifyFilterRuleValidateFailure(null, "request-id", Arrays.asList("$.request-id"));
     }
 
     /**
@@ -433,9 +399,7 @@ public class MdcTopicFilterTest {
      */
     @Test(expected = IllegalArgumentException.class)
     public void modifyFilterRuleEmptyOldKeyTest() {
-        String topicFilterProp = "requestID=$.requestID";
-        MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
-        topicFilter.modifyFilterRule("", "request-id", Arrays.asList("$.request-id"));
+        modifyFilterRuleValidateFailure("", "request-id", Arrays.asList("$.request-id"));
     }
 
     /**
@@ -443,9 +407,7 @@ public class MdcTopicFilterTest {
      */
     @Test(expected = IllegalArgumentException.class)
     public void modifyFilterRuleNullNewKeyTest() {
-        String topicFilterProp = "requestID=$.requestID";
-        MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
-        topicFilter.modifyFilterRule("requestID", null, Arrays.asList("$.request-id"));
+        modifyFilterRuleValidateFailure("requestID", null, Arrays.asList("$.request-id"));
     }
 
     /**
@@ -453,9 +415,7 @@ public class MdcTopicFilterTest {
      */
     @Test(expected = IllegalArgumentException.class)
     public void modifyFilterRuleEmptyNewKeyTest() {
-        String topicFilterProp = "requestID=$.requestID";
-        MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
-        topicFilter.modifyFilterRule("requestID", "", Arrays.asList("$.request-id"));
+        modifyFilterRuleValidateFailure("requestID", "", Arrays.asList("$.request-id"));
     }
 
     /**
@@ -463,10 +423,7 @@ public class MdcTopicFilterTest {
      */
     @Test(expected = IllegalArgumentException.class)
     public void modifyFilterRuleSameKeyTest() {
-        String topicFilterProp = "requestID=$.requestID";
-        MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
-        topicFilter.modifyFilterRule("requestID", "requestID",
-                Arrays.asList("$.request-id"));
+        modifyFilterRuleValidateFailure("requestID", "requestID", Arrays.asList("$.request-id"));
     }
 
     /**
@@ -474,9 +431,7 @@ public class MdcTopicFilterTest {
      */
     @Test(expected = IllegalArgumentException.class)
     public void modifyFilterRuleEmptyPathsTest() {
-        String topicFilterProp = "requestID=$.requestID";
-        MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
-        topicFilter.modifyFilterRule("requestID", "request-id", Arrays.asList());
+        modifyFilterRuleValidateFailure("requestID", "request-id", Arrays.asList());
     }
 
     /**
@@ -485,9 +440,7 @@ public class MdcTopicFilterTest {
      */
     @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"));
+        modifyFilterRuleValidateFailure("request-id", "id", Arrays.asList("$.request-id"));
     }
 
     /**
@@ -658,4 +611,34 @@ public class MdcTopicFilterTest {
         rule.addPaths(Arrays.asList("pathD", "pathE"));
         assertEquals("[pathA, pathB, pathC, pathD, pathE]", rule.getPaths().toString());
     }
+
+    private void addFilterRuleValidateFailure(String mdcKey, String path) {
+        String topicFilterProp = "requestID=$.requestID";
+        MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
+        topicFilter.addFilterRule(mdcKey, path);
+    }
+
+    private void addFilterRuleValidateFailure(String mdcKey, List<String> paths) {
+        String topicFilterProp = "requestID=$.requestID";
+        MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
+        topicFilter.addFilterRule(mdcKey, paths);
+    }
+
+    private void modifyFilterRuleValidateFailure(String mdcKey, String path) {
+        String topicFilterProp = "requestID=$.requestID";
+        MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
+        topicFilter.modifyFilterRule(mdcKey, path);
+    }
+
+    private void modifyFilterRuleValidateFailure(String mdcKey, List<String> paths) {
+        String topicFilterProp = "requestID=$.requestID";
+        MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
+        topicFilter.modifyFilterRule(mdcKey, paths);
+    }
+
+    private void modifyFilterRuleValidateFailure(String oldMdcKey, String newMdcKey, List<String> paths) {
+        String topicFilterProp = "requestID=$.requestID";
+        MdcTopicFilter topicFilter = new MdcTopicFilter(topicFilterProp);
+        topicFilter.modifyFilterRule(oldMdcKey, newMdcKey, paths);
+    }
 }
index 3d93939..f2277be 100644 (file)
@@ -2,14 +2,14 @@
  * ============LICENSE_START=======================================================
  * ONAP
  * ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018, 2020 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.
@@ -43,7 +43,7 @@ import org.slf4j.LoggerFactory;
 
 /**
  * A state in the finite state machine.
- * 
+ *
  * <p>A state may have several timers associated with it, which must be cancelled whenever
  * the state is changed. Assumes that timers are not continuously added to the same state.
  */
@@ -63,7 +63,7 @@ public abstract class State {
 
     /**
      * Constructor.
-     * 
+     *
      * @param mgr pooling manager
      */
     public State(PoolingManager mgr) {
@@ -74,7 +74,7 @@ public abstract class State {
      * Gets the server-side filter to use when polling the DMaaP internal topic. The
      * default method returns a filter that accepts messages on the admin channel and on
      * the host's own channel.
-     * 
+     *
      * @return the server-side filter to use.
      */
     @SuppressWarnings("unchecked")
@@ -98,7 +98,7 @@ public abstract class State {
 
     /**
      * Transitions to the "start" state.
-     * 
+     *
      * @return the new state
      */
     public final State goStart() {
@@ -107,7 +107,7 @@ public abstract class State {
 
     /**
      * Transitions to the "query" state.
-     * 
+     *
      * @return the new state
      */
     public State goQuery() {
@@ -116,7 +116,7 @@ public abstract class State {
 
     /**
      * Goes active with a new set of assignments.
-     * 
+     *
      * @param asgn new assignments
      * @return the new state, either Active or Inactive, depending on whether or not this
      *         host has an assignment
@@ -134,7 +134,7 @@ public abstract class State {
 
     /**
      * Transitions to the "inactive" state.
-     * 
+     *
      * @return the new state
      */
     protected State goInactive() {
@@ -144,25 +144,26 @@ public abstract class State {
     /**
      * Processes a message. The default method passes it to the manager to handle and
      * returns {@code null}.
-     * 
+     *
      * @param msg message to be processed
      * @return the new state, or {@code null} if the state is unchanged
      */
     public State process(Forward msg) {
-        if (!getHost().equals(msg.getChannel())) {
+        if (getHost().equals(msg.getChannel())) {
+            logger.info("received Forward message from {} on topic {}", msg.getSource(), getTopic());
+            mgr.handle(msg);
+
+        } else {
             logger.info("discard Forward message to {} from {} on topic {}", msg.getChannel(), msg.getSource(),
                             getTopic());
-            return null;
         }
 
-        logger.info("received Forward message from {} on topic {}", msg.getSource(), getTopic());
-        mgr.handle(msg);
         return null;
     }
 
     /**
      * Processes a message. The default method just returns {@code null}.
-     * 
+     *
      * @param msg message to be processed
      * @return the new state, or {@code null} if the state is unchanged
      */
@@ -173,7 +174,7 @@ public abstract class State {
 
     /**
      * Processes a message. The default method just returns {@code null}.
-     * 
+     *
      * @param msg message to be processed
      * @return the new state, or {@code null} if the state is unchanged
      */
@@ -185,7 +186,7 @@ public abstract class State {
     /**
      * Processes a message. The default method copies the assignments and then returns
      * {@code null}.
-     * 
+     *
      * @param msg message to be processed
      * @return the new state, or {@code null} if the state is unchanged
      */
@@ -200,7 +201,7 @@ public abstract class State {
 
     /**
      * Processes a message. The default method just returns {@code null}.
-     * 
+     *
      * @param msg message to be processed
      * @return the new state, or {@code null} if the state is unchanged
      */
@@ -211,7 +212,7 @@ public abstract class State {
 
     /**
      * Processes a message. The default method just returns {@code null}.
-     * 
+     *
      * @param msg message to be processed
      * @return the new state, or {@code null} if the state is unchanged
      */
@@ -222,7 +223,7 @@ public abstract class State {
 
     /**
      * Determines if a message is valid and did not originate from this host.
-     * 
+     *
      * @param msg message to be validated
      * @return {@code true} if the message is valid, {@code false} otherwise
      */
@@ -252,7 +253,7 @@ public abstract class State {
 
     /**
      * Publishes a message.
-     * 
+     *
      * @param msg message to be published
      */
     protected final void publish(Identification msg) {
@@ -261,7 +262,7 @@ public abstract class State {
 
     /**
      * Publishes a message.
-     * 
+     *
      * @param msg message to be published
      */
     protected final void publish(Leader msg) {
@@ -270,7 +271,7 @@ public abstract class State {
 
     /**
      * Publishes a message.
-     * 
+     *
      * @param msg message to be published
      */
     protected final void publish(Offline msg) {
@@ -279,7 +280,7 @@ public abstract class State {
 
     /**
      * Publishes a message.
-     * 
+     *
      * @param msg message to be published
      */
     protected final void publish(Query msg) {
@@ -288,7 +289,7 @@ public abstract class State {
 
     /**
      * Publishes a message on the specified channel.
-     * 
+     *
      * @param channel channel
      * @param msg message to be published
      */
@@ -298,7 +299,7 @@ public abstract class State {
 
     /**
      * Publishes a message on the specified channel.
-     * 
+     *
      * @param channel channel
      * @param msg message to be published
      */
@@ -308,7 +309,7 @@ public abstract class State {
 
     /**
      * Starts distributing messages using the specified bucket assignments.
-     * 
+     *
      * @param assignments assignments
      */
     protected final void startDistributing(BucketAssignments assignments) {
@@ -319,7 +320,7 @@ public abstract class State {
 
     /**
      * Schedules a timer to fire after a delay.
-     * 
+     *
      * @param delayMs delay in ms
      * @param task task
      */
@@ -329,7 +330,7 @@ public abstract class State {
 
     /**
      * Schedules a timer to fire repeatedly.
-     * 
+     *
      * @param initialDelayMs initial delay ms
      * @param delayMs delay ms
      * @param task task
@@ -342,7 +343,7 @@ public abstract class State {
      * Indicates that we failed to see our own heartbeat; must be a problem with the
      * internal topic. Assumes the problem is temporary and continues to use the current
      * bucket assignments.
-     * 
+     *
      * @return a new {@link StartState}
      */
     protected final State missedHeartbeat() {
@@ -354,7 +355,7 @@ public abstract class State {
     /**
      * Indicates that the internal topic failed; this should only be invoked from the
      * StartState. Discards bucket assignments and begins processing everything locally.
-     * 
+     *
      * @return a new {@link InactiveState}
      */
     protected final State internalTopicFailed() {
@@ -366,9 +367,9 @@ public abstract class State {
 
     /**
      * Makes a heart beat message.
-     * 
+     *
      * @param timestampMs time, in milliseconds, associated with the message
-     * 
+     *
      * @return a new message
      */
     protected final Heartbeat makeHeartbeat(long timestampMs) {
@@ -377,7 +378,7 @@ public abstract class State {
 
     /**
      * Makes an Identification message.
-     * 
+     *
      * @return a new message
      */
     protected Identification makeIdentification() {
@@ -386,7 +387,7 @@ public abstract class State {
 
     /**
      * Makes an "offline" message.
-     * 
+     *
      * @return a new message
      */
     protected final Offline makeOffline() {
@@ -395,7 +396,7 @@ public abstract class State {
 
     /**
      * Makes a query message.
-     * 
+     *
      * @return a new message
      */
     protected final Query makeQuery() {
index bd3d90b..2a0066b 100644 (file)
@@ -640,27 +640,17 @@ public class PoolingManagerImplTest {
 
     @Test
     public void testBeforeInsert_NoIntercept() throws Exception {
-        startMgr();
-
-        assertFalse(mgr.beforeInsert(CommInfrastructure.UEB, TOPIC2, THE_EVENT, DECODED_EVENT));
+        validateUnhandled(CommInfrastructure.UEB);
     }
 
     @Test
     public void testHandleExternalCommInfrastructureStringStringString_NullReqId() throws Exception {
-        startMgr();
-
-        when(extractors.extract(any())).thenReturn(null);
-
-        assertFalse(mgr.beforeInsert(CommInfrastructure.UEB, TOPIC2, THE_EVENT, DECODED_EVENT));
+        validateHandleReqId(null);
     }
 
     @Test
     public void testHandleExternalCommInfrastructureStringStringString_EmptyReqId() throws Exception {
-        startMgr();
-
-        when(extractors.extract(any())).thenReturn("");
-
-        assertFalse(mgr.beforeInsert(CommInfrastructure.UEB, TOPIC2, THE_EVENT, DECODED_EVENT));
+        validateHandleReqId("");
     }
 
     @Test
@@ -672,50 +662,28 @@ public class PoolingManagerImplTest {
 
     @Test
     public void testHandleExternalCommInfrastructureStringStringString() throws Exception {
-        startMgr();
-
-        assertFalse(mgr.beforeInsert(CommInfrastructure.UEB, TOPIC2, THE_EVENT, DECODED_EVENT));
+        validateUnhandled(CommInfrastructure.UEB);
     }
 
     @Test
     public void testHandleExternalForward_NoAssignments() throws Exception {
-        startMgr();
-
-        assertFalse(mgr.beforeInsert(CommInfrastructure.UEB, TOPIC2, THE_EVENT, DECODED_EVENT));
+        validateUnhandled(CommInfrastructure.UEB);
     }
 
     @Test
     public void testHandleExternalForward() throws Exception {
-        startMgr();
-
-        // route the message to this host
-        mgr.startDistributing(makeAssignments(true));
-
-        assertFalse(mgr.beforeInsert(CommInfrastructure.UEB, TOPIC2, THE_EVENT, DECODED_EVENT));
+        validateNoForward();
     }
 
     @Test
     public void testHandleEvent_NullTarget() throws Exception {
-        startMgr();
-
         // buckets have null targets
-        mgr.startDistributing(new BucketAssignments(new String[] {null, null}));
-
-        assertTrue(mgr.beforeInsert(CommInfrastructure.UEB, TOPIC2, THE_EVENT, DECODED_EVENT));
-
-        verify(dmaap, times(START_PUB)).publish(any());
+        validateHandled(new BucketAssignments(new String[] {null, null}), START_PUB);
     }
 
     @Test
     public void testHandleEvent_SameHost() throws Exception {
-        startMgr();
-
-        // route the message to this host
-        mgr.startDistributing(makeAssignments(true));
-
-        assertFalse(mgr.beforeInsert(CommInfrastructure.UEB, TOPIC2, THE_EVENT, DECODED_EVENT));
-
-        verify(dmaap, times(START_PUB)).publish(any());
+        validateNoForward();
     }
 
     @Test
@@ -736,14 +704,7 @@ public class PoolingManagerImplTest {
 
     @Test
     public void testHandleEvent_DiffHost_Forward() throws Exception {
-        startMgr();
-
-        // route the message to the *OTHER* host
-        mgr.startDistributing(makeAssignments(false));
-
-        assertTrue(mgr.beforeInsert(CommInfrastructure.UEB, TOPIC2, THE_EVENT, DECODED_EVENT));
-
-        verify(dmaap, times(START_PUB + 1)).publish(any());
+        validateHandled(makeAssignments(false), START_PUB + 1);
     }
 
     @Test
@@ -755,11 +716,7 @@ public class PoolingManagerImplTest {
 
     @Test
     public void testExtractRequestId_NullReqId() throws Exception {
-        startMgr();
-
-        when(extractors.extract(any())).thenReturn(null);
-
-        assertFalse(mgr.beforeInsert(CommInfrastructure.UEB, TOPIC2, THE_EVENT, DECODED_EVENT));
+        validateHandleReqId(null);
     }
 
     @Test
@@ -1009,12 +966,7 @@ public class PoolingManagerImplTest {
 
     @Test
     public void testStartDistributing() throws Exception {
-        startMgr();
-
-        // route the message to this host
-        mgr.startDistributing(makeAssignments(true));
-        assertFalse(mgr.beforeInsert(CommInfrastructure.UEB, TOPIC2, THE_EVENT, DECODED_EVENT));
-        verify(dmaap, times(START_PUB)).publish(any());
+        validateNoForward();
 
 
         // null assignments should cause message to be processed locally
@@ -1133,6 +1085,41 @@ public class PoolingManagerImplTest {
         assertEquals(1, latch.getCount());
     }
 
+    private void validateHandleReqId(String requestId) throws PoolingFeatureException {
+        startMgr();
+
+        when(extractors.extract(any())).thenReturn(requestId);
+
+        assertFalse(mgr.beforeInsert(CommInfrastructure.UEB, TOPIC2, THE_EVENT, DECODED_EVENT));
+    }
+
+    private void validateNoForward() throws PoolingFeatureException {
+        startMgr();
+
+        // route the message to this host
+        mgr.startDistributing(makeAssignments(true));
+
+        assertFalse(mgr.beforeInsert(CommInfrastructure.UEB, TOPIC2, THE_EVENT, DECODED_EVENT));
+
+        verify(dmaap, times(START_PUB)).publish(any());
+    }
+
+    private void validateHandled(BucketAssignments assignments, int publishCount) throws PoolingFeatureException {
+        startMgr();
+
+        // route the message to the *OTHER* host
+        mgr.startDistributing(assignments);
+
+        assertTrue(mgr.beforeInsert(CommInfrastructure.UEB, TOPIC2, THE_EVENT, DECODED_EVENT));
+
+        verify(dmaap, times(publishCount)).publish(any());
+    }
+
+    private void validateUnhandled(CommInfrastructure infra) throws PoolingFeatureException {
+        startMgr();
+        assertFalse(mgr.beforeInsert(infra, TOPIC2, THE_EVENT, DECODED_EVENT));
+    }
+
     /**
      * Configure the mock controller to act like a real controller, invoking beforeOffer
      * and then beforeInsert, so we can make sure they pass through. We'll keep count to
index 0b97dd7..ad01870 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * feature-simulators
  * ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2020 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.
@@ -24,14 +24,12 @@ import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.fail;
 
-import java.io.BufferedReader;
-import java.io.DataOutputStream;
 import java.io.IOException;
-import java.io.InputStreamReader;
 import java.net.HttpURLConnection;
 import java.net.URL;
-import java.net.URLConnection;
 import java.nio.charset.StandardCharsets;
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.lang3.tuple.Pair;
 import org.junit.AfterClass;
 import org.junit.BeforeClass;
 import org.junit.Test;
@@ -72,290 +70,131 @@ public class DMaaPSimulatorTest {
     }
 
     @Test
-    public void testGetNoData() {
-        int timeout = 1000;
-        Pair<Integer, String> response = dmaapGet("myTopicNoData", timeout);
-        assertNotNull(response);
-        assertNotNull(response.first);
-        assertEquals(DMaaPSimulatorJaxRs.NO_TOPIC_MSG, response.second);
+    public void testGetNoData() throws IOException {
+        validateResponse(DMaaPSimulatorJaxRs.NO_TOPIC_MSG, dmaapGet("myTopicNoData", 1000));
     }
 
     @Test
-    public void testSinglePost() {
+    public void testSinglePost() throws IOException {
         String myTopic = "myTopicSinglePost";
         String testData = "This is some test data";
-        Pair<Integer, String> response = dmaapPost(myTopic, testData);
-        assertNotNull(response);
-        assertNotNull(response.first);
-        assertNotNull(response.second);
 
-        response = dmaapGet(myTopic, 1000);
-        assertNotNull(response);
-        assertNotNull(response.first);
-        assertEquals(testData, response.second);
+        validateResponse(dmaapPost(myTopic, testData));
+
+        validateResponse(testData, dmaapGet(myTopic, 1000));
     }
 
     @Test
-    public void testOneTopicMultiPost() {
+    public void testOneTopicMultiPost() throws IOException {
         String[] data = {"data point 1", "data point 2", "something random"};
         String myTopic = "myTopicMultiPost";
-        Pair<Integer, String> response = dmaapPost(myTopic, data[0]);
-        assertNotNull(response);
-        assertNotNull(response.first);
-        assertNotNull(response.second);
 
-        response = dmaapPost(myTopic, data[1]);
-        assertNotNull(response);
-        assertNotNull(response.first);
-        assertNotNull(response.second);
+        validateResponse(dmaapPost(myTopic, data[0]));
+        validateResponse(dmaapPost(myTopic, data[1]));
+        validateResponse(dmaapPost(myTopic, data[2]));
 
-        response = dmaapPost(myTopic, data[2]);
-        assertNotNull(response);
-        assertNotNull(response.first);
-        assertNotNull(response.second);
-
-        response = dmaapGet(myTopic, 1000);
-        assertNotNull(response);
-        assertNotNull(response.first);
-        assertEquals(data[0], response.second);
-
-        response = dmaapGet(myTopic, 1000);
-        assertNotNull(response);
-        assertNotNull(response.first);
-        assertEquals(data[1], response.second);
-
-        response = dmaapGet(myTopic, 1000);
-        assertNotNull(response);
-        assertNotNull(response.first);
-        assertEquals(data[2], response.second);
+        validateResponse(data[0], dmaapGet(myTopic, 1000));
+        validateResponse(data[1], dmaapGet(myTopic, 1000));
+        validateResponse(data[2], dmaapGet(myTopic, 1000));
     }
 
     @Test
-    public void testMultiTopic() {
+    public void testMultiTopic() throws IOException {
         String[][] data = {{"Topic one message one", "Topic one message two"},
             {"Topic two message one", "Topic two message two"}};
         String[] topics = {"topic1", "topic2"};
 
-        Pair<Integer, String> response = dmaapPost(topics[0], data[0][0]);
-        assertNotNull(response);
-        assertNotNull(response.first);
-        assertNotNull(response.second);
-
-        response = dmaapGet(topics[0], 1000);
-        assertNotNull(response);
-        assertNotNull(response.first);
-        assertEquals(data[0][0], response.second);
-
-        response = dmaapGet(topics[1], 1000);
-        assertNotNull(response);
-        assertNotNull(response.first);
-        assertEquals(DMaaPSimulatorJaxRs.NO_TOPIC_MSG, response.second);
-
-        response = dmaapPost(topics[1], data[1][0]);
-        assertNotNull(response);
-        assertNotNull(response.first);
-        assertNotNull(response.second);
-
-        response = dmaapPost(topics[1], data[1][1]);
-        assertNotNull(response);
-        assertNotNull(response.first);
-        assertNotNull(response.second);
-
-        response = dmaapPost(topics[0], data[0][1]);
-        assertNotNull(response);
-        assertNotNull(response.first);
-        assertNotNull(response.second);
-
-        response = dmaapGet(topics[1], 1000);
-        assertNotNull(response);
-        assertNotNull(response.first);
-        assertEquals(data[1][0], response.second);
+        validateResponse(dmaapPost(topics[0], data[0][0]));
 
-        response = dmaapGet(topics[0], 1000);
-        assertNotNull(response);
-        assertNotNull(response.first);
-        assertEquals(data[0][1], response.second);
+        validateResponse(data[0][0], dmaapGet(topics[0], 1000));
+        validateResponse(DMaaPSimulatorJaxRs.NO_TOPIC_MSG, dmaapGet(topics[1], 1000));
 
-        response = dmaapGet(topics[1], 1000);
-        assertNotNull(response);
-        assertNotNull(response.first);
-        assertEquals(data[1][1], response.second);
+        validateResponse(dmaapPost(topics[1], data[1][0]));
+        validateResponse(dmaapPost(topics[1], data[1][1]));
+        validateResponse(dmaapPost(topics[0], data[0][1]));
 
-        response = dmaapGet(topics[0], 1000);
-        assertNotNull(response);
-        assertNotNull(response.first);
-        assertEquals(DMaaPSimulatorJaxRs.NO_DATA_MSG, response.second);
+        validateResponse(data[1][0], dmaapGet(topics[1], 1000));
+        validateResponse(data[0][1], dmaapGet(topics[0], 1000));
+        validateResponse(data[1][1], dmaapGet(topics[1], 1000));
+        validateResponse(DMaaPSimulatorJaxRs.NO_DATA_MSG, dmaapGet(topics[0], 1000));
     }
 
     @Test
-    public void testResponseCode() {
-        Pair<Integer, String> response = dmaapPost("myTopic", "myTopicData");
-        assertNotNull(response);
-        assertNotNull(response.first);
-        assertNotNull(response.second);
+    public void testResponseCode() throws IOException {
+        validateResponse(dmaapPost("myTopic", "myTopicData"));
 
-        response = setStatus(503);
-        assertNotNull(response);
-        assertNotNull(response.first);
-        assertNotNull(response.second);
+        validateResponse(setStatus(503));
+        validateResponse(503, "You got response code: 503", dmaapGet("myTopic", 500));
+
+        validateResponse(setStatus(202));
+        validateResponse(202, "myTopicData", dmaapGet("myTopic", 500));
+    }
 
-        response = dmaapGet("myTopic", 500);
+    private void validateResponse(Pair<Integer, String> response) {
         assertNotNull(response);
-        assertEquals(503, response.first.intValue());
-        assertEquals("You got response code: 503", response.second);
+        assertNotNull(response.getLeft());
+        assertNotNull(response.getRight());
+    }
 
-        response = setStatus(202);
+    private void validateResponse(int expectedCode, String expectedResponse, Pair<Integer, String> response) {
         assertNotNull(response);
-        assertNotNull(response.first);
-        assertNotNull(response.second);
+        assertEquals(expectedCode, response.getLeft().intValue());
+        assertEquals(expectedResponse, response.getRight());
+    }
 
-        response = dmaapGet("myTopic", 500);
+    private void validateResponse(String expectedResponse, Pair<Integer, String> response) {
         assertNotNull(response);
-        assertEquals(202, response.first.intValue());
-        assertEquals("myTopicData", response.second);
+        assertNotNull(response.getLeft());
+        assertEquals(expectedResponse, response.getRight());
     }
 
-    private static Pair<Integer, String> dmaapGet(String topic, int timeout) {
+    private static Pair<Integer, String> dmaapGet(String topic, int timeout) throws IOException {
         return dmaapGet(topic, "1", "1", timeout);
     }
 
-    private static Pair<Integer, String> dmaapGet(String topic, String consumerGroup, String consumerId, int timeout) {
+    private static Pair<Integer, String> dmaapGet(String topic, String consumerGroup, String consumerId, int timeout)
+                    throws IOException {
         String url = "http://localhost:" + DMAAPSIM_SERVER_PORT + "/events/" + topic + "/" + consumerGroup + "/"
                 + consumerId + "?timeout=" + timeout;
-        try {
-            URLConnection conn = new URL(url).openConnection();
-            HttpURLConnection httpConn = null;
-            if (conn instanceof HttpURLConnection) {
-                httpConn = (HttpURLConnection) conn;
-            } else {
-                fail("connection not set up right");
-            }
-            httpConn.setRequestMethod("GET");
-            httpConn.connect();
-            String response = "";
-            try (BufferedReader connReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream()))) {
-                String line;
-                while ((line = connReader.readLine()) != null) {
-                    response += line;
-                }
-                httpConn.disconnect();
-                return new Pair<Integer, String>(httpConn.getResponseCode(), response);
-            } catch (IOException e) {
-                if (e.getMessage().startsWith("Server returned HTTP response code")) {
-                    System.out.println("hi");
-                    BufferedReader connReader = new BufferedReader(new InputStreamReader(httpConn.getErrorStream()));
-                    String line;
-                    while ((line = connReader.readLine()) != null) {
-                        response += line;
-                    }
-                    httpConn.disconnect();
-                    return new Pair<Integer, String>(httpConn.getResponseCode(), response);
-                } else {
-                    fail("we got an exception: " + e);
-                }
-            }
-        } catch (Exception e) {
-            fail("we got an exception" + e);
-        }
-
-        return null;
+        HttpURLConnection httpConn = (HttpURLConnection) new URL(url).openConnection();
+        httpConn.setRequestMethod("GET");
+        httpConn.connect();
+        return getResponse(httpConn);
     }
 
-    private static Pair<Integer, String> dmaapPost(String topic, String data) {
+    private static Pair<Integer, String> dmaapPost(String topic, String data) throws IOException {
         String url = "http://localhost:" + DMAAPSIM_SERVER_PORT + "/events/" + topic;
         byte[] postData = data.getBytes(StandardCharsets.UTF_8);
-        try {
-            URLConnection conn = new URL(url).openConnection();
-            HttpURLConnection httpConn = null;
-            if (conn instanceof HttpURLConnection) {
-                httpConn = (HttpURLConnection) conn;
-            } else {
-                fail("connection not set up right");
-            }
-            httpConn.setRequestMethod("POST");
-            httpConn.setDoOutput(true);
-            httpConn.setRequestProperty("Content-Type", "text/plain");
-            httpConn.setRequestProperty("Content-Length", "" + postData.length);
-            httpConn.connect();
-            String response = "";
-            try (DataOutputStream connWriter = new DataOutputStream(httpConn.getOutputStream())) {
-                connWriter.write(postData);
-                connWriter.flush();
-            }
-            try (BufferedReader connReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream()))) {
-                String line;
-                while ((line = connReader.readLine()) != null) {
-                    response += line;
-                }
-                httpConn.disconnect();
-                return new Pair<Integer, String>(httpConn.getResponseCode(), response);
-            } catch (IOException e) {
-                if (e.getMessage().startsWith("Server returned HTTP response code")) {
-                    System.out.println("hi");
-                    BufferedReader connReader = new BufferedReader(new InputStreamReader(httpConn.getErrorStream()));
-                    String line;
-                    while ((line = connReader.readLine()) != null) {
-                        response += line;
-                    }
-                    httpConn.disconnect();
-                    return new Pair<Integer, String>(httpConn.getResponseCode(), response);
-                } else {
-                    fail("we got an exception: " + e);
-                }
-            }
-        } catch (Exception e) {
-            fail("we got an exception: " + e);
-        }
-        return null;
+        HttpURLConnection httpConn = (HttpURLConnection) new URL(url).openConnection();
+        httpConn.setRequestMethod("POST");
+        httpConn.setDoOutput(true);
+        httpConn.setRequestProperty("Content-Type", "text/plain");
+        httpConn.setRequestProperty("Content-Length", "" + postData.length);
+        httpConn.connect();
+        IOUtils.write(postData, httpConn.getOutputStream());
+        return getResponse(httpConn);
     }
 
-    private static Pair<Integer, String> setStatus(int status) {
+    private static Pair<Integer, String> setStatus(int status) throws IOException {
         String url = "http://localhost:" + DMAAPSIM_SERVER_PORT + "/events/setStatus?statusCode=" + status;
-        try {
-            URLConnection conn = new URL(url).openConnection();
-            HttpURLConnection httpConn = null;
-            if (conn instanceof HttpURLConnection) {
-                httpConn = (HttpURLConnection) conn;
-            } else {
-                fail("connection not set up right");
-            }
-            httpConn.setRequestMethod("POST");
-            httpConn.connect();
-            String response = "";
-            try (BufferedReader connReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream()))) {
-                String line;
-                while ((line = connReader.readLine()) != null) {
-                    response += line;
-                }
-                httpConn.disconnect();
-                return new Pair<Integer, String>(httpConn.getResponseCode(), response);
-            } catch (IOException e) {
-                if (e.getMessage().startsWith("Server returned HTTP response code")) {
-                    System.out.println("hi");
-                    BufferedReader connReader = new BufferedReader(new InputStreamReader(httpConn.getErrorStream()));
-                    String line;
-                    while ((line = connReader.readLine()) != null) {
-                        response += line;
-                    }
-                    httpConn.disconnect();
-                    return new Pair<Integer, String>(httpConn.getResponseCode(), response);
-                } else {
-                    fail("we got an exception: " + e);
-                }
-            }
-        } catch (Exception e) {
-            fail("we got an exception" + e);
-        }
-        return null;
+        HttpURLConnection httpConn = (HttpURLConnection) new URL(url).openConnection();
+        httpConn.setRequestMethod("POST");
+        httpConn.connect();
+        return getResponse(httpConn);
     }
 
-    private static class Pair<A, B> {
-        public final A first;
-        public final B second;
+    private static Pair<Integer, String> getResponse(HttpURLConnection httpConn) throws IOException {
+        try {
+            String response = IOUtils.toString(httpConn.getInputStream(), StandardCharsets.UTF_8);
+            return Pair.of(httpConn.getResponseCode(), response);
+
+        } catch (IOException e) {
+            if (e.getMessage().startsWith("Server returned HTTP response code")) {
+                String response = IOUtils.toString(httpConn.getErrorStream(), StandardCharsets.UTF_8);
+                return Pair.of(httpConn.getResponseCode(), response);
+            }
 
-        public Pair(A first, B second) {
-            this.first = first;
-            this.second = second;
+            throw e;
         }
     }
 }
index 6547ca7..5bce350 100644 (file)
@@ -537,7 +537,12 @@ public class PolicyContainer implements Startable {
      * {@inheritDoc}.
      */
     @Override
-    public synchronized boolean start() {
+    public synchronized boolean start() {   // NOSONAR
+        /*
+         * disabling sonar about returning the same value, because we prefer the code to
+         * be structured this way
+         */
+
         if (isStarted) {
             return true;
         }
index 0b959f0..6b669a2 100644 (file)
@@ -600,20 +600,17 @@ public class AggregatedPolicyControllerTest {
 
     @Test(expected = IllegalArgumentException.class)
     public void testDeliver_NullTopic() {
-        apc.start();
-        apc.deliver(CommInfrastructure.NOOP, null, MY_EVENT);
+        validateDeliverFailure(null, MY_EVENT);
     }
 
     @Test(expected = IllegalArgumentException.class)
     public void testDeliver_EmptyTopic() {
-        apc.start();
-        apc.deliver(CommInfrastructure.NOOP, "", MY_EVENT);
+        validateDeliverFailure("", MY_EVENT);
     }
 
     @Test(expected = IllegalArgumentException.class)
     public void testDeliver_NullEvent() {
-        apc.start();
-        apc.deliver(CommInfrastructure.NOOP, SINK_TOPIC1, null);
+        validateDeliverFailure(SINK_TOPIC1, null);
     }
 
     @Test(expected = IllegalStateException.class)
@@ -788,6 +785,11 @@ public class AggregatedPolicyControllerTest {
         assertTrue(apc.toString().startsWith("AggregatedPolicyController ["));
     }
 
+    private void validateDeliverFailure(String topic, String event) {
+        apc.start();
+        apc.deliver(CommInfrastructure.NOOP, topic, event);
+    }
+
     /**
      * Performs an operation that has a beforeXxx method and an afterXxx method. Tries
      * combinations where beforeXxx and afterXxx return {@code true} and {@code false}.
index 82a2b2e..213c1c6 100644 (file)
@@ -47,38 +47,49 @@ public class MdcTransactionTest {
 
         assertNullSubTransactionFields(trans);
 
-        assertNotNull(MDC.get(MdcTransactionConstants.REQUEST_ID));
-        assertNotNull(MDC.get(MdcTransactionConstants.PARTNER_NAME));
-        assertNotNull(MDC.get(MdcTransactionConstants.VIRTUAL_SERVER_NAME));
-        assertNotNull(MDC.get(MdcTransactionConstants.SERVER));
-        assertNotNull(MDC.get(MdcTransactionConstants.SERVER_IP_ADDRESS));
-        assertNotNull(MDC.get(MdcTransactionConstants.SERVER_FQDN));
-        assertNotNull(MDC.get(MdcTransactionConstants.SERVICE_NAME));
-
-        assertNull(MDC.get(MdcTransactionConstants.INVOCATION_ID));
-        assertNull(MDC.get(MdcTransactionConstants.BEGIN_TIMESTAMP));
-        assertNull(MDC.get(MdcTransactionConstants.END_TIMESTAMP));
-        assertNull(MDC.get(MdcTransactionConstants.ELAPSED_TIME));
-        assertNull(MDC.get(MdcTransactionConstants.SERVICE_INSTANCE_ID));
-        assertNull(MDC.get(MdcTransactionConstants.INSTANCE_UUID));
-        assertNull(MDC.get(MdcTransactionConstants.PROCESS_KEY));
-        assertNull(MDC.get(MdcTransactionConstants.STATUS_CODE));
-        assertNull(MDC.get(MdcTransactionConstants.RESPONSE_CODE));
-        assertNull(MDC.get(MdcTransactionConstants.RESPONSE_DESCRIPTION));
-        assertNull(MDC.get(MdcTransactionConstants.SEVERITY));
-        assertNull(MDC.get(MdcTransactionConstants.TARGET_ENTITY));
-        assertNull(MDC.get(MdcTransactionConstants.TARGET_SERVICE_NAME));
-        assertNull(MDC.get(MdcTransactionConstants.TARGET_VIRTUAL_ENTITY));
-        assertNull(MDC.get(MdcTransactionConstants.CLIENT_IP_ADDRESS));
-        assertNull(MDC.get(MdcTransactionConstants.REMOTE_HOST));
+        assertNotNullKeys(
+            MdcTransactionConstants.REQUEST_ID,
+            MdcTransactionConstants.PARTNER_NAME,
+            MdcTransactionConstants.VIRTUAL_SERVER_NAME,
+            MdcTransactionConstants.SERVER,
+            MdcTransactionConstants.SERVER_IP_ADDRESS,
+            MdcTransactionConstants.SERVER_FQDN,
+            MdcTransactionConstants.SERVICE_NAME
+        );
+
+
+        assertNullKeys(
+            MdcTransactionConstants.INVOCATION_ID,
+            MdcTransactionConstants.BEGIN_TIMESTAMP,
+            MdcTransactionConstants.END_TIMESTAMP,
+            MdcTransactionConstants.ELAPSED_TIME,
+            MdcTransactionConstants.SERVICE_INSTANCE_ID,
+            MdcTransactionConstants.INSTANCE_UUID,
+            MdcTransactionConstants.PROCESS_KEY,
+            MdcTransactionConstants.STATUS_CODE,
+            MdcTransactionConstants.RESPONSE_CODE,
+            MdcTransactionConstants.RESPONSE_DESCRIPTION,
+            MdcTransactionConstants.SEVERITY,
+            MdcTransactionConstants.TARGET_ENTITY,
+            MdcTransactionConstants.TARGET_SERVICE_NAME,
+            MdcTransactionConstants.TARGET_VIRTUAL_ENTITY,
+            MdcTransactionConstants.CLIENT_IP_ADDRESS,
+            MdcTransactionConstants.REMOTE_HOST
+        );
 
-        assertEquals(trans.getRequestId(), MDC.get(MdcTransactionConstants.REQUEST_ID));
-        assertEquals(trans.getPartner(), MDC.get(MdcTransactionConstants.PARTNER_NAME));
-        assertEquals(trans.getVirtualServerName(), MDC.get(MdcTransactionConstants.VIRTUAL_SERVER_NAME));
-        assertEquals(trans.getServer(), MDC.get(MdcTransactionConstants.SERVER));
-        assertEquals(trans.getServerIpAddress(), MDC.get(MdcTransactionConstants.SERVER_IP_ADDRESS));
-        assertEquals(trans.getServerFqdn(), MDC.get(MdcTransactionConstants.SERVER_FQDN));
-        assertEquals(trans.getServiceName(), MDC.get(MdcTransactionConstants.SERVICE_NAME));
+        assertTransactionFields(trans);
+    }
+
+    private void assertNotNullKeys(String... notNullKeys) {
+        for (String key: notNullKeys) {
+            assertNotNull(key, MDC.get(key));
+        }
+    }
+
+    private void assertNullKeys(String... nullKeys) {
+        for (String key: nullKeys) {
+            assertNull(key, MDC.get(key));
+        }
     }
 
     private void assertNullSubTransactionFields(MdcTransaction trans) {
@@ -144,52 +155,51 @@ public class MdcTransactionTest {
 
         assertTransactionFields(trans);
 
-        assertNotNull(MDC.get(MdcTransactionConstants.INVOCATION_ID));
-        assertNotNull(MDC.get(MdcTransactionConstants.BEGIN_TIMESTAMP));
-        assertNotNull(MDC.get(MdcTransactionConstants.END_TIMESTAMP));
-        assertNotNull(MDC.get(MdcTransactionConstants.ELAPSED_TIME));
-        assertNotNull(MDC.get(MdcTransactionConstants.SERVICE_INSTANCE_ID));
-        assertNotNull(MDC.get(MdcTransactionConstants.INSTANCE_UUID));
-        assertNotNull(MDC.get(MdcTransactionConstants.PROCESS_KEY));
-        assertNotNull(MDC.get(MdcTransactionConstants.STATUS_CODE));
-        assertNotNull(MDC.get(MdcTransactionConstants.RESPONSE_CODE));
-        assertNotNull(MDC.get(MdcTransactionConstants.RESPONSE_DESCRIPTION));
-        assertNotNull(MDC.get(MdcTransactionConstants.SEVERITY));
-        assertNotNull(MDC.get(MdcTransactionConstants.TARGET_ENTITY));
-        assertNotNull(MDC.get(MdcTransactionConstants.TARGET_SERVICE_NAME));
-        assertNotNull(MDC.get(MdcTransactionConstants.TARGET_VIRTUAL_ENTITY));
-        assertNotNull(MDC.get(MdcTransactionConstants.CLIENT_IP_ADDRESS));
-        assertNotNull(MDC.get(MdcTransactionConstants.REMOTE_HOST));
+        assertNotNullKeys(
+            MdcTransactionConstants.INVOCATION_ID,
+            MdcTransactionConstants.BEGIN_TIMESTAMP,
+            MdcTransactionConstants.END_TIMESTAMP,
+            MdcTransactionConstants.ELAPSED_TIME,
+            MdcTransactionConstants.SERVICE_INSTANCE_ID,
+            MdcTransactionConstants.INSTANCE_UUID,
+            MdcTransactionConstants.PROCESS_KEY,
+            MdcTransactionConstants.STATUS_CODE,
+            MdcTransactionConstants.RESPONSE_CODE,
+            MdcTransactionConstants.RESPONSE_DESCRIPTION,
+            MdcTransactionConstants.SEVERITY,
+            MdcTransactionConstants.TARGET_ENTITY,
+            MdcTransactionConstants.TARGET_SERVICE_NAME,
+            MdcTransactionConstants.TARGET_VIRTUAL_ENTITY,
+            MdcTransactionConstants.CLIENT_IP_ADDRESS,
+            MdcTransactionConstants.REMOTE_HOST);
 
         assertEquals(trans.getInvocationId(), MDC.get(MdcTransactionConstants.INVOCATION_ID));
         assertEquals(trans.timestamp(trans.getStartTime()), MDC.get(MdcTransactionConstants.BEGIN_TIMESTAMP));
         assertEquals(trans.timestamp(trans.getEndTime()), MDC.get(MdcTransactionConstants.END_TIMESTAMP));
         assertEquals(String.valueOf(Duration.between(trans.getStartTime(), trans.getEndTime()).toMillis()),
             MDC.get(MdcTransactionConstants.ELAPSED_TIME));
-        assertEquals(trans.getServiceInstanceId(), MDC.get(MdcTransactionConstants.SERVICE_INSTANCE_ID));
         assertEquals(trans.getInstanceUuid(), MDC.get(MdcTransactionConstants.INSTANCE_UUID));
-        assertEquals(trans.getProcessKey(), MDC.get(MdcTransactionConstants.PROCESS_KEY));
-        assertEquals(trans.getStatusCode(), MDC.get(MdcTransactionConstants.STATUS_CODE));
-        assertEquals(trans.getResponseCode(), MDC.get(MdcTransactionConstants.RESPONSE_CODE));
-        assertEquals(trans.getResponseDescription(), MDC.get(MdcTransactionConstants.RESPONSE_DESCRIPTION));
-        assertEquals(trans.getSeverity(), MDC.get(MdcTransactionConstants.SEVERITY));
-        assertEquals(trans.getTargetEntity(), MDC.get(MdcTransactionConstants.TARGET_ENTITY));
-        assertEquals(trans.getTargetServiceName(), MDC.get(MdcTransactionConstants.TARGET_SERVICE_NAME));
-        assertEquals(trans.getTargetVirtualEntity(), MDC.get(MdcTransactionConstants.TARGET_VIRTUAL_ENTITY));
-        assertEquals(trans.getClientIpAddress(), MDC.get(MdcTransactionConstants.CLIENT_IP_ADDRESS));
-        assertEquals(trans.getRemoteHost(), MDC.get(MdcTransactionConstants.REMOTE_HOST));
-
-        assertEquals("service-instance-id", trans.getServiceInstanceId());
-        assertEquals("process-key", trans.getProcessKey());
-        assertEquals("status-code", trans.getStatusCode());
-        assertEquals("response-code", trans.getResponseCode());
-        assertEquals("response-description", trans.getResponseDescription());
-        assertEquals("severity", trans.getSeverity());
-        assertEquals("target-entity", trans.getTargetEntity());
-        assertEquals("target-service-name", trans.getTargetServiceName());
-        assertEquals("target-virtual-entity", trans.getTargetVirtualEntity());
-        assertEquals("client-ip-address", trans.getClientIpAddress());
-        assertEquals("remote-host", trans.getRemoteHost());
+
+        assertKeyEquals("service-instance-id", trans.getServiceInstanceId(),
+                        MdcTransactionConstants.SERVICE_INSTANCE_ID);
+        assertKeyEquals("process-key", trans.getProcessKey(), MdcTransactionConstants.PROCESS_KEY);
+        assertKeyEquals("status-code", trans.getStatusCode(), MdcTransactionConstants.STATUS_CODE);
+        assertKeyEquals("response-code", trans.getResponseCode(), MdcTransactionConstants.RESPONSE_CODE);
+        assertKeyEquals("response-description", trans.getResponseDescription(),
+                        MdcTransactionConstants.RESPONSE_DESCRIPTION);
+        assertKeyEquals("severity", trans.getSeverity(), MdcTransactionConstants.SEVERITY);
+        assertKeyEquals("target-entity", trans.getTargetEntity(), MdcTransactionConstants.TARGET_ENTITY);
+        assertKeyEquals("target-service-name", trans.getTargetServiceName(),
+                        MdcTransactionConstants.TARGET_SERVICE_NAME);
+        assertKeyEquals("target-virtual-entity", trans.getTargetVirtualEntity(),
+                        MdcTransactionConstants.TARGET_VIRTUAL_ENTITY);
+        assertKeyEquals("client-ip-address", trans.getClientIpAddress(), MdcTransactionConstants.CLIENT_IP_ADDRESS);
+        assertKeyEquals("remote-host", trans.getRemoteHost(), MdcTransactionConstants.REMOTE_HOST);
+    }
+
+    private void assertKeyEquals(String expected, String transValue, String mdcKey) {
+        assertEquals("trans." + expected, expected, transValue);
+        assertEquals("mdc." + expected, expected, MDC.get(mdcKey));
     }
 
     @Test